zoukankan      html  css  js  c++  java
  • POJ 1703 Find them,Catch them ----种类并查集(经典)

    http://blog.csdn.net/freezhanacmore/article/details/8774033?reload  这篇讲解非常好,我也是受这篇文章的启发才做出来的。

    代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    using namespace std;
    #define N 100100
    
    int fa[N],same[N];
    
    void makeset(int n)
    {
        for(int i=1;i<=n;i++)
        {
            fa[i] = i;
            same[i] = 0;
        }
    }
    
    int findset(int x)
    {
        if(x != fa[x])
        {
            int tmp = fa[x];
            fa[x] = findset(fa[x]);
            same[x] = (same[x] + same[tmp])%2;
        }
        return fa[x];
    }
    
    int unionset(char s,int a,int b)
    {
        int x = findset(a);
        int y = findset(b);
        if(x == y)    //属于同一个集合
        {
            if(s == 'A')
            {
                if(same[a] == same[b])
                {
                    return 1;  //same
                }
                else
                {
                    return 0;  //different
                }
            }
        }
        else  //不属于同一个集合
        {
            if(s == 'A')
            {
                return 2;    //unsure
            }
            else if(s == 'D')
            {
                fa[x] = y;
                same[x] = (same[a] + same[b] + 1)%2;
            }
        }
        return 3;  //要加,这是对其他情况的处理,因为此函数必须返回一个值
    }
    
    int main()
    {
        int t,n,m,i;
        char ss[5];
        int a,b;
        scanf("%d",&t);
        while(t--)
        {
            scanf("%d%d",&n,&m);
            makeset(n);
            for(i=0;i<m;i++)
            {
                scanf("%s %d %d",ss,&a,&b);
                if(unionset(ss[0],a,b) == 1)
                {
                    cout<<"In the same gang."<<endl;
                }
                else if(unionset(ss[0],a,b) == 0)
                {
                    cout<<"In different gangs."<<endl;
                }
                else if(unionset(ss[0],a,b) == 2)
                {
                    cout<<"Not sure yet."<<endl;
                }
            }
        }
        return 0;
    }
    View Code

    作者:whatbeg
    出处1:http://whatbeg.com/
    出处2:http://www.cnblogs.com/whatbeg/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    更多精彩文章抢先看?详见我的独立博客: whatbeg.com

  • 相关阅读:
    移动端meta标签
    document.ready 和 window.onload
    axios 源码分析
    vue 中的 el
    安卓和Ios 手机兼容性
    一些移动端问题
    Python 局部变量与全局变量
    Linux常用命令大全(非常全!!!)
    Python_爬虫_基础
    linux 常用命令
  • 原文地址:https://www.cnblogs.com/whatbeg/p/3498416.html
Copyright © 2011-2022 走看看