[BZOJ1060] [ZJOI2007]时态同步

传送门

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值