在遍历到u时,先tarjan遍历完u的子树,则u和u的子树中的节点的最近公共祖先就是u,并且u和【u的兄弟节点及其子树】的最近公共祖先就是u的父亲。注意到由于我们是按照DFS顺序遍历的,我们可用一个color数组标记,正在访问的染色为1,未访问的标记为0,已经访问到即在【u的子树中的】及【u的已访问的兄弟节点及其子树中的】染色标记为2,这样我们可以通过并查集的不断合并更新,通过find实现以上目标。
代码 在查询时 对于相同的直接输出 代码在此处有缺陷
program pro;
var
link:array[0..100]of record ke,po,ne:longint; end;
ask:array[0..100]of record ke,po,ne,lca:longint; end;
sta,st,fa,color:array[0..100]of longint;
ans:array[0..100]of record u,v,fa:longint; end;
nans,n,m,tot,tota,i,j,k:longint;
procedure make(x,y:longint);
begin
inc(tot);
link[tot].ne:=st[x];
st[x]:=tot;
link[tot].ke:=x;
link[tot].po:=y;
end;
procedure makea(x,y:longint);
begin
inc(tota);
ask[tota].ne:=sta[x];
sta[x]:=tota;
ask[tota].ke:=x;
ask[tota].po:=y;
ask[tota].lca:=nans;
end;
function getf(x:longint):longint;
begin
if fa[x]=x then exit(x)
else fa[x]:=getf(fa[x]);
getf:=fa[x];
end;
procedure tarjan(x:longint);
var
ii,temp,v:longint;
begin
color[x]:=1;
temp:=st[x];
while temp<>0 do
begin
v:=link[temp].po;
if color[v]=0 then
begin
tarjan(v);
fa[v]:=x;
end;
temp:=link[temp].ne;
end;
temp:=sta[x];
while temp<>0 do
begin
v:=ask[temp].po;
if color[v]=2 then
begin
ans[ask[temp].lca].fa:=getf(v);
ans[ask[temp].lca].u:=x;
ans[ask[temp].lca].v:=v;
end;
temp:=ask[temp].ne;
end;
color[x]:=2;
end;
procedure init;
var
ii,jj,u,v,c:longint;
begin
readln(n);
for ii:=1 to n do fa[ii]:=ii;
for ii:=1 to n-1 do
begin
readln(u,v);
make(u,v);
end;
for ii:=1 to n-1 do
for jj:=ii+1 to n do
begin
inc(nans);
makea(ii,jj);
makea(jj,ii);
end;
end;
begin
assign(input,'test.in'); reset(input);
assign(output,'test.out'); rewrite(output);
init;
tarjan(1);
for i:=1 to nans do writeln(ans[i].u,' ',ans[i].v,' ',ans[i].fa);
close(input);
close(output);
end.