POJ 1182 / Noi 01 食物链 (并查集&代码优化)

http://poj.org/problem?id=1182


/*219ms,784KB*/

#include<cstdio>
#include<cstring>
const int mx = 50005;
const int mxadd = 3 * 50000;

int fa[mx], rk[mx];

int find(int x)
{
	if (~fa[x])
	{
		int tmp = fa[x];
		fa[x] = find(fa[x]);
		rk[x] += rk[tmp]; ///从根节点向下更新
		return fa[x];
	}
	return x;
}

void merge(int x, int y, int dis)
{
	int rx = find(x), ry = find(y);
	fa[ry] = rx; ///把y加到x之下
	rk[ry] = rk[x] - rk[y] + dis;
	///rk可正可负,重点是rk[x]和rk[y]在模3同余类中是否相差0或1
	///相差0说明x和y属同一类,相差1(或者-2,修正后为1)说明x吃y
}

int main()
{
	memset(fa, -1, sizeof(fa));
	int n, k, d, x, y, cnt = 0;
	scanf("%d%d", &n, &k);
	while (k--)
	{
		scanf("%d%d%d", &d, &x, &y);
		if (x > n || y > n) ++cnt;
		else if (find(x) == find(y)) {if ((rk[y] - rk[x] + mxadd) % 3 != d - 1) ++cnt;}
		else merge(x, y, d - 1);
	}
	printf("%d\n", cnt);
	return 0;
}


另一种解法:

/*266ms,1532KB*/

#include<cstdio>
#include<cstring>
const int mx = 3 * 50000 + 5;

int fa[mx], rk[mx];

void init(int n)
{
	for (int i = 0; i < n; ++i)
		fa[i] = i;
}

int find(int x) {return fa[x] == x ? x : fa[x] = find(fa[x]);}

void merge(int x, int y)
{
	x = find(x), y = find(y);
	if (x == y) return;
	if (rk[x] < rk[y])
		fa[x] = y;
	else
	{
		fa[y] = x;
		if (rk[x] == rk[y]) ++rk[x];
	}
}

int main()
{
	int n, k, d, x, y, cnt = 0;
	scanf("%d%d", &n, &k);
	init(n * 3);
	while (k--)
	{
		scanf("%d%d%d", &d, &x, &y);
		--x, --y;
		if (x < 0 || x >= n || y < 0 || y >= n)
		{
			++cnt;
			continue;
		}
		if (d == 1)
		{
			if (find(x) == find(y + n) || find(x) == find(y + n * 2)) ++cnt;
			else
			{
				merge(x, y);
				merge(x + n, y + n);
				merge(x + n * 2, y + n * 2);
			}
		}
		else
		{
			if (find(x) == find(y) || find(x) == find(y + n * 2)) ++cnt;
			else
			{
				merge(x, y + n);
				merge(x + n, y + n * 2);
				merge(x + n * 2, y);
			}
		}
	}
	printf("%d\n", cnt);
	return 0;
}

你可能感兴趣的:(C++,ACM,poj,并查集)