tarjan求lca

program lcastat;
var ans,ans1:int64;
    w:array[1..10000000]of longint;
    father,head:array[1..10000000]of longint;
    i,n,p,l:longint;
    vis:array[1..10000000]of boolean;
    edge:array[1..10000000,1..2]of longint;
function getfather(x:longint):longint;
var i,t:longint;
begin
 i:=x;
 while father[i]<>i do
  i:=father[i];
 while father[x]<>x do
  begin
   t:=father[x];
   father[x]:=i;
   x:=t;
  end;
 getfather:=i;
end;

procedure tarjan(x:longint);
var p:longint;
begin
 p:=head[x];
 while p<>-1 do
  begin
   tarjan(edge[p,1]);
   father[edge[p,1]]:=x;
   p:=edge[p,2];
  end;
 vis[x]:=true;//全部遍历完标记访问过,保证(x,p)只算一次
 for p:=1 to n do
  if (vis[p])and(x<>p) then
   ans1:=(ans1+w[x]*w[p] mod 1000000007*w[getfather(p)] mod 1000000007) mod 1000000007;
end;
begin
 read(n,w[1]);
 ans:=int64(w[1]*w[1]) mod 1000000007*w[1] mod 1000000007;
 for i:=1 to n do head[i]:=-1;
 for i:=2 to n do
  begin
   read(p,w[i]);
   ans:=(ans+(int64(w[i]*w[i]) mod 1000000007)*w[i] mod 1000000007) mod 1000000007;
   l:=l+1;
   edge[l,1]:=i;
   edge[l,2]:=head[p];
   head[p]:=l;
  end;
 fillchar(vis,sizeof(vis),false);
 for i:=1 to n do father[i]:=i;
 tarjan(1);
 ans:=(ans+ans1*2) mod 1000000007;
 write(ans);
end.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值