[IOI2011]Race $O(nlog^{2}n)$ 做法
这个应该还不是正解,明天看一下正解到底是什么...
Code:
#include<bits/stdc++.h> #define setIO(s) freopen(s".in","r",stdin) #define maxn 500000 #define inf 0x7f7f7f using namespace std; char *q1,*q2,buf[1000000]; #define nc() (q1==q2&&(q2=(q1=buf)+fread(buf,1,1000000,stdin),q1==q2)?EOF:*q1++) int rd() {int x=0; char c=nc(); while(c<48) c=nc(); while(c>47) x=(((x<<2)+x)<<1)+(c^48),c=nc(); return x;} int hd[maxn],to[maxn],nex[maxn],val[maxn],f[maxn],vis[maxn],siz[maxn],dep[maxn],ans,cur=0; int cnt,n,k,root,sn,d[2]; void addedge(int u,int v,int c) { nex[++cnt] = hd[u],hd[u] = cnt,to[cnt] = v,val[cnt] = c; } struct Point{ int dis,tot; Point(int dis = 0,int tot = 0):dis(dis),tot(tot){} bool operator<(Point b)const{ return b.dis != dis ? b.dis>dis : b.tot > tot; } }point[2][maxn],pp[maxn]; void getdis(int u,int fa,int tot) { if(!u) return; point[cur][++d[cur]]=Point(dep[u],tot); for(int i = hd[u]; i ; i = nex[i]) { if(vis[to[i]] || to[i] == fa) continue; dep[to[i]] = dep[u] + val[i],getdis(to[i],u,tot + 1); } } void GetRoot(int u,int ff) { siz[u] = 1,f[u] = 0; for(int i = hd[u]; i ; i = nex[i]) { if(vis[to[i]] || to[i] == ff) continue; GetRoot(to[i],u); siz[u] += siz[to[i]]; f[u] = max(f[u], siz[to[i]]); } f[u] = max(f[u], sn - siz[u]); if(f[u] < f[root]) root = u; } void DFS(int u) { //calc d[cur^1]=d[cur]=0,vis[u]=1; point[cur^1][++d[cur^1]]=Point(0,0); for(int i = hd[u],j,m,p1,p2; i ; i = nex[i]) { if(vis[to[i]]) continue; dep[to[i]]=val[i]; getdis(to[i],u,1); sort(point[cur]+1,point[cur]+1+d[cur]); m = 1; for(j = 2;j <= d[cur]; ++j) if(point[cur][j].dis!=point[cur][j-1].dis) point[cur][++m]=point[cur][j]; d[cur] = m,p1 = 1,p2 = d[cur^1]; while(p1 <= d[cur] && p2 >=1) { if(point[cur][p1].dis + point[cur^1][p2].dis == k) ans = min(ans,point[cur][p1].tot + point[cur^1][p2].tot), ++p1,--p2; if(point[cur][p1].dis + point[cur^1][p2].dis < k) ++p1; if(point[cur][p1].dis + point[cur^1][p2].dis > k) --p2; } for(j = 1;j <= d[cur]; ++j) point[cur^1][++d[cur^1]] = point[cur][j]; sort(point[cur^1]+1,point[cur^1]+1+d[cur^1]); m = 1; for(j=2;j<=d[cur^1];++j) if(point[cur^1][j].dis!=point[cur^1][j-1].dis)point[cur^1][++m]=point[cur^1][j]; d[cur^1]=m, d[cur]=0; } for(int i = hd[u]; i ; i = nex[i]) { if(vis[to[i]]) continue; root = 0,sn = siz[to[i]],GetRoot(to[i],u), DFS(root); } } int main() { // setIO("input"); n=rd(),k=rd(); for(int i = 1,a,b,c;i < n; ++i) a=rd(),b=rd(),c=rd(),addedge(a+1,b+1,c),addedge(b+1,a+1,c); ans = inf, vis[0] = 1,f[0] = inf,sn = n,root = 0, GetRoot(1,0); DFS(root); printf("%d\n",ans==inf?-1:ans); return 0; }