0%

SDTBU2021暑假集训I C题(并查集)

链接
有几个坑一开始没注意到,卡了好久

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 1e5+10;

int T;
int n, m;
int fa[N];
int a[N];

int Find(int x) {
int y = x;
while (y != fa[y]) {
y = fa[y];
}
while (x != y) {
int tmp = fa[x];
fa[x] = y;
x = tmp;
}
return y;
}

bool Union(int x, int y) {
x = Find(x);
y = Find(y);
if(x != y) {
fa[y] = x;
return true;
}
return false;
}
int bu[N];
int main() {
scanf("%d", &T);
while (T--) {
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++) {
fa[i] = i;
}
memset(bu, 0, sizeof(bu));
while(m--) {
char ch;
int x, y;
cin >> ch;
scanf("%d%d", &x, &y);
if(ch == 'D') {
if(bu[x] == 0 && bu[y] == 0) {
bu[x] = y;
bu[y] = x;
} else if(bu[x] == 0) {
bu[x] = y;
Union(x, bu[y]);
} else if(bu[y] == 0) {
bu[y] = x;
Union(bu[x], y);
} else {
Union(x, bu[y]);
Union(y, bu[x]);
}
} else if(ch == 'A') {
if(Find(x) == Find(y)) {
printf("In the same gang.\n");
} else if(Find(x) == Find(bu[y])) {
printf("In different gangs.\n");
} else {
printf("Not sure yet.\n");
}
}
}
}

return 0;
}
求大佬赏个饭