bzoj 2435 BFS
我们可以先将无根树变成有根树,随便选一个点当根就行了,我们选1,bfs求出来每个点
的size值,代表以它为根节点的子树中有多少个节点,(dfs可能会爆栈),然后再对于每一条
边算就好了
我tle了,也不知道咋会事儿,可能是pascal的int64的运算有些耗时。。。。
/************************************************************** Problem: 2435 User: BLADEVIL Language: Pascal Result: Time_Limit_Exceed ****************************************************************/ //By BLADEVIL var n :longint; pre, other, last, len :array[0..2000010] of int64; l :longint; flag :array[0..1000010] of boolean; size, que, dep :array[0..1000010] of int64; ans :int64; fuse :array[0..2000010] of boolean; procedure connect(x,y,z:longint); begin inc(l); pre[l]:=last[x]; last[x]:=l; other[l]:=y; len[l]:=z; end; procedure init; var i :longint; x, y, z :longint; begin read(n); for i:=1 to n-1 do begin read(x,y,z); connect(x,y,z); connect(y,x,z); end; end; procedure bfs; var h, t, cur :longint; q, p :longint; begin h:=0; t:=1; que[1]:=1; flag[1]:=true; while h<>t do begin inc(h); cur:=que[h]; q:=last[cur]; while q<>0 do begin p:=other[q]; if not flag[p] then begin fuse[q]:=true; inc(t); que[t]:=p; dep[p]:=dep[cur]+1; flag[p]:=true; end; q:=pre[q]; end; end; end; procedure main; var i :longint; q, p :longint; begin bfs; for i:=n downto 1 do begin q:=last[que[i]]; size[que[i]]:=1; while q<>0 do begin p:=other[q]; if dep[p]>dep[que[i]] then inc(size[que[i]],size[p]); q:=pre[q]; end; end; for i:=1 to l do if fuse[i] then ans:=ans+abs(n-2*size[other[i]])*len[i]; writeln(ans); end; begin init; main; end.