P1131 [ZJOI2007] Temporal synchronization
Set $f[i]$ to the distance from the $i$ to the farthest point
When DFS is updated each time by the way to count the length, different words will be changed to the longest one and update the answer
#include <iostream>#include<cstdio>#include<cstring>#include<cctype>#defineRe Registerusing namespacestd;voidReadint&x) { CharC=getchar (); x=0; while(!isdigit (c)) c=GetChar (); while(IsDigit (c)) x= (x<<3) + (x<<1) + (c^ -), c=GetChar ();}#defineN 500002typedefLong Longll;intn,s; ll ans,f[n];;intcnt,hd[n],nxt[n<<1],ed[n],poi[n<<1],val[n<<1];voidAdde (intXintYintv) {Nxt[ed[x]]=++cnt; HD[X]=HD[X]?hd[x]:cnt; ED[X]=cnt; Poi[cnt]=y; val[cnt]=v;}voidDfsintXintFA) { for(inti=hd[x],t=0; i;i=nxt[i],++t) { intto=Poi[i]; if(TO==FA) {--t;Continue;} DFS (TO,X); LL v=f[to]+Val[i]; if(v>F[x]) {//update answer ans+=1ll* (V-f[x]) *T; F[X]=v; }Elseans+=f[x]-v; }}intMain () {read (n); Read (s);intq1,q2,q3; for(ReintI=1; i<n;++i) {Read (Q1); Read (Q2); Read (Q3); Adde (Q1,Q2,Q3); Adde (Q2,Q1,Q3); }dfs (s),0); printf ("%lld", ans); return 0;}
P1131 [ZJOI2007] Temporal synchronization (tree DP)