【Problem Description】
Modern people are more and more interested in the blood of the family, and now given enough father-son relationship, please write a program to find the earliest ancestor of a person.
[Input format] gen.in
The input file consists of multiple lines. First, it is a series of descriptions about parent-child relationships. Each group of parent-child relationships consists of two lines. The name of the father in a group of parent-child relationships is described in the form of #name , and described in the form of +name The name of the son in a group of parent-child relationships; then use the form of ?name to indicate the earliest ancestor of the person; finally use a single $ to indicate the end of the file. It is stipulated that each person's name has only 6 characters, and the first letter is capitalized, and no two people have the same name. There may be at most 1,000 groups of father-son relationships, the total number may reach 50,000 at most , and the records in the family tree do not exceed 30 generations.
[Output format] gen.out
According to the required order of the input file, find out the ancestors of each person who is looking for ancestors. The format is: my name + a space + ancestor's name + enter.
【Problem solving ideas】
It's just an ordinary union search problem, but the processing of strings is very troublesome, and then encountered a magical BUG . . .
Mapping arrays (associative containers) need to be used to realize the mutual conversion from numbers to names and names to numbers;
It should be noted that the number given to the name must be the number of its first occurrence
sample input
#George
+Rodney
#Arthur
+ Gareth
+Walter
#Gareth
+Edward
?Edward
?Walter
?Rodney
?Arthur
$
sample output
Edward Arthur
Walter Arthur
Rodney George
Arthur Arthur
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
using namespace std;
map<string, int> name;
map<int, string> num;
int fa[50005];
string s, ss;
int i, j, k, len, father, t;
int find(int x)
{
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
int main()
{
for (i = 1; i <= 50000; ++i)
fa[i] = i;
while (cin >> s && s != "$")
{
if (s[0] == '#' || s[0] == '+')
{
ss = s.substr(1, s.size() - 1);
if (!name.count(ss))
name[ss] = ++t, num[t] = ss;
if (s[0] == '#')
father = name[ss];
if (s[0] == '+')
{
int f1 = name[ss], f2 = find(father);
fa[f1] = f2;
}
}
if (s[0] == '?')
{
ss = s.substr(1, s.size() - 1);
cout << ss << " " << num[find(name[ss])] << endl;
}
}
return 0;
}