POJ 1182 report solving the food chain with the right to disjoint-set

POJ 1182 report solving the food chain

Problem-solving ideas: This question is difficult at how to update the collection in the path compression and merge relationship, read other people's blog, very clever approach, indicating that point and with the same root node 0, with 1 indicating that the root node points to eat, 2 points are represented by the root node to eat, because there were only three cases, it is possible to update the relationship with 3% of the way, it is very convenient. Direct look at the code, added a note. Finally Tucao about some unknown problems that do not enter while n and m on wa, which is just the opposite problem, while using the direct wa.
Here Insert Picture Description

#include <stdio.h>
#include<iostream>
#include <algorithm>
#include<string.h>
#include<cmath>
#pragma warning(disable:4996)
#define mod 1000000007
#define ll unsigned long long
const int N = 50005;
using namespace std;
int sum[N];
int father[N];
int find(int x)
{
	if (x != father[x])
	{
		int tem = father[x];//记录上一级
		father[x] = find(father[x]);//更新最高上级,即路径压缩
		sum[x] = (sum[x] + sum[tem]) % 3;//通过该点和上一级的联系,来更新该点和根节点的联系
	}
	return father[x];
}
int main()
{
	int  n, m;
	scanf("%d%d", &n, &m);

	int ans = 0;
	memset(sum, 0, sizeof(sum));
	for (int i = 0; i <= n; i++)
	{
		father[i] = i;
	}
	while (m--)
	{
		int  d, x, y;
		scanf("%d%d%d", &d, &x, &y);
		if (x > n || y > n)
		{
			ans++;
			continue;
		}
		else if (2 == d && x == y)
		{
			ans++;
			continue;
		}
		else
		{
			int fx = find(x);
			int fy = find(y);
			if (fx != fy)//说明两个点没有在一颗树上
			{
				father[fy] = fx;
				sum[fy] = (d - 1 + sum[x] - sum[y] + 3) % 3;//现在fx是根节点,通过x和fx的关系更新fy和fx的关系,+3保证数值非负
			}
			else
			{
				if (d == 1 && sum[x] != sum[y])
					ans++;
				if (d == 2 && (sum[x] + 1) % 3 != sum[y])
					ans++;
			}
		}
	}
	printf("%d\n", ans);

}


Published 64 original articles · won praise 0 · Views 1438

Guess you like

Origin blog.csdn.net/weixin_45566331/article/details/105094754