现在的位置: 首页 > 综合 > 正文

不相交集 POJ1182 食物链

2018年04月29日 ⁄ 综合 ⁄ 共 861字 ⁄ 字号 评论关闭
#include <iostream>
using namespace std;

struct node
{
	int father;
	int relation;
};

node p[50010];

void make_set(int val)
{
	p[val].father = val;
	p[val].relation = 0;
}

void init()
{
	for(int i = 0; i < 50010; ++i)
		make_set(i);
}

int find_set(int val)
{
	if(val == p[val].father)
		return val;
	int pre = p[val].father;
	p[val].father = find_set(pre);
	p[val].relation = (p[val].relation + p[pre].relation) % 3;
	return p[val].father;		
}

int main(void)
{
	//freopen("1.txt", "r", stdin);
	int n, m, r, x, y;
	int rootx, rooty;
	int error = 0;
	init();
	cin >> n >> m;
	for(int k = 1; k <= m; ++k)
	{
		//cin >> r >> x >> y;	    // cin就TLE,scanf AC 
		scanf("%d%d%d", &r, &x, &y);
		if(x > n || y > n || (r == 2 && x == y))
		{
			error++;	
			continue;
		}
			
		rootx = find_set(x); rooty = find_set(y);
		
		if(rootx != rooty)
		{
			p[rootx].father = rooty;
			p[rootx].relation = (3 - p[x].relation + r-1 + p[y].relation) % 3;
		}
		else
		{
			if(r == 1 && p[x].relation != p[y].relation)
				error++;
			else if(r == 2 && (p[y].relation + 3-p[x].relation) % 3 != (4-r)%3)
				error++;
		}
	}
	cout << error << endl;

	return 0;
}

抱歉!评论已关闭.