带权并查集:HDU3172-Virtual Friends

来源:互联网 发布:创维电视网络唤醒 编辑:程序博客网 时间:2024/05/20 00:13

Virtual Friends

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9179 Accepted Submission(s): 2654

Problem Description

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

1
3
Fred Barney
Barney Betty
Betty Wilma

Sample Output

2
3
4


解题心得

  • 这个是一个带权并查集,其实也没有什么新奇的,主要就是需要记录每一个string的根,这个可以用一个map来映射一下,将每一个string映射成一个数字,然后用映射的数字来进行合并就行了。
  • 这个题需要输出的东西是当前建立关系的网络里面的人数,所以需要用数组来记录一下当前根的人数就可以了。
  • 其实这个题主要处理的就是一个关于string的问题,当需要将一个string用一个数子来代替的时候可以很流畅的想到map 的映射,具体的映射操作看代码。

#include<bits/stdc++.h>using namespace std;const int maxn = 1e5+10;int father[maxn*2],ans,num[maxn*2];map <string,int> mp;//string映射成一个numberint Find(int x){    if(father[x] == x)        return x;    else        return father[x] = Find(father[x]);}void _merge(int a,int b){    int fa = Find(a);    int fb = Find(b);    if(fa != fb)    {        father[fa] = fb;        num[fb] += num[fa];//合并的时候要将不同根的网络的人数也合并起来    }    printf("%d\n",num[fb]);}int main(){    int t;    while(scanf("%d",&t) != EOF)    {        while(t--)        {            int n;            mp.clear();            ans = 1;            scanf("%d",&n);            int cnt = 0;            for(int i=0; i<=n; i++)            {                father[i] = i;                num[i] = 1;            }            for(int i=0; i<n; i++)            {                string s1,s2;                cin>>s1>>s2;                //将string用一个数字来表示                if(mp.find(s1) == mp.end())                    mp[s1] = cnt++;                if(mp.find(s2) == mp.end())                    mp[s2] = cnt++;                _merge(mp[s1],mp[s2]);            }        }    }}
原创粉丝点击