# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
764066 | Ryuga_ | 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.
#include <bits/stdc++.h>
#include <bits/extc++.h>
using namespace std;
#define int long long int
#define F first
#define S second
const int N = 2e5 + 10;
int sub[N] , process[N];
vector<pair<int,int>>g[N];
int ans = 1e18;
map<int,int>mp;
int n , k;
int dfs(int u , int p)
{
sub[u] = 1;
for(auto v : g[u]){
if(v.F != p && !process[v.F]){
sub[u] += dfs(v.F,u);
}
}
return sub[u];
}
int centroid(int u , int p , int req)
{
for(auto v : g[u]){
int x = v.F;
if(x != p && !process[x] && sub[x] >= req){
return centroid(x,u,req);
}
}
return u;
}
void f(int u , int p , int keep, int level,int depth)
{
if(depth > k)return;
if(!keep){
if(mp.find(k-depth) != mp.end()){
ans = min(ans,level+mp[k-depth]);
}
}
else{
if(mp.find(k-depth) != mp.end()){
mp[depth] = min(mp[depth],level);
}
else mp[depth] = level;
}
for(auto v : g[u]){
if(v.F != p && !process[v.F]){
f(v.F,u,keep,level+1,depth+v.S);
}
}
}
void decompos(int u)
{
int x = dfs(u,-1);
int cen = centroid(u,-1,x/2);
process[cen] = 1;
mp[0] = 0;
for(auto v : g[cen]){
if(!process[v.F]){
f(v.F,cen,0,1,v.S);
f(v.F,cen,1,1,v.S);
}
}
mp.clear();
for(auto v : g[cen]){
if(!process[v.F]) decompos(v.F);
}
}
int best_path(int N,int K,int H[][2],int L[])
{
n = N , k = K;
for(int i = 0 ; i < n - 1 ; i ++){
int x = H[i][0] , y = H[i][1] , w = L[i];
g[x].push_back({y,w});
g[y].push_back({x,w});
}
decompos(0);
if(ans == 1e18) ans = -1;
return ans;
}