不相交集 POJ1182 食物链

本文介绍了一种使用并查集算法解决特定问题的方法。通过定义结构体存储节点信息,包括节点的父亲节点和关系属性,实现了节点集合的创建、查找及合并操作。在主函数中,通过对输入数据的处理,完成了对并查集的初始化、查找和合并操作,并解决了错误检测的问题。
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值