欧拉回路,利用并查集来实现;
代码:
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
int a[],f[],b[];
bool vis[]; int find(int x)
{
return f[x]==-?x:f[x]=find(f[x]);
} void combine(int x,int y)
{
int n=find(x);
int m=find(y);
if(n!=m) f[n]=m;
} bool oula()
{
int st=-;
for(int i=; i<; i++)
{
if(a[i]||b[i])
if(st==-)st=find(i);
else if(st!=find(i)) return false;
}
vector<int>v;
for(int i=; i<; i++)
if(a[i]!=b[i])
v.push_back(a[i]-b[i]);
return v.size()==||v.size()==&&v[]*v[]==-;
} int main()
{
int t,n;
char s[];
scanf("%d",&t);
while(t--)
{
memset(a,,sizeof a);
memset(f,-,sizeof f);
memset(b,,sizeof b);
int ans=,cnt=;
bool flag=;
scanf("%d",&n);
for(int i=; i<n; i++)
{
scanf("%s",&s);
int l=strlen(s);
int x=s[]-'a',y=s[l-]-'a';
a[x]++,b[y]++;
combine(x,y);
}
if(oula()) printf("Ordering is possible.\n");
else puts("The door cannot be opened.");
}
return ;
}