ACM-ICPC北京赛区2018重现赛 A题

题目链接:http://hihocoder.com/contest/icpcbeijing2018/problem/1

具体思路:dfs,判断矛盾就可以了。

AC代码:

#include<iostream>
#include<string>
#include<cstring>
#include<iomanip>
#include<algorithm>
#include<stack>
#include<stdio.h>
#include<cmath>
#include<map>
#include<vector>
using namespace std;
# define inf 0x3f3f3f3f
# define maxn 100+100
# define ll long long
map<string,bool>vis;
map<string,int>q;
int father[maxn];
int k;
void dfs(int t1,int t2)
{
    if(k==1)return ;
    if(t1==t2)
    {
        k=1;
        return ;
    }
    if(father[t1]==t1)return ;
    dfs(father[t1],t2);
}
int main()
{
    ios::sync_with_stdio(false);
    int n;
    while(cin>>n)
    {
        vis.clear();
        q.clear();
        int flag=0;
        for(int i=1; i<=maxn; i++)
        {
            father[i]=i;
        }
        int s1,s2;
        int num=0;
        string t1,t2;
        for(int i=1; i<=n; i++)
        {
            cin>>t1>>t2;
            if(vis[t1]==0)
            {
                vis[t1]=1;
                q[t1]=++num;
            }
            if(vis[t2]==0)
            {
                vis[t2]=1;
                q[t2]=++num;
            }
            k=0;
            dfs(father[q[t1]],q[t2]);
            if(k==1&&flag==0)
            {
                flag=1;
                cout<<t1<<" "<<t2<<endl;
            }
            father[q[t2]]=q[t1];
        }
        if(flag==0)cout<<0<<endl;
    }
    return 0;
}

 

posted @ 2018-11-11 21:37  Let_Life_Stop  阅读(271)  评论(0编辑  收藏  举报