poj1703 Find them, Catch them(并查集)

时间:2023-03-08 16:17:33
poj1703 Find them, Catch them(并查集)

https://vjudge.net/problem/POJ-1703

9ms多,卡着时间过了。上次一道并查集也是这样,总觉得要学一波并查集的优化。。

续:好像是可以只做一层存放敌人即可。

 #include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stack>
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
#define INF 0x3f3f3f3f
typedef unsigned long long ll;
using namespace std;
const int N=;
int t, n, m, x, y, pre[];
char c;
int find(int x)
{
while(x != pre[x]){
x = pre[x];
}
return x;
}
int is_same(int a, int b)
{
int tx = find(a);
pre[a] = tx;
int ty = find(b);
pre[b] = ty;
if(tx == ty) return ;
return ;
}
void join(int a, int b)
{
int tx = find(a);
pre[a] = tx;
int ty = find(b);
pre[b] = ty;
pre[tx] = ty;
}
int main()
{
scanf("%d", &t);
while(t--){
scanf("%d%d", &n, &m);
for(int i = ; i <= N*; i++){
pre[i] = i;
}
//c = getchar();
for(int i = ; i < m; i++){
c = getchar();
scanf("%c%d%d", &c, &x, &y);
if(c == 'A'){
if(is_same(x, y)||is_same(x+N, y+N)){
printf("In the same gang.\n");
}
else{
if(!is_same(x, y)&&!is_same(x, y+N)){
printf("Not sure yet.\n");
}
else printf("In different gangs.\n");
}
}
else{
join(x, y+N);
join(x+N, y);
}
}
}
return ;
}