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

    题目地址:POJ 1182

    一道非常经典的种类并查集的题目。

    利用互相之间的关系来进行权值的维护。

    代码例如以下:

    #include <iostream>
    #include <cstdio>
    #include <string>
    #include <cstring>
    #include <stdlib.h>
    #include <math.h>
    #include <ctype.h>
    #include <queue>
    #include <map>
    #include <set>
    #include <algorithm>
    
    using namespace std;
    int bin[60000], rank[60000];
    int find1(int x)
    {
        int y;
        if(bin[x]!=x)
        {
            y=bin[x];
            bin[x]=find1(bin[x]);
            rank[x]=(rank[x]+rank[y])%3;
        }
        return bin[x];
    }
    int main()
    {
        int n, k, p, x, y, i, flag, f1, f2, cnt=0;
        scanf("%d%d",&n,&k);
        for(i=1;i<=n;i++)
        {
            bin[i]=i;
            rank[i]=0;
        }
        while(k--)
        {
            flag=0;
            scanf("%d%d%d",&p,&x,&y);
            if(x>n||y>n||(p==2&&x==y))
            {
                cnt++;
                continue ;
            }
            f1=find1(x);
            f2=find1(y);
            if(p==1)
            {
                if(f1==f2)
                {
                    if(rank[x]!=rank[y])
                        cnt++;
                }
                else
                {
                    bin[f2]=f1;
                    rank[f2]=(rank[x]+3-rank[y])%3;
                }
            }
            else
            {
                if(f1==f2)
                {
                    if(rank[x]!=(rank[y]+1)%3)
                        cnt++;
                }
                else
                {
                    bin[f2]=f1;
                    rank[f2]=(rank[x]+2-rank[y])%3;
                }
            }
        }
        printf("%d
    ",cnt);
        return 0;
    }
    


  • 相关阅读:
    08-JS中table隔行换色
    07-JS中 li 排序
    HTML DOM 事件
    JavaScript 事件
    jQuery事件函数
    JQuery与JS对象相互转换
    jQuery中的选择器
    jQuery实现放大镜特效
    java线程(2016-4-7)
    Java 线程的转换及状态
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/6756473.html
Copyright © 2011-2022 走看看