食物链

这次做食物链这个题目感觉真的好懵逼,先总结出现的错误,第一个是没有注意输入形式和输出格式,直接以为输入0 0就会结束,然后又是属于输入多组数据,但是题目并没有给出这样的提示,所以wa很正常,然后就是超时,想了一下昨天有人提到把cin改成scanf就AC了,所以我也试了一下;果然AC了,真的不容易啊。然后谈一下我做这个题目的各种懵逼,最开始连题目没看懂,感觉我就没有看懂几道题目过,然后条件2和3都很好理解,一就不同了,是指和前面的有出入,就有一个为假,我居然想去知道谁真谁假,这就不可能做出来了,手动再见。但是这个条件一就是要让我们用并查集了,真为一颗树 ,假为一棵树,然后find 函数,在判断吃与被吃关系就只能参考别人的代码了,因为这里真的好懵逼。所以我也不讲解什么,继续贴网址。

http://blog.csdn.net/niushuai666/article/details/6981689

#include<cstdio>
using namespace std;
struct node{
int fa,r;
}p[50010];
int find(int x)
{
    int temp;
    if(x==p[x].fa)
        return x;
    temp=p[x].fa;
    p[x].fa=find(temp);
    p[x].r=(p[x].r+p[temp].r)%3;
    return p[x].fa;
}
int main()
{
    int n,m,num=0;int r1,r2;
    scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
    {
        p[i].fa=i;
        p[i].r=0;
    }
        for(int i=0;i<m;i++)
        {
            int d,x,y;
            scanf("%d%d%d",&d,&x,&y);
            if(d==2&&x==y)
                {num++;continue;}
            if(x>n||y>n) {num++;continue;}
            r1=find(x);r2=find(y);
            if(r1!=r2)
            {
                p[r2].fa=r1;
                p[r2].r=(3+(d-1)+p[x].r-p[y].r)%3;
            }
            else
            {
                if(d==1&&p[x].r!=p[y].r)
                {

                    num++;
                    continue;
                }
                if(d==2&&((3-p[x].r+p[y].r)%3!=d-1))
                {
                    num++;
                    continue;
                }
            }
        }printf("%d",num);
    return 0;
}

  

原文地址:https://www.cnblogs.com/yintoki/p/5691117.html