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<unordered_map>
using namespace std;
typedef double D;
typedef long long ll;
const ll mod=1e9+7;
const ll inf=(1ll<<62);
const int SQ=400;
const int MX=2e5+9;
int n,a,b,subtree[MX],blocked[MX],par[MX],depth[MX],k,dis[MX];
vector<pair<int,int> >v[MX];
vector<int>f;
ll ans=0;
unordered_map<int,int>cnt;
void dfs_size(int x,int p){
subtree[x]=1;par[x]=p;
for(auto pp:v[x]){
if(pp.first==p||blocked[pp.first])continue;
dfs_size(pp.first,x);
subtree[x]+=subtree[pp.first];
}
}
vector<int>nodes;
void DFS(int x,int p,int sum){
if(sum>k)return;
f.push_back(x);
nodes.push_back(x);
dis[x]=sum;
for(auto pp:v[x]){
if(pp.first==p||blocked[pp.first])continue;
depth[pp.first]=depth[x]+1;
DFS(pp.first,x,sum+pp.second);
}
}
void create(int x){
dfs_size(x,-1);
int S=subtree[x],idx;
queue<int>q;
q.push(x);
while(!q.empty()){
int nxt=q.front();q.pop();
int s=subtree[x]-subtree[nxt];
for(auto pp:v[nxt]){
if(pp.first==par[nxt]||blocked[pp.first])continue;
s=max(s,subtree[pp.first]);
q.push(pp.first);
}
if(S>s){
S=s;
idx=nxt;
}
}
for(auto pp:f){
cnt[dis[pp]]=0;
dis[pp]=depth[pp]=0;
}
f.clear();
blocked[idx]=1;
cnt[0]=0;
dis[idx]=depth[idx]=0;
for(auto pp:v[idx]){
if(blocked[pp.first])continue;
depth[pp.first]=1;
DFS(pp.first,idx,pp.second);
for(auto nxt:nodes){
if(k-dis[nxt]<0)continue;
if(dis[nxt]==k)ans=min(ans,(ll)depth[nxt]);
if(cnt[k-dis[nxt]]==0)continue;
ans=min(ans,(ll)depth[nxt]+cnt[k-dis[nxt]]);
}
for(auto i:nodes){
if(cnt[dis[i]]==0){cnt[dis[i]]=depth[i];}
else cnt[dis[i]]=min(cnt[dis[i]],depth[i]);
}
nodes.clear();
}
// cout<<"answer: "<<ans<<endl;
for(auto pp:v[idx]){
if(blocked[pp.first])continue;
create(pp.first);
}
}
int c;
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]+1,y=H[i][1]+1,w=L[i];
v[x].push_back({y, w});
v[y].push_back({x, w});
}
ll ans=inf;
create(1);
if(ans==inf)return -1;
return ans;
}
Compilation message (stderr)
race.cpp: In function 'void create(int)':
race.cpp:37:22: warning: 'idx' may be used uninitialized in this function [-Wmaybe-uninitialized]
int S=subtree[x],idx;
^~~
# | 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... |