hdu 3172 Virtual Friends (并查集)

Virtual Friends

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

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
 
Source
 
Recommend
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[];
int num[];
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[],b[];
while(scanf("%d",&t)!=EOF)
while(t--)
{
map<string,int>M;
M.clear();
for(int i=;i<=;i++){
set[i]=i;num[i]=;
}
scanf("%d",&n);
int m=;
for(int i=;i<n;i++){
scanf("%s%s",a,b);
if(M[a]==) M[a]=m++;
if(M[b]==) M[b]=m++;
merge(M[a],M[b]);
}
}
return ;
} /* 6
3
1 2
2 3
3 4
5
1 2
2 3
3 4
4 4
5 1 */
上一篇:编译指令


下一篇:循序渐进学习开发RISCV-OS