POJ1611(The Suspects)

算法:并差集

为什么并差集写在过程就对,写在主程序里就不对啊……

program POJ1611;

const
  maxn=30001;

var
  n,m,i,j,t,tx,ty,max:longint;
  f,a,sum:array [0..maxn] of longint;{sum[i]表示以i为根的那个组的人数有多少。}

function get(x:longint):longint;
begin
  if f[x]=x then exit(x)
  else
    begin
      f[x]:=get(f[x]);
      exit(f[x]);
    end;
end;

procedure union(x,y:longint);{加上按秩合并的优化,说白了就是哪组人多我就加到哪组。}
begin
  tx:=get(x);
  ty:=get(y);
  if tx<>ty then
    begin
      if sum[tx]<sum[ty] then
        begin
          f[tx]:=ty;
          inc(sum[ty],sum[tx]);
        end
      else
        begin
          f[ty]:=tx;
          inc(sum[tx],sum[ty]);
        end;
    end;
end;

begin

  readln(n,m);
  while n+m<>0 do
    begin
      for i:=0 to n-1 do
        begin
          f[i]:=i;
          sum[i]:=1;
        end;
      for i:=1 to m do
        begin
          read(t,a[1]);
          for j:=2 to t do
            begin
              read(a[j]);
              union(a[1],a[j]);{每次都让第一个人和其它人进行合并。因为并差集具有相互性。}
            end;
          readln;
        end;
      writeln(sum[f[0]]);{最后输出0所在的那个组的人数,也就是染了病毒的那个组有多少人。}
      readln(n,m);
    end;

end.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值