【解题报告】食物链[codevs 1074][rqnoj 455]

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<iostream>
#define maxn 50000+10
using namespace std;
int n,k;
int fa[maxn];
int cnt[maxn];
int find(int x)
{
	if(fa[x]==x)return x;
	int tmp=fa[x];
	fa[x]=find(tmp);
	cnt[x]=(cnt[x]+cnt[tmp])%3;
	return fa[x];
}
int ans;
int main()
{
	int d,x,y;
	scanf("%d %d",&n,&k);
	for(int i=1;i<=n;i++)fa[i]=i;
	for(int i=1;i<=k;i++)
	{
		scanf("%d %d %d",&d,&x,&y);
		if(x>n||y>n)ans++;
		else if(d==2&&x==y)ans++;
		else
		{
			int fx=find(x);
			int fy=find(y);
			if(fx==fy)
			{
				if(d==1&&cnt[x]!=cnt[y])ans++;
				else if(d==2&&(cnt[x]+1)%3!=cnt[y])ans++;
			}
			else 
			{
				fa[fy]=fx;
				cnt[fy]=(cnt[x]+(d-1)+(3-cnt[y]))%3;
			}
		}
	}
	printf("%d\n",ans);
	return 0;
}

你可能感兴趣的:(【解题报告】食物链[codevs 1074][rqnoj 455])