华电北风吹
天津大学认知计算与应用重点实验室
2016-06-24
题目链接:
http://hihocoder.com/problemset/problem/1062
题目分析:
// problem1069.cpp : 定义控制台应用程序的入口点。
// #1069 : 最近公共祖先·三
// 张正义 2016-06-20
#include "stdafx.h"
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <vector>
#include <stack>
using namespace std;
#define SIZE 40005
int father[SIZE];
stack<int> GetFatherList(int sonID)
{
stack<int> result;
while (father[sonID] != sonID)
{
result.push(sonID);
sonID = father[sonID];
}
result.push(sonID);
return result;
}
int main()
{
for (int i = 0; i < SIZE; i++)
{
father[i] = i;
}
int N, M;
cin >> N;
int count = 0;
map<string, int> namemap;
map<int, string> namemapInt;
for (int i = 0; i < N; i++)
{
string name_father, name_son;
cin >> name_father >> name_son;
int id_father = namemap[name_father];
int id_son = namemap[name_son];
if (id_father == NULL)
{
count++;
id_father = count;
namemap[name_father] = id_father;
namemapInt[id_father] = name_father;
}
if (id_son == NULL)
{
count++;
id_son = count;
namemap[name_son] = id_son;
namemapInt[id_son] = name_son;
}
father[id_son] = id_father;
}
cin >> M;
for (int i = 0; i < M; i++)
{
string name1, name2;
cin >> name1 >> name2;
int id1 = namemap[name1];
int id2 = namemap[name2];
if (id1 == NULL)
{
count++;
id1 = count;
namemap[name1] = id1;
namemapInt[id1] = name1;
}
if (id2 == NULL)
{
count++;
id2 = count;
namemap[name2] = id2;
namemapInt[id2] = name2;
}
stack<int> s1, s2;
s1 = GetFatherList(id1);
s2 = GetFatherList(id2);
if (s1.top() != s2.top())
{
cout << "-1" << endl;
}
else
{
int resultID;
while ((s1.empty() == false) && (s2.empty() == false) && (s1.top() == s2.top()))
{
resultID = s1.top();
s1.pop();
s2.pop();
}
cout << namemapInt[resultID] << endl;
}
}
return 0;
}