hiho 13 最近祖先问题

来源:互联网 发布:在端口1521连接失败 编辑:程序博客网 时间:2024/06/06 08:28

问题描述

在树结构中,找到两个节点的最近最先节点。

解决方法

问题规模较小时,比如100个节点,我们可以先将一个节点的所有祖先存储起来,然后另外一个节点在查找祖先的过程中查看是否有相同的祖先。

std::map的使用:

判断key是否存在用count;

#include <cstdio>#include <string>#include <iostream>#include <cstring>#include <unordered_map>#include <vector>using namespace std;unordered_map<string, int> nameToid;vector<string> names;enum {maxn = 200+4};int f[maxn];int findFirst(int p1, int p2){    int pp[maxn];    memset(pp, 0, sizeof(pp));    for (int i= p1; i!= -1; i= f[i])        pp[i]= 1;    int i;    for (i= p2; i!= -1 && !pp[i]; i= f[i])        ;    return i;}int main(){    memset(f, -1, sizeof(f));    int n;    scanf("%d", &n);    for (int i=0; i< n; i++)    {        string father, son;        cin>>father>>son;        if (!nameToid.count(father))        {            nameToid[father] = names.size();            names.push_back(father);        }        if (!nameToid.count(son))        {            nameToid[son] = names.size();            names.push_back(son);        }        f[nameToid[son]] = nameToid[father];    }    int m;    scanf("%d", &m);    for (int i=0; i< m; i++)    {        string p1, p2;        cin>>p1>>p2;        if (p1 == p2)// 注意 如果名字相等则直接输出,名字不在树中也可以。        {            cout<<p1<<endl;            continue;        }        int sp = -1;        if (nameToid.count(p1) && nameToid.count(p2))        {            sp = findFirst(nameToid[p1], nameToid[p2]);        }        if (sp== -1)            printf("-1\n");        else            cout<<names[sp]<<endl;    }    return 0;}
0 0