• 【洛谷P2024】食物链


    题目描述

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

    分析

    知识点:并查集。

    由关押罪犯的2个集合变成了3个集合。不会做的话可以先去做关押罪犯。

    代码

    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<algorithm>
    using namespace std;
    const int maxn=50000+5;
    inline int read()
    {
        int x=0,f=1; char ch=getchar();
        while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
        while(ch>='0'&&ch<='9'){x=x*10+ch-'0'; ch=getchar();}
        return x*f;
    }
    int n,k,ans;
    int father[maxn*3];
    inline int find(int x)
    {
        if(x!=father[x]) father[x]=find(father[x]);
        return father[x];
    }
    inline void merge(int x,int y)
    {
        int r1=find(x);
        int r2=find(y);
        father[r1]=r2;
    }
    int main()
    {
        n=read();k=read();
        for(int i=1;i<=n*3;i++) father[i]=i;
        for(int i=1;i<=k;i++)
        {
            int p,x,y;
            p=read();x=read();y=read();
            if(x>n||y>n){ans++; continue;}
            if(p==1)
            {
                if(find(x+n)==find(y)||find(x+n*2)==find(y)){ans++; continue;}
                merge(x,y);
                merge(x+n,y+n);
                merge(x+n*2,y+n*2);
            }else if(p==2)
            {
                if(find(x+2*n)==find(y)||find(x)==find(y)){ans++; continue;}
                merge(x+n,y);
                merge(y+2*n,x);
                merge(y+n,x+2*n);
            }
        }
        printf("%d
    ",ans);
        return 0;
    }
        
    欢迎转载,转载请注明出处!
  • 相关阅读:
    git使用教程2-更新github上代码
    git使用教程-本地代码上传到github
    【Mac系统 + Git】之上传项目代码到github上以及删除某个文件夹
    【Mac + Appium + Python3.6学习(五)】之常用的Android自动化测试API总结
    【Mac + Python + Selenium】之PyCharm配置Selenium自动化
    appium自动化常用API
    【Mac + Appium + Python3.6学习(四)】之常用的IOS自动化测试API总结
    ubuntu指令大全
    Win10上安装双系统(win10+ubuntu)
    C语言共用体的作用
  • 原文地址:https://www.cnblogs.com/huihao/p/7618123.html
Copyright © 2020-2023  润新知