并查集 + 向量偏移
附代码(AC,10MS)
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int MAX = 1e5 + 5;
int f[MAX], r[MAX];
void init(int n){
for(int i = 1; i <= n; ++i)
f[i] = i, r[i] = 0;
}
int find(int a){
if(a == f[a])
return a;
int t = f[a];
f[a] = find(t);
r[a] = (r[a] + r[t]) % 2;
return f[a];
}
void uni(int a, int b, int rs){
int fa = find(a), fb = find(b);
if(fa != fb){
f[fa] = fb;
r[fa] = (2 - r[a] + r[b] + rs) % 2;
}
}
int main(){
int ca, a, b, n, m;
char s[20];
scanf("%d", &ca);
while(ca--){
scanf("%d%d", &n, &m);
init(n);
while(m--){
scanf("%s", s);
scanf("%d%d", &a, &b);
if(s[0] == 'S'){
uni(a, b, 0);
}
else if(s[0] == 'D'){
uni(a, b, 1);
}
else{
int fa = find(a), fb = find(b);
if(fa == fb){
if(r[a] == r[b])
printf("same.\n");
else
printf("different.\n");
}
else{
printf("not sure yet.\n");
}
}
}
}
return 0;
}