Virtual Friends(hdu-3172)

HDU - 3172 传送门

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


题目大意

题目要我们求每次输入两个人后求当前的朋友圈有多少人


解题思路

这里考虑到字符串并不适合直接并查集合并,我们考虑使用的是用map给当前两个人坐标记,从而变成容易处理的并查集模式
判断是否属于同一个集合,如果是的话就直接输出当前圈子的人数,否则就进行集合合并,即认识了圈子外的人,合并之后呢当前圈子的人数总和就等于两个圈子人数之和
Final 本题要注意一下样例 text 组,是多组的 text ,可以重复输入的 text !!!

AC代码

#include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
#include<map>
using namespace std;
const int maxn = 100100;
int circle[maxn];
int fa[maxn];
void init()
{
	for(int i = 0 ; i <= maxn ; i++)
	{
		fa[i] = i;
		circle[i] = 1;
	}
}
int find(int x)
{
	return fa[x] == x?x:fa[x] = find(fa[x]);
}
void unite(int x,int y)
{
	int a = find (x);
	int b = find (y);
	if(a == b)//属于同一个圈子
	{
		printf("%d\n",circle[b]);//这个圈子当前的人数
	}else
	{
		fa[a] = b;//把b中的合并到圈子里
		circle[b] += circle[a];
		printf("%d\n",circle[b]);//即当前圈子的人数是两个不同圈子之和
	}
}
int main()
{	
	int t;
	while(scanf("%d",&t)!=EOF)
	{
		while(t--)
		{
			map<string, int>mp;
			mp.clear();
			int n;
			scanf("%d",&n);init();
			int val = 1;
			for(int i = 0 ; i < n ; i++)
			{
				string p1,p2;
				cin>>p1>>p2;
				if(mp.count(p1) == 0)//使用map方便编号,编完号就跟普通并查集一样啦
				{
					mp[p1] = val++;
				}
				if(mp.count(p2) == 0)
				{
					mp[p2] = val++;
				}
				int a = mp[p1];int b = mp[p2];
				//cout<<"测试:"<<a<<" "<<b<<endl;
				//测试:1 2

				//Barney Betty
				//测试:2 3

				//Betty Wilma
				//测试:3 4
				unite(a,b);
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46425926/article/details/107603368