并查集的经典问题,我用到的是并查集的经典方法。。就是用relation数组记录与根节点的关系,例如relation[i]=1表示i跟i的根节点在同一个集合,relation[i]=0表示i跟i的根节点不在同一个集合。
然后就可以方便的查询他们之间的关系了。
主要是在find和union函数里面要对relation数组的修改,这个修改要自己在不同的题目中细心找出,,,因为找错一次wa了一次,find函数里的修改是递归的对所有访问到的点的relation值全都修改。
#pragma warning(disable:4996)
#include <cstdio>
#include <iostream>
using namespace std;
const int N = 100005;
int fa[N], relation[N];//relation[i]=1表示i与其根节点属于一个集合,0表示不属于一个集合
int find_set(int x) {
if (x == fa[x])return fa[x];
//这里递归的先修改了fa[x]的relation值
int ret = find_set(fa[x]);
//如果根节点跟x的父节点不同的话我们就要更新x的relation值
if (ret != fa[x]) {
relation[x] = (relation[fa[x]] + relation[x]) == 1 ? 0 : 1;
fa[x] = ret;
}
return ret;
}
void union_set(int x, int y) {
int fx = find_set(x);
int fy = find_set(y);
if (fx != fy) {
fa[fx] = fy;
relation[fx] = (relation[x] + relation[y]) == 1 ? 1 : 0;
}
}
int main() {
//freopen("in.txt", "r", stdin);
int t; scanf("%d", &t);
while (t--) {
int n, m; scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) {
fa[i] = i;
relation[i] = 1;
}
for (int i = 0; i < m; i++) {
char ch;
int x, y;
getchar();
scanf("%c %d %d", &ch, &x, &y);
if (ch == 'D') {
union_set(x, y);
}
else {
int fx = find_set(x), fy = find_set(y);
if (fx == fy) {
if (relation[x] == relation[y])printf("In the same gang.\n");
else printf("In different gangs.\n");
}
else {
printf("Not sure yet.\n");
}
}
}
}
return 0;
}