EOJ2562
来源:互联网 发布:太极越狱mac 编辑:程序博客网 时间:2024/06/06 12:40
题目:http://acm.cs.ecnu.edu.cn/problem.php?problemid=2562
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;
}
- EOJ2562
- Myeclipse 10 Maven 构建 Java Web 项目
- 小兔的棋盘
- hdu 1054 Strategic Game 最小点覆盖
- 基于Arm 的linux 的启动分析
- 关于手机和各种pad的定位
- EOJ2562
- poj 2366 Sacrament of the sum 尺取法的灵活运用
- 数据挖掘过程模型研究
- 晶振两端串联和并联电阻的租用
- hadoop学习5-HDFS API学习
- DICOM医学图像处理:DIMSE消息发送与接收“大同小异”之DCMTK fo-dicom mDCM
- primary key与unique
- 学习笔记1-Metro UI
- CheckBox的API