POJ 1182食物链——并查集模板题

本文探讨了代码操作过程中的技巧与数据结构的应用,通过实例展示了如何高效地使用CL2姐姐的方法来解决编程问题。

没什么好说的了,用CL2姐姐的话说,题解满天飞,标程也满天飞……

我的代码:

Program eat;//by_Thispoet
Const 	
	maxn=50005;
Var
	father,data			:Array[1..maxn]of Longint;
	ans,i,k,n,m,p,q		:Longint;
	
Function Root(i:Longint):Longint;
var t:Longint;
begin
	if father[i]=i then exit(i);
	t:=father[i];
	father[i]:=Root(father[i]);
	data[i]:=(data[i]+data[t])mod 3;
	exit(father[i]);
end;
	
	
BEGIN

	readln(n,m);
	ans:=0;
	for i:=1 to n do father[i]:=i;
	fillchar(data,sizeof(data),0);
	while m>0 do 
		begin
			readln(k,p,q);
			if (p>n)or(q>n) then 
				begin
					dec(m);
					inc(ans);
					continue;
				end;//pos 1
			case k of 
				1:
					begin
						if Root(p)=Root(q) then
							begin
								if data[p]<>data[q] then
									inc(ans);
							end else
								begin
									i:=Root(p);
									father[i]:=q;
									data[i]:=(3-data[p])mod 3;
								end;
					end;
				2:
					begin
						if Root(p)=Root(q) then 
							begin
								i:=(data[p]-data[q]+3)mod 3;
								if i<>1 then inc(ans);
							end else
								begin
									i:=Root(p);
									father[i]:=q;
									data[i]:=(4-data[p])mod 3;
								end;
					end;
			end;
			dec(m);
		end;
	writeln(ans);

END.

转载于:https://www.cnblogs.com/Thispoet/archive/2011/10/08/2202369.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值