POJ 1182 / Noi 01 먹이 사슬 (수집 & 코드 최적화)

2052 단어 C++ACMpoj병 찰 집
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
", 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
", cnt); return 0; }

좋은 웹페이지 즐겨찾기