内容目录
求森林数,裸的并查集
Program c; var n,i,j,ans:longint; map:array[1..100,1..2] of longint; f:array[1..100] of longint; function getfather(a:longint):longint; begin if f[a]=a then exit(a); f[a]:=getfather(f[a]); exit(f[a]); end; procedure union(a,b:longint); begin f[getfather(a)]:=f[getfather(b)]; end; begin read(n); for i:=1 to n do begin f[i]:=i; read(map[i,1],map[i,2]); for j:=1 to i-1 do if (map[i,1]=map[j,1]) or (map[i,2]=map[j,2]) then union(i,j); end; ans:=0; for i:=2 to n do if getfather(i)<>getfather(i-1) then begin inc(ans); union(i,i-1); end; writeln(ans); end.