Skip to content

并查集(反集) ​

[BOI2003] 团伙 ​

题目描述 ​

现在有 n 个人,他们之间有两种关系:朋友和敌人。我们知道:

  • 一个人的朋友的朋友是朋友
  • 一个人的敌人的敌人是朋友

现在要对这些人进行组团。两个人在一个团体内当且仅当这两个人是朋友。请求出这些人中最多可能有的团体数。

输入格式 ​

第一行输入一个整数 n 代表人数。

第二行输入一个整数 m 表示接下来要列出 m 个关系。

接下来 m 行,每行一个字符 opt 和两个整数 p,q,分别代表关系(朋友或敌人),有关系的两个人之中的第一个人和第二个人。其中 opt 有两种可能:

  • 如果 opt 为 F,则表明 p 和 q 是朋友。
  • 如果 opt 为 E,则表明 p 和 q 是敌人。

输出格式 ​

一行一个整数代表最多的团体数。

样例 #1 ​

样例输入 #1 ​

6
4
E 1 4
F 3 5
F 4 6
E 1 2

样例输出 #1 ​

3

提示 ​

对于 100% 的数据,2≤n≤1000,1≤m≤5000,1≤p,q≤n。

题解 ​

我们将a+n和b,b+n和a合并,将b+n和c,c+n和b合并

find(a)就会找到b+n,find(b+n)就会找到c

c++
#include <bits/stdc++.h>
using namespace std;

using i64 = long long;

struct DSU {
    std::vector<int> f, siz;

    DSU() {}
    DSU(int n) { init(n); }

    void init(int n) {
        f.resize(n);
        std::iota(f.begin(), f.end(), 0);
        siz.assign(n, 1);
    }

    int find(int x) {
        while (x != f[x]) {
            x = f[x] = f[f[x]];
        }
        return x;
    }

    bool same(int x, int y) { return find(x) == find(y); }

    bool merge(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) {
            return false;
        }
        siz[x] += siz[y];
        f[x] = y;
        return true;
    }

    int size(int x) { return siz[find(x)]; }
};

void solve() {
    int n, m;
    cin >> n >> m;
    DSU dsu(2 * n + 1);
    while (m--) {
        char op;
        int x, y;
        cin >> op >> x >> y;
        if (op == 'F') {//朋友 直接合并
            dsu.merge(x, y);
        } else {//敌人 合并反集
            dsu.merge(x + n, y);
            dsu.merge(y + n, x);
        }
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        if (dsu.f[i] == i) {
            ans++;
        }
    }
    cout << ans << "\n";
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;
    while (t--) {
        solve();
    }
}