Friends disjoint-set

Problem Description

There is a town with N residents. Of course, many of whom are friends of the relationship. According to a famous saying: "My friend's friend is my friend," so if A and B are friends, B and C are friends, then A and C are also friends. Your task is to calculate the largest group in this town friends to many people.

Input Format

The first line of the input file are two positive integers N and M. N represents the number of inhabitants in the town (1 <= N <= 30000), M represents the number (0 <= M <= 30000) friend relationship of these residents. Next M lines each have two integers A, B (1 <= A, B <= N, A is not equal to B), on behalf of A, B are friends. Some may be repeated this M line.

Output Format

Output file only one row, the largest town in this group many people as friends.

SAMPLE INPUT

10 12
1 2
3 1
3 4
5 4
3 5
4 6
5 2
2 1
7 10
1 2
9 10
8 9

Sample Output

6

Restrictions and conventions

Time limit: 1s

Space limitations: 128MB

#include<iostream>
using namespace std;
int f[50010],n,m,p,size[30010],ans[30010];
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),ry=find(y);
    if(rx!=ry){
        if(size[rx]>=size[ry]){f[ry]=rx;size[rx]+=size[ry];}
        else {f[rx]=ry;size[ry]+=size[rx];}
    } 
}
int main()
{
    int a,b,ds=0;
    cin>>n>>m;
    for(int i=1;i<=n;i++){f[i]=i;size[i]=1;}
    for(int i=1;i<=m;i++)
    {
        cin>>a>>b;
        merge(a,b);
    }
    for(int i=1;i<=n;i++)
    {
        ans[find(i)]++;
        if(ans[find(i)]>ds) ds=ans[find(i)];
        
    }
    cout<<ds;
    return 0;
}

 

Guess you like

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