Every time we find the smallest point that left the largest unicom, that is, the center of gravity calculation contribution
#include <cstdio>#include<iostream>#include<algorithm>using namespacestd; intnext[80001],des[80001],len[80001],nd[40001],cnt,bt[40001],dfstim,size[40001]; intmsiz[40001],b[40001],maxsiz,grav,sta[40001],top,k,fin[40001]; Long Longans; voidAddedge (intXintYintle) {next[++CNT]=ND[X];d es[cnt]=y;len[cnt]=le;nd[x]=CNT; } voidDFS1 (intPO) {Bt[po]=dfstim;size[po]=1; msiz[po]=0; for(intP=ND[PO];p!=-1;p =Next[p])if(b[des[p]]&&bt[des[p]]<Dfstim) {DFS1 (des[p]); MSIZ[PO]=Max (Msiz[po],size[des[p]]); SIZE[PO]+=Size[des[p]]; } } voidDFS2 (intPointtot) {Bt[po]=Dfstim; if(Max (Msiz[po],tot-size[po]) <maxsiz) {Maxsiz=max (msiz[po],tot-Size[po]); Grav=PO; } for(intP=ND[PO];p!=-1;p =Next[p])if(b[des[p]]&&bt[des[p]]<dfstim) DFS2 (Des[p],tot); } intFindgrav (intPO) {Dfstim++;d FS1 (PO); Maxsiz=1e9; Dfstim++;d FS2 (Po,size[po]); } voidDFS3 (intPointLeft ) { if(left>=0) sta[++top]=k-Left ; if(left<0)return; BT[PO]=Dfstim; for(intP=ND[PO];p!=-1;p =Next[p])if(b[des[p]]&&bt[des[p]]<dfstim) dfs3 (Des[p],left-len[p]); } voidWorkintPO) {Findgrav (PO); B[grav]=0; intAll=0; for(intP=nd[grav];p!=-1;p =Next[p])if(B[des[p]]) {Dfstim++;top=0; DFS3 (Des[p],k-len[p]); Ans+=top; Sort (STA+1, sta+top+1); inttmp=All ; for(intI=1; i<=top;i++){ while(sta[i]+fin[tmp]>k) tmp--; Ans+=tmp; } for(intI=1; i<=top;i++) fin[++all]=Sta[i]; Sort (Fin+1, fin+all+1); } for(intP=nd[grav];p!=-1;p =Next[p])if(B[des[p]]) work (des[p]); } intMain () {intN; scanf ("%d",&N); for(intI=1; i<=n;i++) nd[i]=-1, b[i]=1; for(intI=1; i<n;i++){ intT1,t2,t3; scanf ("%d%d%d",&t1,&t2,&T3); Addedge (T1,T2,T3); Addedge (T2,T1,T3); } scanf ("%d",&k); Work (1); printf ("%lld\n", ans); }
Point Division Treatment