3681 - 家谱
现代的人对于本家族血统越来越感兴趣,现在给出充足的父子关系,请你编写程序找到某个人的最早的祖先。
Input
输入文件由多行组成,首先是一系列有关父子关系的描述,其中每一组父子关系由二行组成,用#name的形式描写一组父子关系中的父亲的名字,用+name的形式描写一组父子关系中的儿子的名字;接下来用?name的形式表示要求该人的最早的祖先;最后用单独的一个$表示文件结束。规定每个人的名字都有且只有6个字符,而且首字母大写,且没有任意两个人的名字相同。最多可能有1000组父子关系,总人数最多可能达到50000人,家谱中的记载不超过30代。
Output
按照输入文件的要求顺序,求出每一个要找祖先的人的祖先,格式:本人的名字+一个空格+祖先的名字+回车。
Examples
Input
#George +Rodney #Arthur +Gareth +Walter #Gareth +Edward ?Edward ?Walter ?Rodney ?Arthur $
Output
Edward Arthur Walter Arthur Rodney George Arthur Arthur
Solution C++
#include <iostream> #include <map> using namespace std; map<string, string> p; string find(string x) { if (p[x] != x) p[x] = find(p[x]); return p[x]; } int main() { string s, father, child; while (cin >> s) { if (s == "$") return 0; else if (s[0] == '#') { father = s.substr(1); if (p[father] == "") p[father] = father; } else if (s[0] == '+') { child = s.substr(1); p[child] = father; } else if (s[0] == '?') { child = s.substr(1); cout << child << ' ' << find(child) << endl; } } return 0; }