食物链
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
Source
[Submit] [Go Back] [Status] [Discuss]
总结:起初做这个题目的时候,丝毫没有头绪,放了一段时间,再回头看的时候,感觉好了很多,下面来捋一捋思路,
对于这个题目,我先来说一下我的思路与做题所需要的辅助。
首先,这个题目的难点在于:结点与根节点之间的关系(0:是同类 1:被根吃 2:吃根),在寻找根结点的根的关系的时候,还存在剪枝的操作、结点之间关系的更新。难点也是这两点。
一、寻找根结点,剪枝操作
int find(int x)
{
if(p[x].pre==x)
return x;
int t=p[x].pre;
p[x].pre=find(t);
p[x].relation=(p[x].relation+p[t].relation)%3;
return p[x].pre;
}
详细的剪枝过程在 这篇博客中有所讲述 ::https://blog.csdn.net/lmengi000/article/details/80109392
二、节点之间关系的更新
1.
int root1 =find(a);
int root2 =find(b);
if(root1!=root2)
{
p[root2].pre=root1;
p[root2].relation=(3+(type-1)+p[a].relation-p[b].relation)%3;
}
当输入的两个结点不属于同一个集合的时候,这个时候它们的祖宗根是不同的,我们就要执行合并操作,
p[root2].pre=root1; 更新根,把两个不同的集合合并为一个集合
当集合合并了之后,还要再进一步判断两个合并的祖宗根之间的关系
p[root2].relation=(3+(type-1)+p[a].relation-p[b].relation)%3;
解释一下这一句代码,这一句代码困扰了我很久,其实理解了之后再加以数学知识,就感觉好很多,我们可以把这一句话想象成数学中的向量:
root1->root2 root1->x ; x->y ; y->root2 ,多出的就是x->y
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define N 500100
struct node
{
int pre;
int relation;
}p[N];
int n,k;
int type;
int lies=0;
int find(int x)
{
if(p[x].pre==x)
return x;
int t=p[x].pre;
p[x].pre=find(t);
p[x].relation=(p[x].relation+p[t].relation)%3;
return p[x].pre;
}
void inist()
{
for(int i=1;i<=n;i++)
{
p[i].pre=i;
p[i].relation=0;
}
}
int union_set(int type,int a,int b)
{
int root1 =find(a);
int root2 =find(b);
if(root1!=root2)
{
p[root2].pre=root1;
p[root2].relation=(3+(type-1)+p[a].relation-p[b].relation)%3;
}
else
{
if(type==1 && p[a].relation!=p[b].relation)
{
return 1;
}
if(type==2 && (3-p[a].relation+p[b].relation)%3!=(type-1))
{
return 1;
}
}
return 0;
}
int main()
{
scanf("%d%d",&n,&k);
inist();
int a,b;
for(int i=1;i<=k;i++)
{
scanf("%d%d%d",&type,&a,&b);
if(a>n || b>n)
{
lies++;
continue;
}
else if(type==2 && a==b)
{
lies++;
continue;
}
else
{
lies=lies+union_set(type,a,b);
continue;
}
}
printf("%d\n",lies);
return 0;
}