Test instructions: machine turn?
Well, pretend you've read the question.
The first is violence, enumerating every point as the root, and then each time doing a tree DP, complexity O (n2), t off;
Then, we consider how to optimize.
Suppose we have found the answer to X, to each of its child nodes,
We notice that the subtree contribution of Y is known in fact when we change its child node Y to root.
Just consider the other side of the contribution between that
It is also noted that the contribution to X, except for y, is that x's answer minus Y's contribution to it is certain.
So only x will affect Y, so just transfer it between Y and X directly according to the limit.
#include <cstdio>#include<cstring>#include<string>using namespaceStd;inlineintgi () {intx=0, w=0;CharCh=0; while(! (ch>='0'&& ch<='9') ) { if(ch=='-') w=1; CH=GetChar (); } while(ch>='0'&& ch<='9') {x= (x<<3) + (x<<1) + (ch^ -); CH=GetChar (); } returnw?-x:x;}Const intn=2e5+Ten;intT,n,tot,ans,head[n],f[n],deg[n],ind[n],vis[n];structEdge {intNext, now, Val;} E[n<<1];inlinevoidMake (int from,intTo,intva) {e[++tot].next=head[ from]; E[tot].now=to ; E[tot].val=va; head[ from]=tot;}voidnew_case () {tot=0; ans=0; Memset (F,0,sizeof(f)); memset (&e,0,sizeof(e)); memset (Ind,0,sizeof(Ind)); memset (Vis,0,sizeof(VIS)); memset (Deg,0,sizeof(Deg)); memset (Head,0,sizeof(head));}voidDP (intk) {Vis[k]=1; for(intI=head[k];i;i=E[i].next) { intx=E[i].now; if(Vis[x])Continue; DP (x); if(ind[x]==1) deg[k]+=E[i].val; Elsedeg[k]+=min (deg[x], e[i].val); }}voidDFS (intp) {Vis[p]=1; for(intI=head[p];i;i=E[i].next) { intk=E[i].now; if(Vis[k])Continue; if(ind[p]==1) f[k]=deg[k]+E[i].val; ElseF[k]=deg[k]+min (E[i].val, f[p]-min (E[i].val, deg[k])); DFS (k); } }intMain () {T=gi (); while(t--) {n=gi (); New_case (); for(intI=1, X, Y, z;i<n;++i) {x=gi (), Y=gi (), z=gi (); IND[X]+ +, ind[y]++; Make (x, y, z); Make (y, x, z); } DP (1); memset (Vis,0,sizeof(VIS)); f[1]=deg[1]; DFS (1);//Change Root for(intI=1; i<=n;++i) ans=Max (ans, f[i]); printf ("%d\n", ans); } return 0;}
POJ3585 Change root Template