LCA-Tarjan-O(n^2)-O(1)

最近公共祖先问题~还有O(n)-O(1)的算法,再研究吧

 

整体用了递归、集合、分类等思想,可以去网上搜某牛的资料,黑书也不错

Code:

Program LCA_tarjan;

var
	n,i,u,v:longint;
	LCA	:array[1..1000,1..1000] of longint;
	c	:array[1..1000,0..1000] of longint;
	fa	:array[1..1000] of longint;
	hash:array[1..1000] of boolean;

	Function Getfather(x:longint):longint;
	begin
		if fa[x]=x then exit(x);
		fa[x]:=Getfather(fa[x]);
		exit(fa[x]);
	end;

	Procedure DFS(u:longint);
	var
		v,i:longint;
	begin
        if c[u,0]>0 then
		for i:=1 to c[u,0] do
			begin
                v:=c[u,i];
				DFS(v);
				fa[v]:=u;
			end;
		hash[u]:=true;
		for v:=1 to n do
			if hash[v] then
				begin
					LCA[u,v]:=Getfather(v);
					LCA[v,u]:=LCA[u,v];
				end;
	end;

begin
	readln(n);
	for u:=1 to n do fa[u]:=u;
	for i:=1 to n-1 do
		begin
			readln(u,v);
			inc(c[u,0]);
			c[u,c[u,0]]:=v;
		end;
	DFS(1);
	for u:=1 to n do
		begin
			for v:=1 to n do
				write(LCA[u,v]);
			writeln;
		end;
end.

posted on 2012-03-26 22:43  爱宝宝  阅读(245)  评论(0编辑  收藏  举报

导航