Saturday, February 24, 2018

UVa problem solution 10608 - Friends

problem link:

Discuss: this is simple disjoint set problem. to solve this problem just use a extra array to store how much element add in a set. for that in make in makeUnion function when you check is the parent to node equal or not.then if not equal then you set ara[x]=y similar way we just count the member of the set also.such m[y]+=m[x] and just print the biggest element of the m array.there is no tricky part in this problem



#include<bits/stdc++.h>
using namespace std;
int ara[30005];
int m[30005];
int fnd(int u)
{
    if(ara[u]==u)
        return u;
    else ara[u]=fnd(ara[u]);
    return ara[u];
}
int makeUnion(int a,int b)
{
    int x=fnd(a);
    int y=fnd(b);
    if(x!=y)
    {
        ara[x]=y;
        m[y]+=m[x];
    }

}
int main()
{
    //freopen("input.txt","r",stdin);
   // freopen("output.txt","w",stdout);
    int t;
    cin >>t;
    while(t--)
    {
        int n,me,i,j,cnt=0,flag=0,a,b,mx=0;
        cin >>n>>me;
        for(i=0; i<=n; i++)
        {
            ara[i]=i;
            m[i]=1;
        }
        for(i=0; i<me; i++)
        {
            cin >>a>>b;
            makeUnion(a,b);
        }
        for(i=0;i<n;i++)
        {
            for(j=0;j<n-i;j++)
            {
                if(m[j]<m[j+1])
                    swap(m[j],m[j+1]);
            }
        }
        cout <<m[0];
        if(t>=0)
        cout <<endl;
    }
    return 0;
}

No comments:

Post a Comment