uva 10129 dfs

#include<bits/stdc++.h>
using namespace std;
const int maxm=30;
int vis[maxm],son,far,in[maxm],out[maxm],G[maxm][maxm];
void dfs(int u)
{
    vis[u]=true;
    for(int i=0;i<maxm;i++)
        if(G[u][i]&&!vis[i])
        dfs(i);
}
int main()
{
    string str;
    int kase;
    cin>>kase;
    while(kase--)
    {
        int n,cnt=0,n_in=0,n_out=0,start=0;
        cin>>n;
        memset(in,0,sizeof(in));
        memset(out,0,sizeof(out));
        memset(G,0,sizeof(G));
        memset(vis,0,sizeof(vis));
        for(int i=0; i<n; i++)
        {
            cin>>str;
            far=str[0]-'a';
            son=str[str.size()-1]-'a';
            out[far]++;
            in[son]++;
        }
        for(int i=0; i<27; i++)
        {
            if(in[i]!=out[i])
            {
                if(in[i]==out[i]+1)
                    n_in++;
                else if(in[i]+1==out[i])
                    n_out++,start=i;
                else n_in+=maxm;
            }
            if(start==0&&in[i]==out[i])
                start=i;
        }
        //cout<<start<<endl;
        if((n_in==1&&n_out==1)||(n_in==0&&n_out==0))
            dfs(start);
        for(int i=0;i<27;i++)
            if(!vis&&(in[i]||out[i]))
                cnt++;
        if(cnt!=0||!((n_in==1&&n_out==1)||(n_in==0&&n_out==0)))
            cout<<"The door cannot be opened."<<endl;
        else cout<<"Ordering is possible."<<endl;
    }
    return 0;
}

你可能感兴趣的:(uva 10129 dfs)