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.

你可能感兴趣的:(Tarjan,LCA)