洛谷 P2814 家谱(并查集,裸题)

这是一篇关于洛谷P2814题目的解析,主要聚焦于并查集的应用。题目要求处理不超过50000个名字,通过离散化将名字转化为整数,然后进行并查集操作,强调了路径压缩的技术要点。
摘要由CSDN通过智能技术生成

并查集,裸题
本题要点:
1、 n <= 50000, 把名字离散化为整数,后面就是并查集的操作。压缩路径。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <string>
using namespace std;
const int MaxN = 5e4 + 10;
int fa[MaxN];
map<string, int> mp;
string s_int[MaxN];
int cnt;

int get(int x)
{
	if(x == fa[x]) 
		return x;
	return fa[x] = get(fa[x]);
}

int main()
{
	for(int i = 1; i < MaxN; ++i)
		fa[i] = i;
	string str, name, parent;
	while(cin >> str)
	{
		if(str == "$")	break;
		name = str.substr(1, 6);
		if(mp.find(name) == mp.end())		
		{
			mp[name] = ++cnt;	
			s_int[cnt] = name;
		}
		if(str[0] == '#')
		{
			parent = name;
		}else if(str[0] == '+'){
			fa[mp[name]] = mp[parent];	
		}else{
			cout << name << " " << s_int[get(mp[name])] << endl;				
		}
	}
	return 0;
}

/*
#George
+Rodney
#Arthur
+Gareth
+Walter
#Gareth
+Edward
?Edward
?Walter
?Rodney
?Arthur
$
*/

/*
Edward Arthur
Walter Arthur
Rodney George
Arthur Arthur
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值