hdu 1182 A Bug's Life(简单种类并查集)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1829

题意:就是给你m条关系a与b有性关系,问这些关系中是否有同性恋

这是一道简单的种类并查集,而且也比较简单只要比较给出的两个点是否有相同祖宗如果有那么他们距离祖宗结点的距离是否为偶数

如果是偶数那么他(她)们必然是同性恋。

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int M = 2e3 + 10;
int n , m , x , y , f[M] , root[M];
void init() {
    for(int i = 1 ; i <= n ; i++) {
        f[i] = i;
        root[i] = 0;
    }
}
int find(int x) {
    if(x == f[x])
        return x;
    int t = find(f[x]);
    root[x] = (root[f[x]] + root[x]) & 1;
    f[x] = t;
    return t;
}
bool Union(int x , int y) {
    int a = find(x) , b = find(y);
    if(a == b) {
        if(root[x] == root[y])
            return false;
    }
    else {
        f[a] = b;
        root[a] = (root[x] + root[y] + 1) & 1;
    }
    return true;
}
int main() {
    int t , ans = 0;
    scanf("%d" , &t);
    while(t--) {
        bool flag = true;
        scanf("%d%d" , &n , &m);
        init();
        for(int i = 1 ; i <= m ; i++) {
            scanf("%d%d" , &x , &y);
            if(!flag)
                continue;
            flag = Union(x , y);
        }
        printf("Scenario #%d:
" , ++ans);
        if(!flag) {
            printf("Suspicious bugs found!
");
        }
        else {
            printf("No suspicious bugs found!
");
        }
        printf("
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/TnT2333333/p/6580691.html