#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <stack>
#include <assert.h>
using namespace std;
const int N = 26;
const int LENGTH = 1024;
bool G[N+2][N+2];
bool pot[N+2];
int in[N+2];
int out[N+2];
void build_G()
{
int m;
char s[LENGTH];
memset(pot, 0, sizeof(pot));
memset(G, 0, sizeof(G));
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
scanf("%d", &m);
while (m-- > 0)
{
scanf("%s", s);
int u = s[0] - 'a' + 1;
int v = s[strlen(s)-1] - 'a' + 1;
G[u][v] = true;
pot[u] = pot[v] = true;
out[u]++;
in[v]++;
}
}
bool vis[N+2];
void _dfs(int u)
{
vis[u] = true;
for (int v = 1; v <= N; v++)
if ((G[u][v] || G[v][u]) && !vis[v])
_dfs(v);
}
bool is_joint()
{
memset(vis, 0, sizeof(vis));
for (int u = 1; u <= N; u++)
if (pot[u] && !vis[u])
{
_dfs(u);
break;
}
for (int u = 1; u <= N; u++)
if (pot[u] && !vis[u])
return false;
return true;
}
bool io_check()
{
bool begin = false;
bool end = false;
for (int u = 1; u <= N; u++)
{
if (pot[u] && in[u] != out[u])
{
if (out[u] == in[u] + 1)
{
if (begin)
return false;
begin = true;
}
else if (in[u] == out[u] + 1)
{
if (end)
return false;
end = true;
}
else
return false;
}
}
return true;
}
int main()
{
int T;
scanf("%d", &T);
while (T-- > 0)
{
build_G();
if (is_joint() && io_check())
printf("Ordering is possible.\n");
else
printf("The door cannot be opened.\n");
}
return 0;
}
ACM篇:Uva 10129 -- Play on Words
最新推荐文章于 2024-02-06 19:41:10 发布