Gang disjoint-set

Problem Description

I lived in a city where n people, any two people who know is the enemy not friends, but also to meet:

1, my friend's friend is my friend;

2, the enemy of my enemy is my friend; all are friends of people of a gang. Tell you this n m pieces of information about an individual that is a friend of two people, two people or a certain enemy, you write a program to calculate the maximum number of cities may have a gang?

Input Format

The first behavior and n m, N is less than 1000, M less than 5000; when the m rows, each behavior pxy, p is 0 or 1, p is 0, x and y are represented by friends, p is 1, x represents and y is the enemy.

Output Format

An integer representing the n individual may have up to several gangs.

SAMPLE INPUT

6
4
1 1 4
0 3 5
0 4 6
1 1 2

Sample Output

3

prompt

{1},{2,4,6},{3,5}

Restrictions and conventions

Time limit: 1s

Space limitations: 128MB

#include<cstdio>
#include<iostream>
using namespace std;
int n,m,f[10010]={0},zt[10010]={0};
int find(int x)
{
    if(x==f[x]) return x;
    else return f[x]=find(f[x]);
}
void merge(int x,int y)
{
    int rx=find(x);
    int ry=find(y);
    if(rx!=ry) f[rx]=ry;
}
int main()
{
    
    int ch,x,y,ans(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        f[i]=i;
    }
    for(int i=1;i<=m;i++)
    {
        cin>>ch;
        if(ch==1)
        {
            cin>>x>>y;
            if(zt[x]==0) 
            {
            zt[x]=y;
            }
            if(zt[y]==0) 
            {
            zt[y]=x;
            }
            merge(zt[x],y);
            merge(zt[y],x);
        }
        if(ch==0)
        {
            cin>>x>>y;
            merge(x,y);
        }
    }
    for(int i=1;i<=n;i++) if(find(i)==i) ans++;
    cout<<ans;
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/hfang/p/11240002.html