POJ-1703-Find them, Catch them
本题并查集~
成功tle。原因:使用cin。我心想:1e5的数据量似乎不是很大呀?emmm太年轻了
题目大意:有两个帮派。龙帮和蛇帮。
D a b 代表a和b是不同的帮派
A a b 查询a和b是不是同一个帮派
输出结果。
做题思路:小tips:初始化fa[]。开两倍大的空间。
mix(a, b + n)
mix (b, a + n)
代表的是a和b + n所属相同的帮派
b和a + n所属相同的帮派。
从而确定a和b所属不同的帮派。(因为只有两个帮派嘛)
后来更改的过程中如果遇到先前更改过的,就会将两个相同的帮派的元素归属在一起。
奇妙的思路,并查集得用熟练了!然后记得路径压缩,不然可能会tle。
代码部分:
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 2e5 + 10;
int fa[N];
void init(int n)
{
for (int i = 1; i <= n; i++)
{
fa[i] = i;
}
}
int find(int x)
{
if (x != fa[x])
{
fa[x] = find(fa[x]);
}
return fa[x];
}
int same(int x, int y)
{
return find(x) == find(y);
}
void mix(int x, int y)
{
int xx = find(x);
int yy = find(y);
if (xx != yy)
{
fa[yy] = xx;
}
}
int main()
{
int t;
scanf ("%d", &t);
while (t--)
{
char op;
int x, y;
int n, m;
scanf ("%d%d", &n, &m);
init(2 * n);
for (int i = 1; i <= m; i++)
{
getchar();
scanf ("%c%d%d", &op, &x, &y);
if (op == 'D')
{
mix(x, y + n);
mix(y, x + n);
}
else
{
if (same(x, y) || same(x + n, y + n))
{
cout << "In the same gang.\n";
}
else if (same(x, y + n) || same(y, x + n))
{
cout << "In different gangs.\n";
}
else
{
cout << "Not sure yet.\n";
}
}
}
}
return 0;
}