您的位置:首页 > 其它

POJ 1703 Find them, Catch them (并查集&利用异或的性质优化)

2014-01-20 10:49 351 查看
http://poj.org/problem?id=1703

思路和食物链那题一样的。

完整代码:

/*297ms,1156KB*/

#include<cstdio>
#include<cstring>

int fa[100005], rk[100005];

int find(int x)
{
	if (fa[x])
	{
		int tmp = fa[x];
		fa[x] = find(fa[x]);/// 最终找到0这个根
		rk[x] ^= rk[tmp]; /// 用异或的性质优化
		return fa[x];
	}
	return x;
}

void merge(int x, int y)
{
	int xx = find(x), yy = find(y);
	if (xx != yy)
	{
		fa[yy] = xx;
		rk[yy] = rk[x] ^ rk[y] ^ 1; /// 用异或的性质优化
	}
}

int main()
{
	int t, n, m, x, y, i;
	char ch;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d%d", &n, &m);
		memset(fa, 0, sizeof(fa));///以0为根
		memset(rk, 0, sizeof(rk));
		while (m--)
		{
			getchar();
			scanf("%c%d%d", &ch, &x, &y);
			if (ch == 'D') merge(x, y);
			else
			{
				if (find(x) != find(y)) puts("Not sure yet.");
				else if (rk[x] == rk[y]) puts("In the same gang.");
				else puts("In different gangs.");
			}
		}
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: