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

华电北风吹
天津大学认知计算与应用重点实验室
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值