天天看点

poj1611 The suspect并查集

AC啦

var   n,m,i,j,t,ans,k:longint;   f:array[0..30000] of longint;   a:array[1..30000] of longint; function findset(x:longint):longint; begin   if x<>f[x] then     f[x]:=findset(f[x]);   exit(f[x]); end; procedure union(x,y:longint); begin   x:=findset(x);   y:=findset(y);   if x<>y then     if x=0 then       f[y]:=x     else       if y=0 then         f[x]:=y       else         f[x]:=y; end; begin   while not eof do     begin       fillchar(f,sizeof(f),0);       read(n,m);       for i:=1 to n do         f[i]:=i;       for j:=1 to m do         begin           fillchar(a,sizeof(a),0);           read(k);           read(a[1]);           for i:=2 to k do             begin               read(a[i]);               union(a[i],a[i-1]);             end;         end;   ans:=0;   for i:=0 to n do     begin       f[i]:=findset(f[i]);       if f[i]=0 then inc(ans);     end;   if n<>0 then     writeln(ans);   end; end.

poj