您的位置:首页 > 其它

hdu 3172 Virtual Friends (并查集)

2014-03-24 20:31 183 查看

Virtual Friends

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


[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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).

[align=left]Output[/align]
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.

[align=left]Sample Input[/align]

1
3
Fred Barney
Barney Betty
Betty Wilma

[align=left]Sample Output[/align]

2
3
4

[align=left]Source[/align]
University of Waterloo Local Contest 2008.09

[align=left]Recommend[/align]
chenrui | We have carefully selected several similar problems for you: 3038 3234 3047 2818 2473

//875MS     1828K    1063B     G++
/*

题意:
给出n个朋友关系,朋友的朋友也是朋友,求每组关系的圈子的人数

并查集+STL:
这种做法有点小暴力,不过没想到更好的方法。
要使用并查集的路径压缩,每次更新把全部点更新到一个点上,
然后更新该改点的人数就行了。然后直接输出该点的人数。

*/
#include<iostream>
#include<string>
#include<map>
using namespace std;
int set[100005];
int num[100005];
int find(int x)
{
int r=x;
while(set[r]!=r)
r=set[r];
int i=x;
while(i!=r){  //路径压缩
int j=set[i];
set[i]=r;
i=j;
}
return r;
}
void merge(int a,int b)
{
int x=find(a);
int y=find(b);
if(x!=y){
set[y]=x;
num[x]+=num[y];
printf("%d\n",num[x]);
}else{
printf("%d\n",num[x]);
}
}
int main(void)
{
int t,n;
char a[25],b[25];
while(scanf("%d",&t)!=EOF)
while(t--)
{
map<string,int>M;
M.clear();
for(int i=1;i<=100000;i++){
set[i]=i;num[i]=1;
}
scanf("%d",&n);
int m=1;
for(int i=0;i<n;i++){
scanf("%s%s",a,b);
if(M[a]==0) M[a]=m++;
if(M[b]==0) M[b]=m++;
merge(M[a],M[b]);
}
}
return 0;
}

/*

6
3
1 2
2 3
3 4
5
1 2
2 3
3 4
4 4
5 1

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: