[BZOJ1060] [ZJOI2007]时态同步

来源:互联网 发布:本.西蒙斯体测数据 编辑:程序博客网 时间:2024/04/30 05:53

传送门

http://www.lydsy.com/JudgeOnline/problem.php?id=1060

题目大意

给定一棵树及其边权,在边上权值不断+1,使根到所有叶子节点的距离都相同
询问最小+1的次数

题解

树形DP
f[i]:i
ans=f[i]f[son[i]w[i,son[i]]

{$M 100000000,0,100000000}uses math;const    maxn=500005;var    w:array[0..3*maxn,1..3]of longint;    f:array[0..maxn]of longint;    i,j,k:longint;    a,b,c,n,m,len,root:longint;    ans:int64;procedure init(a,b,c:longint);begin    w[len,1]:=b; w[len,2]:=c;    if w[a,3]=0 then w[a,3]:=len else w[w[a,1],3]:=len;    w[a,1]:=len; inc(len);end;procedure dfs1(a,fa:longint);var tt:longint;begin    tt:=w[a,3]; f[a]:=0;    while tt<>0 do        begin            if w[tt,1]<>fa            then begin dfs1(w[tt,1],a); f[a]:=max(f[a],f[w[tt,1]]+w[tt,2]); end;            tt:=w[tt,3];        end;end;procedure dfs2(a,fa:longint);var tt:longint;begin    tt:=w[a,3];    while tt<>0 do        begin            if w[tt,1]<>fa             then begin ans:=ans+f[a]-f[w[tt,1]]-w[tt,2]; dfs2(w[tt,1],a); end;            tt:=w[tt,3];        end;end;begin    readln(n); len:=n+1;    readln(root);    for i:=1 to n-1 do        begin            readln(a,b,c);            init(a,b,c); init(b,a,c);        end;    dfs1(root,0); ans:=0;    dfs2(root,0);    writeln(ans);end.
0 0