家谱~map容器与并查集

在这里插入图片描述

输入样例

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

输出样例

Edward Arthur
Walter Arthur
Rodney George
Arthur Arthur

说明提示

在这里插入图片描述

AC Code

#include <iostream>
#include <string>
#include <map>
using namespace std;
map<string,string> p;
string s1,s2,s3;
string findf(string x){
	if(x == p[x])	return x;
	return p[x] = findf(p[x]);
}
int main()
{
	char tmp;
	while(cin>>tmp){
		if(tmp == '$')	break;
		else if(tmp == '#'){
			cin >> s1;
			if(p[s1] == "")	p[s1] = s1;
		}
		else if(tmp == '+'){
			cin >> s2;
			p[s2] = s1;
		}
		else{
			cin>>s3;
			cout<<s3<<' '<<findf(s3)<<endl;
		}
	}
	return 0;
}

解释与说明

〇本题思路参考自洛谷博主 zhmshitiancai
①建立map容器:map<string,string> p;,其模板为:map<key,value> VarName;,此处建立的是字符串对应字符串的词典。
②查找操作:

string findf(string x){
	if(x == p[x])	return x;
	return p[x] = findf(p[x]);
}

通过并查集,实现查找操作。 本人也是在参考思路后,才发现并查集可以和map数组结合使用,极大程度地简化了本题的思路。
③主要部分:

while(cin>>tmp){
	if(tmp == '$')	break;
	else if(tmp == '#'){
		cin >> s1;
		if(p[s1] == "")	p[s1] = s1;
	}
	else if(tmp == '+'){
		cin >> s2;
		p[s2] = s1;
	}
	else{
		cin>>s3;
		cout<<s3<<' '<<findf(s3)<<endl;
	}
}

1)建立父亲:

if(tmp == '#'){
	cin >> s1;
	if(p[s1] == "")	p[s1] = s1;
}

👆如果s1位置上没有键值,即s1作为key对应一个空的value,那么它的value和key相同。
2)建立子孙:

if(tmp == '+'){
	cin >> s2;
	p[s2] = s1;
}

👆使s2的键值成为s1,即建立一个s2到s1的索引。如果s2之前有键值,那么将会覆盖。
3)输出:cout<<s3<<' '<<findf(s3)<<endl;直接使用并查集的查找操作。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值