今天一直在练习并查集,发现这道题有点神奇,感觉这题出的特别好~~~~
题意就就不说了:附上代码
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
#include <stdio.h>
#include <string>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#define eps 1e-7
#define M 1000100
#define LL __int64
#define INF 0x3f3f3f3f
#define PI 3.1415926535898
const int maxn = 1010000;
using namespace std;
int fa[maxn];
int dis[maxn];
int sum[maxn];
int mp[maxn];
int t;
int n, m;
void init()
{
for(int i = 0; i <= n+m; i++)
{
fa[i] = i;
mp[i] = i;
dis[i] = 0;
sum[i] = 1;
}
t = n+1;
}
int Find(int x)
{
if(fa[x] != x)
{
int root = Find(fa[x]);
dis[x] += dis[fa[x]];
return fa[x] = root;
}
return x;
}
int main()
{
char st[10];
while(~scanf("%d %d",&n, &m))
{
init();
int x, y;
for(int i = 0; i < m; i++)
{
scanf("%s",st);
if(st[0] == 'L')
{
scanf("%d %d",&x, &y);
x = mp[x];
y = mp[y];
int tx = Find(x);
int ty = Find(y);
if(tx != ty)
{
sum[tx] += sum[ty];
fa[ty] = tx;
dis[ty] = dis[x]+dis[y]+1;
}
}
else if(st[0] == 'Q')
{
scanf("%d %d",&x, &y);
x = mp[x];
y = mp[y];
int tx = Find(x);
int ty = Find(y);
if(tx != ty)
puts("Unknown");
else
{
if(abs(dis[x]-dis[y])%2 == 0)
puts("Same");
else
puts("Different");
}
}
else if(st[0] == 'D')
{
scanf("%d",&x);
int xx = mp[x];
int tx = Find(xx);
sum[tx] -= 1;
mp[x] = ++t;
}
else if(st[0] == 'S')
{
scanf("%d",&x);
x = mp[x];
int tx = Find(x);
printf("%d\n",sum[tx]);
}
}
}
return 0;
}