【hdu-3172】 Virtual Friends (并查集+map)

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

解题报告:

这也是一道并查集的题目,不过这道题给了不同的人名,要求把他们合并,因此用map把人名映射成数字,再来用并查集做,这道题要求多组输入,因此需要加while(scanf("%d",&n)!=EOF),一开始没加这个错了好几次。用map容器,在循环输入这种情况下,记得每次开始都要清空容器。

注意:

有一个map容器m,看m中有没有元素a,可以用!m[a]或者m.find(a)==m.end()这两种方式来判断,前者可能会快一点。如果m中本来没有a,如果m[a],这样用,那么m中会有a这个元素并且对应键值是0,不是随机的。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring> 
#include<queue>
#include<stack> 
#include<string>
#include<map>
using namespace std;
map<string,int> mm;
int f[100005];
int numb[100005];
void init()
{
	for(int i=0;i<=100004;i++)
	{
		f[i]=i;
		numb[i]=1;
	}
}
int getf(int v)
{
	if(f[v]!=v)
	f[v]=getf(f[v]);
	return f[v];
}
void merge(int u,int v)
{
	int t1=getf(u);
	int t2=getf(v);
	if(t1==t2)printf("%d\n",numb[t1]);
	else 
	{
		numb[t1]+=numb[t2];
		printf("%d\n",numb[t1]);
		f[t2]=t1;
	} 
}
char s1[25],s2[25];
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		while(n--)
		{
			int ff;
			scanf("%d",&ff);
			init();
			mm.clear();
			int num=1;//用来记录人的id
			for(int i=0;i<ff;i++)
			{
				scanf("%s%s",&s1,&s2);
				if(!mm[s1])
				{
					mm[s1]=num++;
				}
				if(!mm[s2])
				{
					mm[s2]=num++;
				}
				merge(mm[s1],mm[s2]);
			}
		}
	}
  return 0;
}

猜你喜欢

转载自blog.csdn.net/QQ_774682/article/details/81125683