当前位置: 代码迷 >> 综合 >> POJ——1611 The Suspects(并查集)
  详细解决方案

POJ——1611 The Suspects(并查集)

热度:92   发布时间:2024-02-27 02:23:50.0

原题链接: http://poj.org/problem?id=1611

在这里插入图片描述
测试样例

Sample Input
100 4
2 1 2
5 10 13 11 12 14
2 0 1
2 99 2
200 2
1 5
5 1 2 3 4 5
1 0
0 0
Sample Output
4
1
1

题意:nnn个学生和mmm个小组,其中每个学生可以加入多个小组。学生编号从000n?1n-1n?1,现在有一个规定,若一个小组中有一个是疑似SARS感染者,那么该小组其他人也会被认为是SARS感染者。现在学生000被认为是SARS感染者,你需要找出这nnn个学生中到底有多少个SARSSARSSARS感染者。

解题思路: 一道妥妥的并查集问题,即小组的同为一集合,一个人待的多个小组也是同一集合,这样去合并即可,最后计算与编号为000的同学所在的集合有多少就行。要注意的一点就是我们在进行小组合并时可以选择一个主导者作为参考者,让其他组员加入他所在的集合。 OK,具体看代码。

AC代码

/* *邮箱:unique_powerhouse@qq.com *blog:https://me.csdn.net/hzf0701 *注:文章若有任何问题请私信我或评论区留言,谢谢支持。 * */
#include<iostream> //POJ不支持#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pairusing namespace std;const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 3e4+4;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll>  pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//int n,m;//n代表人数,m代表组数。
int father[maxn];//每个人所在集合。
int Find(int x){
    int r=x;while(r!=father[r]){
    r=father[r];}int i=x,j;while(father[i]!=r){
    j=father[i];father[i]=r;i=j;}return r;
}
int main(){
    //freopen("in.txt", "r", stdin);//提交的时候要注释掉IOS;while(cin>>n>>m){
    if(n==0&&m==0){
    break;}rep(i,0,n-1){
    father[i]=i;}rep(i,0,m-1){
    //默认第一个组为老大。int temp,leader,people;cin>>temp;if(temp==0){
    continue;}cin>>leader;rep(i,1,temp-1){
    cin>>people;int fx=Find(leader);int fy=Find(people);if(fx!=fy){
    father[fy]=fx;}}}int cnt=0;rep(i,0,n-1){
    if(Find(i)==Find(0)){
    cnt++;}}cout<<cnt<<endl;}return 0;
}