CSU-ACM2017暑期训练10-并查集&&HASH A-Virtual Friends HDU

来源:互联网 发布:量表数据怎么录入excel 编辑:程序博客网 时间:2024/06/01 21:57

题目:

These days, you can do all sorts of things online. For example, you can use various websites to make virtual friends. For some people, growing their social network (their friends, their friends' friends, their friends' friends' friends, and so on), has become an addictive hobby. Just as some people collect stamps, other people collect virtual friends. 

Your task is to observe the interactions on such a website and keep track of the size of each person's network. 

Assume that every friendship is mutual. If Fred is Barney's friend, then Barney is also Fred's friend.
Input
Input file contains multiple test cases. 
The first line of each case indicates the number of test friendship nest. 
each friendship nest begins with a line containing an integer F, the number of friendships formed in this frindship nest, which is no more than 100 000. Each of the following F lines contains the names of two people who have just become friends, separated by a space. A name is a string of 1 to 20 letters (uppercase or lowercase).
Output
Whenever a friendship is formed, print a line containing one integer, the number of people in the social network of the two people who have just become friends.
Sample Input
13Fred BarneyBarney BettyBetty Wilma
Sample Output
234


          题目大意:一些人组成一些朋友圈,问最大的朋友圈的人数为多少。

         思路:并查集的同时维护一个sum数组,存每个朋友圈的人数,如sum[i]表示i所在的朋友圈的人数


代码:

#include<map>#include<string>#include<cstring>#include<cstdio>#include<cstdlib>#include<cmath>#include<queue>#include<vector>#include<iostream>#include<algorithm>#include<bitset>#include<climits>#include<list>#include<iomanip>#include<stack>#include<set>const int maxn=111111;using namespace std;int t,n;int f[maxn];int sum[maxn];string a,b;map<string,int>m;int Get_f(int v){    if(f[v]==v)        return v;    else    {        f[v]=Get_f(f[v]);        return f[v];    }}int Merge(int v,int u){    v=Get_f(v);    u=Get_f(u);    if(u!=v)    {        f[u]=v;        sum[v]+=sum[u];    }    return sum[v];}int main(){    while(scanf("%d",&t)!=EOF)    {        while(t--)        {            m.clear();            for(int i=0;i<maxn;i++)            {                f[i]=i;                sum[i]=1;            }            scanf("%d",&n);            int k=1;            for(int i=0;i<n;i++)            {                cin>>a>>b;                if(!m[a])                    m[a]=k++;                if(!m[b])                    m[b]=k++;                printf("%d\n",Merge(m[a],m[b]));            }        }    }    return 0;}