A Bug's Life(并查集)

第一次接触这种分组的并查集,分集团的思想:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <string>
#include <stack>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
#define MAXN 1000000
int pre[MAXN*2];//开一个大一点的数组,前面的存储一个性别的,后面的再存储一个性别的
int root(int a)//寻找根节点
{
    while(a!=pre[a])
        a = pre[a];
    return a;
}
void merge(int a, int b)//合并
{
    int x = root(a);
    int y = root(b);
    if(x!=y)
        pre[x] = y;
}
int main()
{
    int t, n, m;
    scanf("%d", &t);//组数
    for(int i=1;i<=t;i++)
    {
        for(int k=1;k<=2*MAXN;k++)
            pre[k] = k;//初始化
        int flag = 1;//标记
        scanf("%d %d", &n, &m);
        for(int j=1;j<=m;j++)
        {
          int x, y;
          scanf("%d %d", &x, &y);
        if(flag==0)//已经找到性别相同的
            continue;
        if((root(x+n)==root(y+n))||(root(x)==root(y)))//根节点一样,性别相同
        {
            flag = 0;//标记
            continue;
        }
        else
        {
            //合并
            merge(x, y+n);
            merge(x+n, y);
        }
        }
        printf("Scenario #%d:\n", i);
        if(flag==0)
            printf("Suspicious bugs found!\n\n");//输出空行
        else
            printf("No suspicious bugs found!\n\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_39302444/article/details/79739711