BZOJ 2599 Race
阿新 • • 發佈:2018-05-10
mes 長度 return base add TP () names stream
點分治
\(DP[k]\)表到重心長\(k\)最少邊數
掃子樹,拼長度,更ans
註意判\(-1\) !
#include <iostream> using namespace std; const int MAXN=200111; const int MAXK=1000111; int N, K; struct Vert{ int FE; int Size, Val; bool Vis; int Dis, Dep; } V[MAXN]; struct Edge{ int x, y, l, next; } E[MAXN<<1]; int Ecnt=0; void addE(int a, int b, int c){ ++Ecnt; E[Ecnt].x=a;E[Ecnt].y=b;E[Ecnt].l=c;E[Ecnt].next=V[a].FE;V[a].FE=Ecnt; } void getSize(int at, int f=0){ V[at].Size=1; for(int k=V[at].FE, to;k>0;k=E[k].next){ to=E[k].y; if(to==f || V[to].Vis) continue; getSize(to, at); V[at].Size+=V[to].Size; } } int AllSize; void getVal(int at, int f=0){ V[at].Val=AllSize-V[at].Size; for(int k=V[at].FE, to;k>0;k=E[k].next){ to=E[k].y; if(to==f || V[to].Vis) continue; getVal(to, at); V[at].Val=max(V[at].Val, V[to].Size); } } int getG(int at, int f=0){ int ret=at; for(int k=V[at].FE, to;k>0;k=E[k].next){ to=E[k].y; if(to==f || V[to].Vis) continue; to=getG(to, at); if(V[ret].Val>V[to].Val) ret=to; } return ret; } void getD(int at, int f=0){ if(V[at].Dis>K) return; for(int k=V[at].FE, to;k>0;k=E[k].next){ to=E[k].y; if(to==f || V[to].Vis) continue; V[to].Dis=V[at].Dis+E[k].l; V[to].Dep=V[at].Dep+1; getD(to, at); } } int ANS; int DP[MAXK]; int Dps[MAXK]; int DPN=0; void relax(int t, int v){ if(Dps[t]!=DPN){ DP[t]=v;Dps[t]=DPN; } else DP[t]=min(v, DP[t]); } bool In(int t){ return Dps[t]==DPN; } void getA(int at, int f=0){ if(V[at].Dis>K) return; if(In(K-V[at].Dis)) ANS=min(ANS, DP[K-V[at].Dis]+V[at].Dep); for(int k=V[at].FE, to;k>0;k=E[k].next){ to=E[k].y; if(to==f || V[to].Vis) continue; getA(to, at); } } void getP(int at, int f=0){ if(V[at].Dis>K) return; relax(V[at].Dis, V[at].Dep); for(int k=V[at].FE, to;k>0;k=E[k].next){ to=E[k].y; if(to==f || V[to].Vis) continue; getP(to, at); } } void Div(int at){ getSize(at);AllSize=V[at].Size; getVal(at);at=getG(at); V[at].Vis=true; V[at].Dis=0;V[at].Dep=0; getD(at); ++DPN; relax(0, 0); for(int k=V[at].FE, to;k>0;k=E[k].next){ to=E[k].y; if(V[to].Vis) continue; getA(to, at); getP(to, at); } for(int k=V[at].FE, to;k>0;k=E[k].next){ to=E[k].y; if(!V[to].Vis) Div(to); } } int main(){ ios_base::sync_with_stdio(false); cin >> N >> K; for(int i=1, a, b, c;i<N;++i){ cin >> a >> b >> c;++a;++b; addE(a, b, c);addE(b, a, c); } ANS=N; Div(1); if(ANS>=N) ANS=-1; cout << ANS << endl; return 0; } /* 4 3 0 1 1 1 2 2 1 3 4 2 */
BZOJ 2599 Race