Thursday, October 20, 2016

Solution of Uva 11504-Virtual Friend

See the problem UVa-11503

#include<bits/stdc++.h>
using namespace std;

int ar[100009];
int par(int z){                // creating disjoint set
    if(ar[z]==z) return z;
    else return par(ar[z]);
}

int main()
{
    int t, i, n;
    string x, y;
    cin>>t;                    // test case
    while(t--){
        map<string, int>mp;    // for checking inserted person is new or old
        map<string, int>mpp;//indexing against person cope with the array position
        cin>>n;
        int l=0, arr[100009]={0};
        while(n--){
            cin>>x>>y;
            mp[x]++;
            mp[y]++;
            int ans=0;
            if(mp[x]==1&&mp[y]==1){   // when both person are new
                l++;
                mpp[x]=ar[l]=l;
                l++;
                mpp[y]=ar[l]=l;
                ans=arr[l]=2;
                ar[par(mpp[x])]=par(mpp[y]);
            }
            else if(mp[x]==1||mp[y]==1){     // when one person is new
                if(mp[x]==1){
                    l++;
                    mpp[x]=ar[l]=l;
                    ans=arr[par(mpp[y])] += 1;
                    ar[par(mpp[x])]=par(mpp[y]);
                }
                else{
                    l++;
                    mpp[y]=ar[l]=l;
                    ans=arr[par(mpp[y])] = (1+arr[par(mpp[x])]);
                    ar[par(mpp[x])]=par(mpp[y]);
                }
            }
            else{                             // when no one is new
             if((par(mpp[x])==mpp[y])||(par(mpp[y])==mpp[x])||(par(mpp[x])==par(mpp[y]))){
                    // if equal any person with another parent or both parents
                    ans=arr[par(mpp[x])];
                }
                else{
                    ans=arr[par(mpp[y])] += arr[par(mpp[x])];
                    ar[par(mpp[x])]=par(mpp[y]);
                }
            }
            cout<<ans<<endl;
        }
    }
    return 0;
}

No comments:

Post a Comment