题目意思好懂得很,就不再啰嗦。
并查集:以前一直只是简单地在图上用过,现在见到这种类别偏移的题这不是很好做啊。。。
主要思想就是要把一种物质的两面都建立起来,这样就能很好判断了;
这个题就是将两个帮派的人维护起来,并联系到两种形态;
如1,2是对立的帮派,那么1和2 + n就是一派的,2和1 + n就是一派的;
然后就这样建立并查集;
这题有坑就是只有两人时,那么这两人就是两个帮派的,因为这是题上说的“每个帮派至少一人”;
代码如下:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
#define maxn 100100
#define INF 1e7
#define ll long long
using namespace std;
typedef pair<ll, ll> P;
int a[maxn * 2];
int find(int x)
{
if (a[x] == x)
return x;
return a[x] = find(a[x]);
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int n, t;
scanf("%d%d", &n, &t);
for (int i = 1; i <= 2 * n; ++i)
{
a[i] = i;
}
while(t--)
{
char str[10], ch;
int x, y;
scanf("%s%d%d", str, &x, &y);
ch = str[0];
int x1,y1;
int x2,y2;
x1 = find(x), y1 = find(n + x);
x2 = find(y), y2 = find(n + y);
if (ch == 'D')
{
a[y2] = x1;
a[y1] = x2;
}
else
{
if (n == 2)
{
printf("In different gangs.\n");
continue;
}
if (x1 == x2 && y1 == y2)
printf("In the same gang.\n");
else if (x1 == y2 || x2 == y1)
printf("In different gangs.\n");
else
printf("Not sure yet.\n");
}
}
}
return 0;
}