EOJ2562

题目:http://acm.cs.ecnu.edu.cn/problem.php?problemid=2562


Virtual Friends

Time Limit:5000MSMemory Limit:65536KB
Total Submit:200Accepted:75

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

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

1
3
Fred Barney
Barney Betty
Betty Wilma

Sample Output

2
3
4

Source

waterloo local 2008


题目分析:

简单并查集,每次判断两个人是否属于同一集合,若属于同一集合,则输出集合内元素数目,否则先合并两个集合,并更新新集合的数目,然后输出新集合数目。其中可以利用map将string哈希为int数字一一对应。每次查找集合代表元素时注意压缩路径提高以后的查找效率,增加一个域用于记录当前节点所在集合内元素的数目,这个域只需对根节点(即集合代表元素)有效即可

 

AC代码:

#include <iostream>

#include <cstdio>

#include <map>

#include <string>

 

using namespace std;

int f[100005],cnt[100005];

 

int find_fa(int x){

   if(f[x]==x) return x;

   return f[x]=find_fa(f[x]);

}

 

int main()

{

   int t;

   scanf("%d",&t);

   while(t--){

       int n;

       scanf("%d",&n);

       map<string,int> m;

       int i,k=1,x,y;

       string a,b;

       for(i=0;i<100005;++i) {f[i]=i;cnt[i]=1;}

       for(i=0;i<n;++i){

           a.resize(20),b.resize(20);

           scanf("%s %s",&a[0],&b[0]);

           if(m[a])

                x=m[a];

           else m[a]=x=k++;

           if(m[b])

                y=m[b];

           else m[b]=y=k++;

           int fa=find_fa(x),fb=find_fa(y);

           if(fa==fb)

               printf("%d\n",cnt[fa]);

           else{

                f[fa]=fb;

               printf("%d\n",cnt[fb]+=cnt[fa]);

           }

           a.clear();b.clear();

       }

    }

   return 0;

}

 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值