Tarjan LCA

在遍历到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.


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值