codevs2597 团伙

题目描述 Description

1920年的芝加哥,出现了一群强盗。如果两个强盗遇上了,那么他们要么是朋友,要么是敌人。而且有一点是肯定的,就是:

我朋友的朋友是我的朋友;

我敌人的敌人也是我的朋友。 

两个强盗是同一团伙的条件是当且仅当他们是朋友。现在给你一些关于强盗们的信息,问你最多有多少个强盗团伙。

输入描述 Input Description

输入文件gangs.in的第一行是一个整数N(2<=N<=1000),表示强盗的个数(从1编号到N)。 第二行M(1<=M<=5000),表示关于强盗的信息条数。 以下M行,每行可能是F p q或是E p q(1<=p q<=N),F表示p和q是朋友,E表示p和q是敌人。输入数据保证不会产生信息的矛盾。

输出描述 Output Description

输出文件gangs.out只有一行,表示最大可能的团伙数。

样例输入 Sample Input

6
4
E 1 4
F 3 5
F 4 6
E 1 2

样例输出 Sample Output

3

数据范围及提示 Data Size & Hint

2<=N<=1000

1<=M<=5000

1<=p q<=N

#include <iostream>
#include <stdio.h>

using namespace std;

int pre[1000 + 2] , n , m , x , y , ans , i , e[1000 + 2];
char s[10];

int find( int x )
{
    if( x == pre[x] )
        return x;
    return pre[x] = find( pre[x] );
}

void merge( int a , int b )
{
     pre[ find( a ) ] = find( b );
}

int main()
{
    scanf( "%d %d" , &n , &m );
    for( i = 1 ; i <= n ; i++ )
         pre[i] = i;
    while( m-- )
    {
        scanf( "%s %d %d" , s , &x , &y );
        if( s[0] == 'E' )
        {
            if( !e[x] )
                e[x] = y;
            else
                merge( e[x] , y );
            if( !e[y] )
                e[y] = x;
            else
                merge( e[y] , x );
        }
        else
            merge( x , y );
    }
    for( i = 1 ; i <= n ; i++ )
         if( find( i ) == i )
             ans++;
    cout << ans << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/hyfer/p/5852451.html