Tarjan LCA
来源:互联网 发布:三鹿奶粉事件 知乎 编辑:程序博客网 时间:2024/06/05 08:01
在遍历到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;beginassign(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
- Tarjan LCA
- Tarjan lca
- Tarjan LCA
- tarjan--lca
- LCA 离线算法 tarjan
- lca---tarjan算法
- poj 1470--tarjan--LCA
- Tarjan&LCA题集
- POJ 3694 Tarjan+LCA
- LCA&&Tarjan算法
- HDU2586 离线tarjan LCA
- hdu 4547(tarjan LCA)
- hdu 4547(tarjan LCA)
- hdu 4547(tarjan LCA)
- LCA的Tarjan算法
- LCA 离线tarjan算法
- POJ1330(LCA-离线tarjan)
- LCA Tarjan离线算法
- 工作经验——一次简单的Maven加速构建实战
- Android开发规范详解
- 工作经验——一次简单的Maven加速构建实战
- Caused by: java.sql.SQLException: Invalid value for getInt()
- CSS 中 @import url()
- Tarjan LCA
- *** Assertion failure in -[UISectionRowData refreshWithSection:tableView:tableViewRowData:], /Source
- python发送包含html、图片、附件和链接的邮件
- 类是公共的,应在名为.java的文件中声明
- 给定一个数,求比它大的第一个对称数
- Android-sharedUserId数据权限
- Java中的泛型方法
- 树状数组
- 树莓派学习笔记(2):常用linux命令