hdu 3172 Virtual Friends(并查集+map)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3172

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来处理,还有,多组样例,接收到EOF

#pragma GCC optimize(2)
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<queue>
#include<map>
using namespace std;
const int maxn = 1e5 + 100;
const int inf = 0x3f3f3f3f;
typedef long long ll;
map<string, int>mp;
int f[maxn], num[maxn];
int t, n;
char a[25], b[25];
int find(int x)
{
	if (x == f[x])
	{
		return x;
	}
	else
	{
		return f[x] = find(f[x]);
	}
}
void _union(int a, int b)
{
	int x = find(a);
	int y = find(b);
	if (x != y)
	{
		f[x] = y;
		num[y] += num[x];
		printf("%d\n", num[y]);
	}
	else
	{
		printf("%d\n", num[y]);
	}
}
int main()
{
	//freopen("C://input.txt", "r", stdin);
	while (scanf("%d", &t) != EOF)
	{
		while (t--)
		{
			scanf("%d", &n);
			for (int i = 0; i < maxn - 1; i++)
			{
				f[i] = i;
				num[i] = 1;
			}
			mp.clear();
			int ans = 1;
			for (int i = 1; i <= n; i++)
			{
				scanf("%s%s", a, b);
				if (!mp[a])
				{
					mp[a] = ans++;
				}
				if (!mp[b])
				{
					mp[b] = ans++;
				}
				_union(mp[a], mp[b]);
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Evildoer_llc/article/details/82950653
今日推荐