食物链

题目描述

动物王国中有三类动物 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

两种思路

一带权并查集;

把每一个确定关系的点放到三层树中(当然要压缩的)根据到公共根的距离判断其关系。

不在同一颗树上的就并上。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<vector>
using namespace std;
int f[99999],t[99999];
int n,k,ans;
int find(int x)
{
    if(f[x]==x)    return x;
    int fx=find(f[x]);
    t[x]=(t[x]+t[f[x]]+3)%3;
    return f[x]=fx;
} 
int bing(int o,int x,int y)
{
    int fa=find(x);int fb=find(y);
    if(fa==fb)
    {
        if((-t[y]+t[x]+3)%3==(o-1))    return 0;
         return 1;
    }
    f[fa]=fb;
    t[fa]=(t[y]-t[x]+o-1+3)%3;
    return 0;
}
int main()
{
    scanf("%d%d",&n,&k);
    int c,a,b;
    ans=0;
    for(int i=0;i<=n;i++)    f[i]=i;
    for(int i=1;i<=k;i++)
    {
        scanf("%d%d%d",&c,&a,&b);
        if(a>n||b>n||a<1||b<1)    {ans++;}else
        if(c==2&&a==b)    {ans++;}else
        ans+=bing(c,a,b);
    }
    cout<<ans;
    return 0;
}

 

第二种运用反集(调了半天)掌握不太好

#include<iostream>
#include<cstdio>
#include<cstring>
#include<math.h>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
#define M 50005
int f[M*3],n,k,ans;
int find(int  x)
{
    if(f[x]!=x)    f[x]=find(f[x]);
    return f[x];
}
void bing(int x,int y)
{
    int fx=find(x),fy=find(y);
    f[fx]=fy;
}
int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n+n+n;i++)    f[i]=i;
    int o,a,b;
    for(int i=1;i<=k;i++)
    {
        scanf("%d%d%d",&o,&a,&b);
        if (a > n||b > n||a<1||b<1) {ans++; continue;}
        if(o==2&&a==b)    {ans++; continue;}
        int fa=find(a),fb=find(b);
        if(o==1)
        {
            if(find(a+n)==fb||find(a+n+n)==fb)    {ans++; continue;}
            bing(a,b);bing(a+n,b+n);bing(a+n+n,b+n+n);
        }
        if(o==2)
        {
            if(find(a+n)==fb)    continue;
            if(fa==fb||find(b+n)==fa)    {ans++; continue;};
            bing(a+n,b);bing(b+n+n,a);bing(b+n,a+n+n);
        }
    }
    cout<<ans;
    return 0;
}

 

posted @ 2017-02-26 10:57  浪矢-CL  阅读(242)  评论(0编辑  收藏  举报