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;
const int N = 2e5 + 1;
const int K = 20;
vector<pair<int,int> > adj[N];
int sz[N],pa[N],lv[N],dp[K][N],ans = INT_MAX;
bool blocked[N];
long long dist[N];
unordered_map<int,int> res[N];
void dfs(int u,int p){ sz[u] = 1; for(auto [d,v] : adj[u]) if(v!=p and !blocked[v]) dfs(v,u),sz[u]+=sz[v]; }
void build(int u,int cp)
{
dfs(u,0);
int c = u,prev = 0;
while(true)
{
int mx = 0,id = 0;
for(auto [d,v] : adj[c]) if(!blocked[v] and v!=prev) if(sz[v]>mx) mx = sz[v],id = v;
if(mx*2>sz[u]) prev = c,c = id;
else break;
}
pa[c] = cp;
blocked[c] = true;
for(auto [d,v] : adj[c]) if(!blocked[v]) build(v,c);
}
void dfslca(int u,int p){ lv[u] = lv[p]+1,dp[0][u] = p; for(auto [d,v] : adj[u]) if(v!=p) dist[v] = dist[u]+(long long)d,dfslca(v,u); }
int lca(int a,int b)
{
if(lv[a]<lv[b]) swap(a,b);
for(int i = K-1;i >= 0;i--) if(lv[dp[i][a]]>=lv[b]) a = dp[i][a];
if(a==b) return a;
for(int i = K-1;i >= 0;i--) if(dp[i][a]!=dp[i][b]) a = dp[i][a],b = dp[i][b];
return dp[0][a];
}
int best_path(int n,int k,int h[][2],int l[])
{
for(int i = 0;i < n-1;i++)
{
int a = h[i][0],b = h[i][1],d = l[i]; a++,b++;
adj[a].push_back({d,b});
adj[b].push_back({d,a});
}
build(1,0);
dfslca(1,0);
for(int i = 1;i <= n;i++)
{
for(int u = pa[i];u;u = pa[u])
{
int l = lca(i,u);
long long all = dist[i]-dist[l]+dist[u]-dist[l];
if(all>k) continue;
int len = lv[i]-lv[l]+lv[u]-lv[l];
if(res[u][all]==0 or res[u][all]>len)
{
res[u][all] = len;
if(all==k) ans = min(ans,len);
else if(res[u][k-all]) ans = min(ans,res[u][k-all]+len);
}
}
}
if(ans==INT_MAX) ans = -1;
return ans;
}
Compilation message (stderr)
race.cpp: In function 'void dfs(int, int)':
race.cpp:14:48: warning: unused variable 'd' [-Wunused-variable]
void dfs(int u,int p){ sz[u] = 1; for(auto [d,v] : adj[u]) if(v!=p and !blocked[v]) dfs(v,u),sz[u]+=sz[v]; }
^
race.cpp: In function 'void build(int, int)':
race.cpp:23:22: warning: unused variable 'd' [-Wunused-variable]
for(auto [d,v] : adj[c]) if(!blocked[v] and v!=prev) if(sz[v]>mx) mx = sz[v],id = v;
^
race.cpp:29:18: warning: unused variable 'd' [-Wunused-variable]
for(auto [d,v] : adj[c]) if(!blocked[v]) build(v,c);
^| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |