AcWing 1253. 家谱
原题链接
简单
作者:
王小强
,
2021-03-02 16:43:48
,
所有人可见
,
阅读 284
把原问题转化成的N叉树的问题(只需记录当前节点的父结点是谁?)
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
string name;
struct Person {
string name;
Person* parent;
Person(string _name) : name(_name), parent(nullptr) {};
~Person() {};
};
unordered_map<string, Person*> humans;
vector<string> queries;
Person* find(const string& name) {
Person* p = humans[name];
if (!p) {
p = new Person(name);
humans[name] = p;
}
return p;
}
// 找爷爷 (一直向上找,直到没有parent)
string findGrandFather(const string& name) {
Person* p = find(name);
while (p->parent) p = p->parent;
return p->name;
}
int main(void) {
Person *parent, *p;
parent = p = nullptr;
while (cin >> name, name != "$") {
char op = name[0];
name = name.substr(1);
switch (op) {
case '#': parent = find(name); break;
case '+': p = find(name); p->parent = parent; break;
case '?': queries.emplace_back(name); break;
}
}
for (const auto& name : queries)
cout << name << ' ' << findGrandFather(name) << endl;
}