题意
题目描述
动物王国中有三类动物 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 句话有的是真
的,有的是假的。当一句话满足下列三条之一时,这句话就是假话,否则就是真话。
• 当前的话与前面的某些真的话冲突,就是假话
• 当前的话中 X 或 Y 比 N 大,就是假话
• 当前的话表示 X 吃 X,就是假话
你的任务是根据给定的 N 和 K 句话,输出假话的总数。
输入输出格式
输入格式:
从 eat.in 中输入数据
第一行两个整数,N,K,表示有 N 个动物,K 句话。
第二行开始每行一句话(按照题目要求,见样例)
输出格式:
输出到 eat.out 中
一行,一个整数,表示假话的总数。
输入输出样例
输入样例#1:
100 7
1 101 1
2 1 2
2 2 3
2 3 3
1 1 3
2 3 1
1 5 5
输出样例#1:
3
说明
1 ≤ N ≤ 5 ∗ 10^4
1 ≤ K ≤ 10^5
此题一开始看以为是水题,谁知道一做起来毫无头绪,只拿了30分
题解很强,原理是把动物总数乘个3分为A,B,C三个集合,关系分别是A eat B,
B eat C,C eat A;然后就是判断(裸地并查集,遗憾的是我没想出来~)
口头也无法解释再多了,还是看代码吧:
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 1000010;
int a[maxn],b[maxn],c[maxn];
int fa[maxn];
int father(int x){
return fa[x] = fa[x] == x? x : father(fa[x]);
}
int read(){
int x = 0;
char naozhaowen = getchar();
while(naozhaowen<'0' || naozhaowen>'9'){
naozhaowen = getchar();
}
while(naozhaowen>='0' && naozhaowen<='9'){
x = x*10 + naozhaowen-'0';
naozhaowen = getchar();
}
return x;
}
void merge(int x,int y){
if(father(x) == father(y))return;
fa[father(x)]=father(y);
}
int main(){
int i,j,ans=0,k,m,n;
int x,y,z;
m = read();
n = read();
for(i=1;i<=m*3;i++)fa[i] = i;
for(i=1;i<=n;i++){
x = read();
y = read();
z = read();
if(y>m||z>m){
ans++;
continue;
}
if(x==1){
if(father(y+m) == father(z) || father(y+m*2) == father(z))ans++;
else {
merge(y,z),merge(y+m,z+m),merge(y+m*2,z+m*2);
}
}
else{
if(y==z){
ans++;
continue;
}
if(father(y) == father(z) || father(y+m*2) == father(z))ans++;
else{
merge(y+m,z),merge(y+m*2,z+m),merge(y,z+m*2);
}
}
}
printf("%d\n",ans);
return 0;
}