# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
635926 | daisy2 | 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<iostream>
#include "race.h"
#include<vector>
#include<algorithm>
using namespace std;
vector< pair<long long,long long> > v[200005];
long long numv[200005],nex,rs,k,ans=1000000000;
bool used[200005];
pair<long long,long long> pr[200005],nw[200005],r[200005];
long long numvr(long long vr,long long par)
{
if(used[vr]) return 0;
long long b=0;
for(long long i=0;i<v[vr].size();i++)
{
if(v[vr][i].first==par) continue;
b+=numvr(v[vr][i].first,vr);
}
return numv[vr]=b+1;
}
long long findcen(long long vr,long long par,long long ncom)
{
if(used[vr]) return 0;
for(long long i=0;i<v[vr].size();i++)
{
if(v[vr][i].first==par) continue;
if(numv[v[vr][i].first]>(ncom/2)) return findcen(v[vr][i].first,vr,ncom);
}
return vr;
}
void finp(long long vr,long long par,long long d,long long br)
{
if(used[vr]) return;
nw[nex]={d,br};
nex++;
for(long long i=0;i<v[vr].size();i++)
{
if(v[vr][i].first!=par)
finp(v[vr][i].first,vr,v[vr][i].second+d,br+1);
}
}
void merg()
{
long long in1=0,in2=0,i=0;
while(in1<nex || in2<rs)
{
if(in2>=rs || (in1<nex && nw[in1].first<=pr[in2].first))
{
r[i]=nw[in1];
in1++;i++;
}
else
{
r[i]=pr[in2];
in2++;i++;
}
}
for(long long j=0;j<i;j++)
pr[j]=r[j];
rs=i;
}
void calc()
{
long long br=rs-1,l,r,mid,fin;
for(long long i=0;i<nex;i++)
{
l=0;r=br;
fin=k-nw[i].first;
while(l<=r)
{
mid=(l+r)/2;
if(pr[mid].first>=fin) r=mid-1;
else l=mid+1;
}
if(pr[l].first==fin && pr[l].second+nw[i].second<ans)
{ans=pr[l].second+nw[i].second;}
}
}
void solve(long long cen)
{
nex=0;rs=1;
pr[0]={0,0};
used[cen]=1;
for(long long i=0;i<v[cen].size();i++)
{
if(used[v[cen][i].first]) continue;
nex=0;
finp(v[cen][i].first,cen,v[cen][i].second,1);
sort(nw,nw+nex);
calc();
merg();
}
for(long long i=0;i<v[cen].size();i++)
{
if(used[v[cen][i].first]) continue;
long long tn=numvr(v[cen][i].first,cen);
solve(findcen(v[cen][i].first,cen,tn));
}
}
long long best_path (long long N, long long K, long long H[][2], long long L[])
{
k=K;
for(long long i=0;i<N-1;i++)
{
v[H[i][0]].push_back({H[i][1],L[i]});
v[H[i][1]].push_back({H[i][0],L[i]});
}
long long tn=numvr(0,-1);
solve(findcen(0,-1,tn));
if(ans==1000000000) return -1;
return ans;
}