2021秋季《数据结构》_EOJ 1082. Virtual Friends

题目

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.在这里插入图片描述

思路

并查集应用,开map
需要注意的是,结构体不能作为map的key,而std::map是一个有序关联容器,它会在内部给key值排序,由此报错。于是新开一个getCnt记录count。

代码

#include<bits/stdc++.h>
using namespace std;
#define MAXN 100001

struct node
{
	string name = "0";
};



string findSet(map<string, node>& parent, string s)
{
	string tmp = s;
	while (parent[tmp].name != "0")
	{
		tmp = parent[tmp].name;
	}
	while (s != tmp)
	{
		string t = parent[s].name;
		parent[s].name = tmp;
		s = t;
	}
	return tmp;
}

string unionSet(map<string, node>& parent, map<string, int>& getCnt,node first, node next)
{
	string s1 = first.name;
	string s2 = next.name;
	string root1 = findSet(parent, s1);
	string root2 = findSet(parent, s2);
	//cout << "s1=" << s1 << ' ' << "s2=" << s2 << ' ' << "root1=" << root1 << ' ' << "root2=" << root2 << endl;
	if (root1 == root2)
		return root1;
	int tmpCnt = getCnt[root1] + getCnt[root2];
	// cout << "tmpCnt=" << tmpCnt << endl;
	if (getCnt[root1] >= getCnt[root2])
	{
		parent[root2].name = root1;
		getCnt[root1] = tmpCnt;
		//cout << "root1=" << root1 << ' ' << getCnt[root1] << endl;
		return root1;
	}
	else
	{
		parent[root1].name = root2;
		getCnt[root2] = tmpCnt;
		return root2;
	}
}

int main()
{
	int t; cin >> t;
	for (int q = 0; q < t; q++)
	{
		map<string, node> parent;
		map<string, int> getCnt;
		int f; cin >> f;
		for (int i = 0; i < f; i++)
		{
			node first, next;
			cin >> first.name >> next.name;
			if (parent.count(first.name) == 0)
				getCnt[first.name] = 1;
			if (parent.count(next.name) == 0)
				getCnt[next.name] = 1;
			string tmpRes = unionSet(parent, getCnt, first, next);
			//cout << '*' << tmpRes << endl;
			cout << getCnt[tmpRes] << endl;

		}
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值