题目链接:P2814 家谱 - 洛谷 | 计算机科学教育新生态
题目难度:普及/提高
解题心得:这道题用了并查集(貌似不怎么常用的字符串并查集),用STL中的map将子孙和祖先连接起来,第一次接触这种做法感觉很妙,发篇题解记录下。。。。
代码部分:
#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;
}