# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
526883 | Yuisuyuno | Race (IOI11_race) | C++14 | 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.
//Nguyen Huu Hoang Minh
#include <bits/stdc++.h>
#include "race.h"
#define sz(x) int(x.size())
#define all(x) x.begin(),x.end()
#define reset(x) memset(x, 0,sizeof(x))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define MAXN 200005
#define remain(x) if (x > MOD) x -= MOD
#define ii pair<int, int>
#define iiii pair< ii , ii >
#define viiii vector< iiii >
#define vi vector<int>
#define vii vector< ii >
#define bit(x, i) (((x) >> (i)) & 1)
#define Task "test"
#define int long long
using namespace std;
typedef long double ld;
const int inf = 1e10;
const int minf = -1e10;
int n, ans, k;
vector<ii> g[MAXN];
vector<int> brute;
bool rm[MAXN];
int s[MAXN], a[1000005], sub[MAXN], d[MAXN], dep[MAXN];
int dfs(int u, int par=-1){
s[u] = 1;
for(auto i : g[u]){
int v = i.fi; if (v==par || rm[v]) continue;
s[u] += dfs(v,u);
}
return s[u];
}
int get_centroid(int u, int ms, int par=-1){
for(auto i : g[u]){
int v = i.fi; if (v==par || rm[v]) continue;
if (s[v]*2 > ms) return get_centroid(v,ms,u);
}
return u;
}
int DFS(int u, int par){
sub[u] = 1;
brute.pb(u);
for(auto i : g[u]){
int v = i.fi; int uv = i.se;
if (v==par || rm[v]) continue;
d[v] = d[u] + uv;
dep[v] = dep[u] + 1;
sub[u] += DFS(v,u);
}
return sub[u];
}
void centroid(int n = 0){
int C = get_centroid(n,dfs(n));
rm[C] = 1;
if (s[n]==1) return;
queue<int> q;
for(auto i : g[C]){
int v = i.fi; int uv = i.se; if (rm[v]) continue;
d[C] = 0; d[v] = d[C] + uv; dep[C] = 0; dep[v] = dep[C] + 1; brute.clear();
DFS(v,C);
for(auto x : brute){
if (d[x] > k) continue;
if (d[x]== k) ans = min(ans,dep[x]);
else if (a[k-d[x]]) ans = min(ans,dep[x] + a[k-d[x]]);
}
for(auto x : brute){
if (d[x] <= k && (a[d[x]]==0 || a[d[x]] > dep[x])) a[d[x]] = dep[x], q.push(d[x]);
}
}
while (q.size()){
a[q.front()] = 0;
q.pop();
}
for(auto i : g[C]){
int v = i.fi; if (!rm[v]) centroid(v);
}
}
int best_path(int N, int K, int H[][2], int L[])
{
int i;
n = N, k = K;
for (i = 0; i < n - 1; i++){
g[H[i][0]].push_back(ii(H[i][1],L[i]));
g[H[i][1]].push_back(ii(H[i][0],L[i]));
}
ans = n + 1;
centroid();
return ans == n + 1 ? -1 : ans;
}