A - 最近公共祖先·一 HihoCoder - 1062 暴力找lca

  • A - 最近公共祖先·一

  •  HihoCoder - 1062 
  • #include<bits/stdc++.h>
    using namespace std;
    int n,m;
    map<string,string > pre;
    void FindAnscetor(string str1,string str2)
    {
        map<string,int >book;
        book[str1]=1;
        while(!pre[str1].empty())
        {
            book[pre[str1]]=1;
            str1=pre[str1];
        }
        while(!str2.empty())
        {
            if(book[str2])
            {
                cout<<str2<<endl;
                return ;
            }
            str2=pre[str2];
        }
        printf("-1\n");
    }
    int main()
    {
        while(~scanf("%d",&n))
        {
            pre.clear();
            string str1,str2;
            for(int i=1; i<=n; i++)
            {
                cin>>str1>>str2;
                pre[str2]=str1;
            }
            scanf("%d",&m);
            for(int i=1; i<=m; i++)
            {
                cin>>str1>>str2;
                FindAnscetor(str1,str2);
            }
        }
        return 0;
    }
  •  

猜你喜欢

转载自blog.csdn.net/BePosit/article/details/83152385
今日推荐