洛谷P2814 家谱(c嘎嘎)

题目链接:P2814 家谱 - 洛谷 | 计算机科学教育新生态

题目难度:普及/提高

解题心得 :这道题用了并查集 (貌似不怎么常用的字符串并查集),用STL 中的map将子孙和祖先连接起来,第一次接触这种做法感觉很妙,发篇题解记录下。。。。

代码部分:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;	
#define _for(i,a,b) for(int i=(a); i<(b); i++)
#define _rep(i,a,b) for(int i=(a); i<=(b); i++)
typedef long long ll;
const int N = 1e5 + 10;
map<string,string>p; 
string s,t;

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

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr),cout.tie(nullptr);
	
     char ch;
     cin >> ch;
     
     while(ch != '$')
	 {
	 	cin >> s;
	 	if(ch == '#')
	 	{
	 		t = s;
	 		if(p[s] == "") p[s] = s;
		}
		else if(ch == '+')
		{
			p[s] = t;
		}
		else 
	    	cout<<s<<' '<<find(s)<<'\n';
	    cin >> ch;
	 } 
    
	
    return 0;
}
相关推荐
iFulling2 小时前
【数据结构】第六章:图
数据结构·笔记·算法
森焱森2 小时前
出现“ping不通但可以远程连接”的情况可能由以下原因导致
linux·c语言·网络·c++
原来是猿3 小时前
蓝桥备赛(九)- 结构体和类
数据结构·c++·算法
Forget the Dream4 小时前
设计模式之中介者模式
java·c++·设计模式·中介者模式
orionyl6 小时前
深度理解指针与内存
c语言·指针
Raizeroko6 小时前
Linux - 网络套接字
linux·服务器·网络·c++·php
Murphy_lx6 小时前
数据结构(回顾)
开发语言·数据结构
修己xj7 小时前
算法系列之广度优先搜索解决妖怪和尚过河问题
算法
攻城狮7号8 小时前
【第22节】C++设计模式(行为模式)-Iterator(迭代器)模式
c++·设计模式·迭代器模式
Y1nhl9 小时前
搜广推校招面经三十八
pytorch·算法·机器学习·推荐算法·搜索算法