poj-1182 种类并查集

转: 用0  1   2 分别表示A B C的关系。
0吃1,1吃2,2吃0.
注意这个编号都是以根结点为参照的,不是绝对的。
开一个val数组,一开始这个数组为0,所有的点都是独立的,不是相连的,没有关系。
慢慢加入点之后,把有关系的合并在一起,并且编号的相对大小确定一个集合中的关系。


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <iomanip>

using namespace std;

int n, k, d, x, y;
int fa[50010];
int rankk[50010];
int ans;

int findd(int x)
{
	if (fa[x] == -1)
		return x;

	int tmp = findd(fa[x]);

	rankk[x] += rankk[fa[x]];
	rankk[x] %= 3;

	return fa[x] = tmp;
}

int main()
{
	scanf("%d %d",&n,&k);
	{
		
		memset(fa,-1,sizeof(fa));
		memset(rankk,0,sizeof(rankk));

		ans = 0;

		while (k--)
		{
			scanf("%d %d %d", &d, &x, &y);

			if (x > n || y > n)
			{
				ans++;
				continue;
			}

			int fx = findd(x);
			int fy = findd(y);

			if (fx == fy)
			{
				if (d == 1 && rankk[x] != rankk[y])
					ans++;
				if (d == 2 && (rankk[x] + 1) % 3 != rankk[y])
					ans++;
			}
			else
			{
				if (d == 1)
				{
					fa[fy] = fx;
					rankk[fy] = rankk[x] - rankk[y];
					rankk[fy] = (rankk[fy] + 3) % 3;
				}
				else
				{
					fa[fy] = fx;
					rankk[fy] = rankk[x] - rankk[y] + 1; 
					rankk[fy] = (rankk[fy] + 3) % 3;
				}

			}
		}
		printf("%d\n",ans);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值