zoukankan      html  css  js  c++  java
  • poj 1703 Find them, Catch them 【并查集 新写法的思路】

    题目地址:http://poj.org/problem?id=1703

    Sample Input

    1
    5 5
    A 1 2
    D 1 2
    A 1 2
    D 2 4
    A 1 4
    

    Sample Output

    Not sure yet.
    In different gangs.
    In the same gang.
    
    题目解读:T组数据,每组输入n m,n代表有n个人, m代表有m次操作。
    操作A x y:表示询问x y的关系是怎样的? 三中情况:不确定,属于同一个集合, 不属于同一个集合
    操作D x y:表示x y一定不属于同一个集合。

    分析:set[]分成两部分:一部分是下标1-->n 另一部分是n+1-->2*n
    这些元素初始化祖先都为自己,当我查询a、b的关系时候,如果findset(a)和 findset(b)与findset(b+n)都不相等,说明a b的关系不确定
    若findset(a)==findset(b),则说明a b属于同一个集合。否则findset(a)必然等于findset(b+n),a b不属于同一个集合。

    在将两个元素划分到不同的集合中的时候,判断:findset(a)!=findset(b+n)??? 如果不等于说明a b可以划分到不同的集合,
    然后将他们划分到不同的集合。

    代码:(这是参考一本书上写的新写法, 思路也有新的调整,当然还是并查集的思想)
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <math.h>
    #include <iostream>
    #include <string>
    #include <queue>
    #include <stack>
    #include <algorithm>
    #define N 100000+10
    
    using namespace std;
    int n, m;
    int set[N+N];
    
    int findset(int x)
    {
        if(set[x]<0) return x;
        return set[x]=findset(set[x]);
    }
    
    int main()
    {
        int tg; scanf("%d", &tg);
        int i, j, k;
        while(tg--)
        {
            scanf("%d %d", &n, &m);
            memset(set, -1, sizeof(set));
            char s[3]; int a, b;
            while(m--)
            {
                scanf("%s %d %d", s, &a, &b);
                if(s[0]=='A')
                {
                    if(findset(a)!=findset(b) && findset(a)!=findset(b+n))
                        printf("Not sure yet.
    ");
                    else if(findset(a)==findset(b))
                        printf("In the same gang.
    ");
                    else
                        printf("In different gangs.
    ");
                }
                else
                {
                    if(findset(a)!=findset(b+n)){
                        set[findset(a)]=findset(b+n);
                        set[findset(b)]=findset(a+n);
                    }
                }
            }
        }
        return 0;
    }
    
    
    
  • 相关阅读:
    青魔法圣堂法术 Django的技术栈(持续更新)
    青魔法圣堂法术 Django REST framework (DRF) 框架(持续更新)
    Python无法卸载的解决办法
    Django开发social-auth-app-django 第三方登陆
    【转载】青魔法圣堂法术Django项目知识点汇总
    基于session 的springMvc 国际化
    java导出生成csv文件
    mybatis + log4j 打印mybatis的sql
    spring Mvc + Mybatis 中使用junit
    spring官网项目
  • 原文地址:https://www.cnblogs.com/yspworld/p/4731935.html
Copyright © 2011-2022 走看看