zoukankan      html  css  js  c++  java
  • poj 2492 A Bug's Life(并查集)

    题意:有N只虫子和M个配对关系,问是否有两个虫子是同性的。

    思路:这题和1703题很相似,也是判断两个虫子是否在一个集合中,稍微一改上一题的代码就行了。

    1、输入两个虫子的编号,先判断这两个虫子是否是在一个集合,若是,直接标记。

    2、若不是,判断一下这两只虫子在上面是否给出了配对关系,若没有,则它的相反数组就记录这组数据中它的相反虫子的编号。

    3、若已经给出,则直接将它们相反虫子的编号连接起来。

    代码:

    View Code
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <iostream>
    #include <algorithm>
    #include <queue>
    #include <math.h>
    #define N 2004
    using namespace std ;
    
    int f[N] , opp[N] ;
    
    void init( int n )
    {
        int i ;
        for ( i = 0 ; i <= n ; i++ )
        {
            f[i] = i ;
            opp[i] =  0;
        }
    }
    
    int find ( int x )
    {
        if ( x != f[x] )
        f[x] = find ( f[x] );
        return f[x] ;
    }
    
    int main()
    {
        int cas , n , m , x , y , i ;
    
        scanf ( "%d", &cas );
        for ( int c = 1 ; c <= cas ; c++ )
        {
            scanf ( "%d%d" , &n , &m );
            init( n ) ;
            int flag = 0 ;
            for ( i = 1 ; i <= m ; i++ )
            {
                scanf( "%d%d" , &x , &y );
                if ( flag )
                continue ;
                x = find ( x ) ;
                y = find ( y ) ;
                if ( x == y )
                {
                    flag = 1 ;
                    continue ;
                }
                if ( !opp[x] ) opp[x] = y ;
                if ( !opp[y] ) opp[y] = x ;
                opp[x] = find ( opp[x] ) ;
                opp[y] = find ( opp[y] ) ;
                f[opp[x]] = y ;
                f[opp[y]] = x ;
            }
            printf ( "Scenario #%d:\n" , c );
            if ( !flag )
            {
                printf ( "No suspicious bugs found!\n" );
            }
            else
            {
                printf ( "Suspicious bugs found!\n" );
            }
            if ( c != cas )
            printf( "\n" );
        }
        return 0 ;
    }
  • 相关阅读:
    Java基础之多线程没那么复杂!
    高性能Java RPC框架Dubbo与zookeeper的使用
    Java 学习之集合类(Collections)
    Java中List与数组互相转化
    AOJ-542-Window/POJ-2823-Window
    HDU-1074-Doing Homework
    HDU-5365-Run
    HDU-5366-The mook jong
    HDU-5391-Zball in Tina Town
    AOJ-351-求最值之差
  • 原文地址:https://www.cnblogs.com/misty1/p/2615337.html
Copyright © 2011-2022 走看看