• 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 ;
    }
  • 相关阅读:
    【JAVASCRIPT】JS实现淘宝,百度评分功能
    【数据结构】链式线性表的几种常用用法
    【JAVASCRIPT】无刷新评论
    【JAVASCRIPT】表单序列化问题
    【JAVASCRIPT】如何不使用jquery函数和ajax框架实现ajax效果
    图灵北京作译者交流会
    是起点,而非终点——评《程序员的思维修炼》
    2011图灵新春特献
    图灵2011.01书讯
    图灵2010.12书讯
  • 原文地址:https://www.cnblogs.com/misty1/p/2615337.html
Copyright © 2020-2023  润新知