洛谷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;
}
相关推荐
wadesir21 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
yugi98783821 小时前
基于MATLAB实现协同过滤电影推荐系统
算法·matlab
TimberWill21 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit21 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
leoufung21 小时前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
OliverH-yishuihan1 天前
开发linux项目-在 Windows 上 基于“适用于 Linux 的 Windows 子系统(WSL)”
linux·c++·windows
七禾页丫1 天前
面试记录12 中级c++开发工程师
c++·面试·职场和发展
wifi chicken1 天前
数组遍历求值,行遍历和列遍历谁更快
c语言·数据结构·算法
qingyun9891 天前
深度优先遍历:JavaScript递归查找树形数据结构中的节点标签
前端·javascript·数据结构
胡楚昊1 天前
NSSCTF动调题包通关
开发语言·javascript·算法