Virtual Friends<并查集+map求解>

1899: Problem C: Virtual Friends

Time Limit: 5 Sec   Memory Limit: 128 MB
Submit: 106   Solved: 55
[ Submit][ Status][ Web Board]

Description

Problem C: Virtual Friends

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

The first line of input contains one integer specifying the number of test cases to follow. Each test case begins with a line containing an integer F, the number of friendships formed, 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

HINT

Source


这个题是第二次来做了,第一次遇见的时候不知道怎么处理字符串然后利用并查集求解,暑假集训开始后尝试了使用set集合,这里就利用map集合来对字符串进行处理,给字符串赋予了数字编号,这样就方便使用并查集求解了


#include<cstdio>
#include<cstring>
#include<cctype>
#include<algorithm>
#include<set>
#include<cstring>
#include<string>
#include<iostream>
#include<cmath>
#include<map>
using namespace std;
int f[100005],rank[100005];
int find(int a){
    if(a!=f[a])
        f[a]=find(f[a]);
    return f[a];
}
 
void union_set(int x, int y)
{
    x = find(x);
    y = find(y);
    if(x==y)//跟并查集模板有一点点不一样,因为我们要输出的是朋友圈子里的人数
    {
         printf("%d\n",rank[x]);//当两者已经在同一个朋友圈里的时候,直接输出任意一个人的rank;
    }
 
    else//结交了朋友圈外的朋友的时候,直接指定一个人的朋友圈为最后要输出的朋友圈,然后输出他们两个的rank之和
    {
        f[x] = y;
        rank[y]+=rank[x];
            printf("%d\n",rank[y]);
    }
}
 
 
int main()
{
    int t;
    scanf("%d",&t);
    map<string,int>ren;
 
    while(t--){
    for(int i=1;i<=100000;i++)
    {
        f[i]=i;
        rank[i]=1;
 
    }
        ren.clear();
        int n;
        scanf("%d",&n);
        string a,b;
        int cou=1;
        for(int i=0;i<n;i++)//利用map集合对每个字符串编号
        {
            cin>>a>>b;
            if(!ren[a])
                ren[a]=cou++;
            if(!ren[b])
                ren[b]=cou++;
        int x=ren[a];
        int y=ren[b];
        union_set(x,y);
        }
 
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值