BOI 2003 gang

Luo Gu P1892 [BOI2003] gang

Luo Gu Portal

Title Description

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 line of the input file is an integer gangs.in N (2 <= N <= 1000), represents the number of robbers (numbered from 1 to N). The second line M (1 <= M <= 5000), indicates the number of pieces of information about the robbers. The following M rows, each row may be F pq or E pq (1 <= p q <= N), F represents p and q are friends, E is p and q are the enemy. Input data to ensure that no conflicting information.

Output Format

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

Sample input and output

Input # 1 copy

Output # 1 copy

answer:

A good disjoint-set of questions.

The difficulty of solving the problem is how to deal with the enemy of the problem.

We use this way:

Establishing a first enemy array to store e i, if there is an enemy after it, put the enemy and e [i] can be merged.

So this question is very simple, we pay attention to the issue of statistics can be.

But I started ,, WA a point because when I judge only sentenced e [p] no sentence e [q], should be sentenced to two.

Also, pay attention to this character can not be read by scanf, because there may be a space to enter, do not believe you try.

Code:

#include<cstdio>
#include<iostream>
using namespace std;
int n,m,ans;
int fa[1001],e[1001],v[1001];
int find(int x)
{
    if(fa[x]==x)
        return x;
    return fa[x]=find(fa[x]);
}
void unionn(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
        fa[fx]=fy;
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        fa[i]=i;
    for(int i=1;i<=m;i++)
    {
        int p,q;
        char ch;
        cin>>ch>>p>>q;
        if(ch=='F')
            unionn(p,q);
        if(ch=='E')
        {
            if(!e[p])
                e[p]=q;
            else
                unionn(e[p],q);
            if(!e[q])
                e[q]=p;
            else
                unionn(e[q],p);
        }
    }
    for(int i=1;i<=n;i++)
        v[find(i)]=1;
    for(int i=1;i<=n;i++)
        if(v[i]==1)
            ans++;
    printf("%d",ans);
    return 0;
}

Guess you like

Origin www.cnblogs.com/fusiwei/p/11315550.html