zoukankan      html  css  js  c++  java
  • 【POJ 1182】食物链(并查集)

    三种动物,A吃B,B吃C,C吃A。那么用并查集时,还要多一个x和根的关系,吃或者被吃或者同类。合并两个需要更新和祖先的关系。这个关系可以自己画一画。

    #include<cstdio>
    #define N 50005
    struct lian
    {
        int fa;
        int re;
    } f[N];
    int find(int x)
    {
        if(x==f[x].fa)return x;
        int fa= f[x].fa;
        f[x].fa=find(fa);
        f[x].re=(f[x].re+f[fa].re)%3;
        return f[x].fa;
    }
    int ans,n,k;
    int main()
    {
        scanf("%d%d",&n,&k);
        for(int i=1; i<=n; i++)
        {
            f[i].fa=i;
            f[i].re=0;
        }
        for(int i=1; i<=k; i++)
        {
            int d,x,y;
            scanf("%d%d%d" ,&d,&x,&y);
            if(x>n||y>n)
            {
                ans++;
                continue;
            }
            int fx=find(x);
            int fy=find(y);
            if(fx!=fy)
            {
                f[fx].fa=fy;
                f[fx].re=(f[y].re-f[x].re+4-d)%3;
            }
            else
            {
                if(f[x].re!=f[y].re&&d==1)
                    ans++;
                else if(f[y].re!=(f[x].re+1)%3&&d==2)
                    ans++;
            }
        }
        printf("%d",ans);
    }
  • 相关阅读:
    SQL注入的一般步骤及防范方法
    防止SQL注入的五种方法
    document.getElementById("orderform").submit() 提交给了谁?
    页面调试-F12
    rs.last()续
    rs.last()
    14课后习题
    HashMap
    链表
    习题
  • 原文地址:https://www.cnblogs.com/flipped/p/5663893.html
Copyright © 2011-2022 走看看