/**
* 种类并查集入门题:
* 这题开始做的时候总是MLE 因为在get_together(x, y)之前没有判断find(x) != find(y)
* 因为,如果find(x) == find(y) 的时候,x,y在同个集合中,那么在合并的时候,根节点的fa = y;
* 而y的fa又等于根节点,就会变成没有根节点。当下次在调用find(y)的时候就会不停的递归,导致MLE.
* 还有,就是看discuss上说,如果find()函数是用迭代而非递归写的话会TLE。而用递归则MLE
* 总之在合并之前要先判断find(x) != find(y) 才可以继续合并。
*/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
#define INF 0x7fffffff
#define MAXS 100005
#define LL long long
using namespace std;
struct Person {
int re, fa;
} guys[MAXS];
void init(int n) {
for(int i = 1; i <= n; i ++) {
guys[i].fa = i;
guys[i].re = 1;
}
}
int find(int x) {
int fa = guys[x].fa;
if(fa == x) return fa;
else {
guys[x].fa = find(fa);
guys[fa].re == guys[x].re ? guys[x].re = 1 : guys[x].re = 0;
return guys[x].fa;
}
}
bool judge(int x, int y) {
if(guys[x].re == guys[y].re) return true;
else return false;
}
void get_together(int x, int y) {
int xfa = find(x);
guys[xfa].fa = y;
if(guys[x].re == 1) guys[xfa].re = 0;
else guys[xfa].re = 1;
}
int main()
{
int t, N, M, a, b;
char cmd;
scanf("%d", &t);
while(t --) {
scanf("%d%d", &N, &M);
init(N);
for(int i = 1; i <= M; i ++) {
scanf("\n%c", &cmd);
scanf("%d%d", &a, &b);
if(cmd == 'A') {
if(find(a) != find(b)) {
printf("Not sure yet.\n");
} else {
if(judge(a, b)) printf("In the same gang.\n");
else printf("In different gangs.\n");
}
}
else if(cmd == 'D') {
if(find(a) != find(b))
get_together(a, b);
}
}
}
return 0;
}
POJ 1703 Find them, Catch them 种类并查集(入门)
最新推荐文章于 2019-08-21 17:10:56 发布