专栏文章

P2814 家谱 题解

P2814题解参与者 1已保存评论 0

文章操作

快速查看文章及其快照的属性,并进行相关操作。

当前评论
0 条
当前快照
1 份
快照标识符
@minejwg5
此快照首次捕获于
2025/12/02 01:07
3 个月前
此快照最后确认于
2025/12/02 01:07
3 个月前
查看原文

P2814 家谱 题解

比较有意思的并查集
CPP
#include <iostream>//可以用map将自己和祖先联系在一起 并查集
using namespace std;
#include <map>
map<string,string> root;
string find(string x){
	if(x == root[x]) return root[x];
	else return root[x] = find(root[x]);
}
int main(){
	string name,father_name;
	char ch; cin >> ch;
	while(ch != '$'){
		cin >> name;
		if(ch == '#'){
			father_name = name;
			if(root[name] == "") root[name] = name;//如果没有祖先 指向自己 
		}else if(ch == '+') root[name] = father_name;
		else //询问 
			cout << name << " " << find(name) << '\n';
		cin >> ch;
	}
	return 0;
}

评论

0 条评论,欢迎与作者交流。

正在加载评论...