这一题是典型的欧拉道路题目。 欧拉道路的定义是: 除了起点和终点外, 其他点的“进出” 次数应该相等。
换句话说,除了起点和终点外, 其他点的度数应该是偶数。
对于有向图, 则必须其中一个点的出度恰好比入度大1, 另一个的入度比出度大。
如果奇点数不存在的话, 则可以从任意点出发,最终一定会回到该点(成为欧拉回路)。
题目给的单词量比较大,但是有用的只有首和尾的字母,所以只需要存首尾字母就可以了。
欧拉道路还有关键的一部是判断这一个图是连通的, 并且只有一个一个连通分支。
这个可以用并查集的方法, 也可一用dfs直接搜索。
// Created by Chenhongwei in 2015.
// Copyright (c) 2015 Chenhongwei. All rights reserved.
#include"iostream"
#include"cstdio"
#include"cstdlib"
#include"cstring"
#include"climits"
#include"queue"
#include"cmath"
#include"map"
#include"set"
#include"stack"
#include"vector"
#include"sstream"
#include"algorithm"
using namespace std;
typedef long long ll;
int T,n,cnt;
int v[100][100],tmp[100][100];
int euler(int u)
{
for(int v=1;v<=26;v++)
{
if(tmp[u][v])
{
tmp[u][v]--;
euler(v);
cnt++;
}
}
return 0;
}
int main()
{
//ios::sync_with_stdio(false);
// freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
cin>>T;
string s;
while(T--)
{
cin>>n;
memset(v,0,sizeof v);
for(int i=1;i<=n;i++)
{
cin>>s;
int x=s[0]-'a'+1,y=s[s.size()-1]-'a'+1;
// cout<<x<<' '<<y<<endl;
v[x][y]++;
}
for(int i=1;i<=26;i++)
{
cnt=0;
memcpy(tmp,v,sizeof v);
euler(i);
if(cnt==n)break;
}
// cout<<cnt<<endl;
if(cnt==n)
cout<<"Ordering is possible."<<endl;
else
cout<<"The door cannot be opened."<<endl;
}
return 0;
}