acwing 784. gang of robbers

Questions surface:

1920 Chicago, there was a group of bandits.

If the two robbers met, then they are either friends or enemies.

And one thing is certain, that is:

My friend's friend is my friend;

My enemy's enemy is my friend.

Two robbers condition is the same gang if and only if they are friends.

Now to give you some information about the robbers, you have to ask the maximum number of bandit gangs.

Input Format

The first row contains an integer number N, the robber (numbered from 1 to N).

The second row contains an integer M, represents the number of pieces of information about the robbers.

Next M lines, each line may be F pq or E pq, F represents p and q are friends, E represents p and q are the enemy.

Input data to ensure that no conflicting information.

Output Format

Output only one line that indicates the maximum number of groups possible.

data range

2N10002≤N≤1000,
1M50001≤M≤5000,
1p,qN1≤p,q≤N

SAMPLE INPUT

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

Sample Output

3
Solution:
understanding
1. The friend of a friend is my friend
2. The enemy of my enemy is my friend;
3. the enemy's friend and my relationship uncertain
Code
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
int fa[1010],f[1010],vis[1010];//f数组存敌人
int find(int x)
{
    return fa[x]==x?x:fa[x]=find(fa[x]);
}
void uoion1(int x,int y)
{
    x=find(x);
    y=find(y);
    if(x==y)
    return;
    fa[x]=y;
}
int main()
{
    int n,m;char ch;int x,y;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    fa[i]=i;
    while(m--)
    {
        cin>>ch>>x>>y;
        if(ch=='F')
        {
            uoion1(x,y);
        }
        else
        {
            if(!f[x])//a没有敌人,
            f[x]=y;
            else
            uoion1(y,f[x]);
            if(!f[y])
            f[y]=x;
            else
            uoion1(x,f[y]);
        }
    }
    int cnt=0;
    for(int i=1;i<=n;i++)
    {
        if(!vis[find(i)])
        {
            cnt++;
            vis[find(i)]=1;
        }
    }
    printf("%d\n",cnt);
    return 0;
}

 



Guess you like

Origin www.cnblogs.com/flyljz/p/11627523.html