1. 程式人生 > >[HihoCoder]#1069 : 最近公共祖先·三

[HihoCoder]#1069 : 最近公共祖先·三

華電北風吹
天津大學認知計算與應用重點實驗室
2016-06-24

題目分析:

// 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; }