POJ - 2492 A Bug‘s Life(带权并查集板子)

题目链接

思路:
带权并查集板子题,将种类分为两类,对2取余为0的一类,取余为1的一类,
对于每组输入数据维护带权并查集关系,遇到与前面相悖的就直接flag更新,这组数据后面的就不用考虑了。

代码:

#include <iostream>
#include <algorithm>
#include <string>
#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <climits>
#include <iomanip>
#include <queue>
#include <vector>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl

using namespace std;

typedef long long ll;
typedef pair<int, int> PII;

const int N = 2010;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;

int n, m;
int f[N], d[N];
int find(int x)
{
    if (x != f[x])
    {
        int u = find(f[x]);
        d[x] += d[f[x]];
        f[x] = u;
    }
    return f[x];
}

int main()
{
    int T;
    cin >> T;
    for (int j = 1; j <= T; j++)
    {
        scanf("%d%d", &n, &m);
        for (int i = 1; i <= n; i++)
            f[i] = i, d[i] = 0;
        bool flag = false;
        while (m--)
        {
            int x, y;
            scanf("%d%d", &x, &y);
            if (flag)
                continue;
            int f1 = find(x), f2 = find(y);
            if (f1 != f2)
            {
                f[f1] = f2;
                d[f1] = d[y] + 1 - d[x];
                while (d[f1] < 0)
                    d[f1] += 2;
            }
            else
            {
                if (d[x] % 2 == d[y] % 2)
                    flag = true;
            }
        }
        printf("Scenario #%d:\n", j);
        if (flag)
            printf("Suspicious bugs found!\n");
        else
            printf("No suspicious bugs found!\n");
        printf("\n");
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值