POJ 2492 A Bug's Life (并查集)

题意:Professor Hopper专门研究bug的生活习性,他表示若两只bugs的生活习性差别很大,则说明他们可能为不同的性别,但如果出现三只bugs的习性两两差别很大,则有可能出现同性恋的bug了。现在有n只bugs,和生活习性差别很大的m对bugs的编号,问这些bugs中,有没有可能出现同性恋者。


分析:并查集

//140K  719MS
#include <stdio.h>
#define N  2005
int oppoent[N] ;
int rank[N] ;
int parent[N] ;

int Find_Father ( int x )
{
    if ( x != parent[x] )
    {
        x = Find_Father ( parent[x] ) ;
    }
    return parent[x] ;
}

void Restart_Parent_Rank ( int const n )
{
    int i ;
    for ( i = 1 ; i <= n ; i ++ )
    {
        parent[i] = i ;
        rank[i] = 0 ;
        oppoent[i] = 0 ;            //记得清零。。。WA了好多次。。 
    }
}

void Union ( int const x , int const y )
{
    int pre_x , pre_y ;
    pre_x = Find_Father ( x ) ;
    pre_y = Find_Father ( y ) ;
    if ( pre_x == pre_y )
    {
        return ;
    }
    else if ( rank[pre_x] > rank[pre_y] )
    {
        parent[pre_y] = pre_x ;
    }
    else
    {
        if ( rank[pre_x] == rank[pre_y] )
        {
            rank[pre_y] ++ ;
        }
        parent[pre_x] = pre_y ;
    }
}

int
main ( )
{
   int count ;
   scanf ("%d" , & count ) ;
   int i ;
   for ( i = 1 ; i <= count ; i ++ )
   {
       int n , m ;
       scanf ("%d%d" , & n , & m ) ;
       Restart_Parent_Rank ( n ) ;
       int flag ;
       flag = 0 ;
       while ( m -- )
       {
           int x , y ;
           scanf ("%d%d" , & x , & y ) ;
           int pre_x , pre_y ;
           pre_x = Find_Father ( x ) ;
           pre_y = Find_Father ( y ) ;
           if ( pre_x == pre_y )
           {
               flag = 1 ;
               continue ;
           }
           else if ( 0 == oppoent[x] && 0 == oppoent[y] )
           {
               oppoent[x] = y ;
               oppoent[y] = x ;
           }
           else if ( 0 == oppoent[x] )
           {
               oppoent[x] = y ;
               Union ( x , oppoent[y] ) ;
           }
           else if ( 0 == oppoent[y] )
           {
               oppoent[y] = x ;
               Union ( y , oppoent[x] ) ;
           }
           else
           {
               Union ( x , oppoent[y] ) ;
               Union ( y , oppoent[x] ) ;
           }
       }
       if ( flag )
       {
           printf ("Scenario #%d:\nSuspicious bugs found!\n\n" , i ) ;
       }
       else
       {
           printf ("Scenario #%d:\nNo suspicious bugs found!\n\n" , i ) ;
       }
   }
   return 0 ;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值