并查集(反集)
[BOI2003] 团伙
题目描述
现在有
- 一个人的朋友的朋友是朋友
- 一个人的敌人的敌人是朋友
现在要对这些人进行组团。两个人在一个团体内当且仅当这两个人是朋友。请求出这些人中最多可能有的团体数。
输入格式
第一行输入一个整数
第二行输入一个整数
接下来
- 如果
为 F,则表明和 是朋友。 - 如果
为 E,则表明和 是敌人。
输出格式
一行一个整数代表最多的团体数。
样例 #1
样例输入 #1
6
4
E 1 4
F 3 5
F 4 6
E 1 2样例输出 #1
3提示
对于
题解
我们将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();
}
}