POJ1182 食物链(并查集好题)

题目链接

Description

动物王国中有三类动物A,B,C,这三类动物的食物链构成了有趣的环形。A吃B, B吃C,C吃A。
现有N个动物,以1-N编号。每个动物都是A,B,C中的一种,但是我们并不知道它到底是哪一种。
有人用两种说法对这N个动物所构成的食物链关系进行描述:
第一种说法是"1 X Y",表示X和Y是同类。
第二种说法是"2 X Y",表示X吃Y。
此人对N个动物,用上述两种说法,一句接一句地说出K句话,这K句话有的是真的,有的是假的。当一句话满足下列三条之一时,这句话就是假话,否则就是真话。
1) 当前的话与前面的某些真的话冲突,就是假话;
2) 当前的话中X或Y比N大,就是假话;
3) 当前的话表示X吃X,就是假话。
你的任务是根据给定的N(1 <= N <= 50,000)和K句话(0 <= K <= 100,000),输出假话的总数。

Input

第一行是两个整数N和K,以一个空格分隔。
以下K行每行是三个正整数 D,X,Y,两数之间用一个空格隔开,其中D表示说法的种类。
若D=1,则表示X和Y是同类。
若D=2,则表示X吃Y。

Output

只有一个整数,表示假话的数目。

Sample Input

100 7
1 101 1 
2 1 2
2 2 3 
2 3 3 
1 1 3 
2 3 1 
1 5 5

Sample Output

3

思路

使用3*N大小的数组分别对应A,B,C三种动物,对于不同的关系利用并查集建立联系,若出现矛盾情况,则进行记录。(详见代码注释)

代码

#include<map>
#include<set>
#include<stack>
#include<queue>
#include<string>
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
//#include<bits/stdc++.h>
#define pb push_back
using namespace std;
const int maxn=1e6+5;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int minn=0xc0c0c0c0;
int n,k,x[maxn],y[maxn],r[maxn],pre[maxn];
int find(int x)
{
    
    
	if(x==pre[x])
        return x;
    else
        return pre[x]=find(pre[x]);
}
void unite(int a,int b)
{
    
    
	
    int fa=find(a);
    int fb=find(b);
    if(fa!=fb)
        pre[fa]=fb;
}
bool judge(int a,int b)
{
    
    
	return find(a)==find(b);
}
int main()
{
    
    
	scanf("%d%d",&n,&k); 
	for(int i=0;i<k;i++)
		scanf("%d%d%d",&r[i],&x[i],&y[i]);//说法种类,编号 
	for(int i=0;i<=n;i++)
		pre[i]=i;
	int ans=0;
	for(int i=0;i<k;i++)
	{
    
    
		int num=r[i];
		int a=x[i]-1,b=y[i]-1;
		if(a<0||a>n-1||b<0||b>n-1)
		{
    
    
			ans++;
			continue;
		}//条件越界 
		if(num==1)//a和b是同类
		{
    
    
			if(judge(a,b+n)||judge(a,b+2*n))
				ans++;//非同类动物在同一集合中,产生矛盾
			else
			{
    
    
				unite(a,b);//A类合并
				unite(a+n,b+n);//B类合并
				unite(a+2*n,b+2*n);//C类合并 
			}
		}
		else
		{
    
    
			if(judge(a,b)||judge(a,b+2*n))
				ans++;//a,b已是同类或出现逆食物链的情况 
			else
			{
    
    
				unite(a,b+n);//A吃B 
				unite(a+n,b+2*n);//B吃C 
				unite(a+2*n,b);//C吃A 
			}
		}
	}
	printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/WTMDNM_/article/details/108802999