题目链接
Find them, Catch them POJ - 1703
思路
$$ \begin{aligned}并查集基础题。\end{aligned} $$
时间复杂度
$$ O(N \alpha (N)) $$
代码
#include <cstdio>
#include <vector>
using namespace std;
class DSU {
public:
vector<int> p, r;
void init(int n) {
p.resize(n + 10);
r.resize(n + 10);
for (int i = 0; i <= n; i++) {
p[i] = i;
r[i] = 0;
}
}
int find(int x) {
if (x == p[x]) {
return x;
} else {
return p[x] = find(p[x]);
}
}
bool unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return false;
}
if (r[x] < r[y]) {
p[x] = y;
} else {
p[y] = x;
if (r[x] == r[y]) {
r[x]++;
}
}
return true;
}
bool same(int x, int y) {
return find(x) == find(y);
}
};
int main() {
int T;
scanf("%d", &T);// don't forget &
DSU dsu;
char op[5];
while (T--) {
int n, m;
scanf("%d%d", &n, &m);// don't forget &
dsu.init(2 * n);
while (m--) {
int x, y;
scanf("%s%d%d", op, &x, &y);
if (x > y) {
swap(x, y);
}
if (op[0] == 'D') {
dsu.unite(x, y + n);
dsu.unite(x + n, y);
} else {
if (dsu.same(x, y)) {
puts("In the same gang.");
} else if (dsu.same(x, y + n)) {
puts("In different gangs.");
} else {
puts("Not sure yet.");
}
}
}
}
return 0;
}