# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
502445 | Marceantasy | Race (IOI11_race) | C++17 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "race.h"
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define int long long
#define ar array
const int mxN = 2e5+5, M = 1e9+7;
int k, ans = 1e9, sz[mxN];
vector<pair<ll, ll>> adj[mxN], flag;
bool del[mxN];
// getting the size of our current tree
void dfs_size(int u, int p = -1){
sz[u] = 1;
for(pair<int, int> v : adj[u]){
if(v.first != p && !del[v.first]){
dfs_size(v.first, u);
sz[u] += sz[v.first];
}
}
}
// traversing subtrees without the centroid and check for possible answers
void dfs_get(map<int, int>& mp, int u, int p, int cnt, int len){
if(cnt == k){
ans = min(ans, len);
return;
}else{
flag.push_back(make_pair(cnt, len));
}
if(mp[k-cnt] > 0){
ans = min(ans, mp[k-cnt]+len);
}
for(pair<int, int> v : adj[u]){
if(v.first != p && !del[v.first]){
dfs_get(mp, v.first, u, cnt+v.second, len+1);
}
}
}
//finding the centroid
int dfs_find(int u, int total_size, int p = -1){
for(pair<int, int> v : adj[u]){
if(v.first != p && sz[v.first] > total_size/2) return dfs_find(v.first, u, total_size);
}
return u;
}
// get the size of the current tree, find its centroid and then check for possible answers considering
// that the centroid is in the answer path, then, check for the case when its not, deleting the centroid
// and doing the same process for the centroid adjacent's trees
void find_centroid(int u = 0){
memset(sz, 0, sizeof(sz));
dfs_size(u);
int total_size = sz[u];
int C = dfs_find(u, total_size);
del[C] = true;
map<int, int> mp;
for(pair<int, int> v : adj[C]){
dfs_get(mp, v.first, C, v.second, 1);
for(pair<ll, ll> val : flag){
if(mp[val.first] == 0){
mp[val.first] = val.second;
}else{
mp[val.first] = min(mp[val.first], val.second);
}
}
flag.clear();
}
for(pair<int, int> v : adj[C]){
find_centroid(v.first);
}
}
int best_path(int N, int K, int H[][2], int L[]){
k = K;
for(int i = 0; i<N-1; ++i){
adj[H[i][0]].push_back(make_pair(H[i][1], L[i]));
adj[H[i][1]].push_back(make_pair(H[i][0], L[i]));
}
find_centroid();
return (ans >= 1e9?-1:ans);
}