POJ 1611 The Suspects
一道非常簡單的並查集題目,只需要把每組人均合併到一起。最後統計和 0 是一個父親的數量即可,20 分鐘 Accepted.
/* POJ 1611
* By Ceeji
* Union
*/
#include <iostream>
#include <cstring>
using namespace std;
#define MAX_N 30000
int m, n;
int father[MAX_N];
int get_father(const int p)
{
if (father[p] == -1 || father[p] == p)
{
father[p] = p;
return p;
}
father[p] = get_father(father[p]);
return father[p];
}
void set_union (const int x, const int y)
{
int fx = get_father (x);
int fy = get_father (y);
father[fx] = fy;
}
void do_work ()
{
for (int i = 0; i < MAX_N; ++i)
father[i] = -1;
for (int j = 0; j < m; ++j)
{
int gn, tmp, first;
cin >> gn >> first;
for (int i = 0; i < gn - 1; ++i)
{
cin >> tmp;
if (get_father(tmp) != get_father(first))
set_union (tmp, first);
}
}
int f = get_father(0);
int num = 0;
for (int i = 0; i < n; ++i)
{
if (get_father(i) == f)
++num;
}
cout << num << endl;
}
int main ()
{
while (true)
{
cin >> n >> m;
if (m == 0 && n == 0)
return 0;
do_work ();
}
return 0;
}
© 轉載需附帶本文連結,依 CC BY-NC-SA 4.0 釋出。