1386

/*
欧拉回路或者通路的判定

对于有向图:

欧拉通路的判定:出了两个顶点外,所有顶点的入度和出度相等。另外的两个顶点的出度比入度大一,入度比出度大1
欧拉回路的盘点:所有点的出度和入度相等

对于无向图:
欧拉通路的判定:连通,只有两个奇度顶点
欧拉回路的判定:连通,全是偶度顶点

还需要判断是否连通图
*/

// include file
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <ctime>

#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <bitset>

#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <list>
#include <functional>

using namespace std;

// typedef
typedef long long LL;
typedef unsigned long long ULL;

// 
#define read freopen("in.txt","r",stdin)
#define write freopen("out.txt","w",stdout)
#define FORi(a,b,c) for(int i=(a);i<(b);i+=c)
#define FORj(a,b,c) for(int j=(a);j<(b);j+=c)
#define FORk(a,b,c) for(int k=(a);k<(b);k+=c)
#define FORp(a,b,c) for(int p=(a);p<(b);p+=c)
#define FORii(a,b,c) for(int ii=(a);ii<(b);ii+=c)
#define FORjj(a,b,c) for(int jj=(a);jj<(b);jj+=c)
#define FORkk(a,b,c) for(int kk=(a);kk<(b);kk+=c)

#define FF(i,a)    for(int i=0;i<(a);i++)
#define FFD(i,a)   for(int i=(a)-1;i>=0;i--)

#define Z(a) (a<<1)
#define Y(a) (a>>1)

const double eps = 1e-6;
const double INFf = 1e10;
const int INFi = 1000000000;
const double Pi = acos(-1.0);

template<class T> inline T sqr(T a){return a*a;}
template<class T> inline T TMAX(T x,T y)
{
	if(x>y) return x;
	return y;
}
template<class T> inline T TMIN(T x,T y)
{
	if(x<y) return x;
	return y;
}
template<class T> inline void SWAP(T &x,T &y)
{
	T t = x;
	x = y;
	y = t;
}
template<class T> inline T MMAX(T x,T y,T z)
{
	return TMAX(TMAX(x,y),z);
}


// code begin
int T,N,sz;
int in[27],out[27];
bool mp[27][27];
bool used[27];
char st[1010];

bool Isok()
{
	int cnt1 = 0,cnt2 = 0;
	FORi(0,26,1)
	{
		in[i] = in[i] - out[i];
		if(in[i]==1)
			cnt1++;
		else if(in[i]==-1)
			cnt2++;
		else if(in[i]!=0)
			return false;
	}
	if(cnt1!=cnt2) return false;
	if(cnt1>1) return false;
	return true;
}

void dfs(int i)
{
	used[i] = true;
	FORj(0,26,1)
	{
		if(!used[j] && mp[i][j] && (in[j]!=0 || out[j]!=0))
		{
			dfs(j);
		}
	}
}

bool Iscon()
{
	int cnt = 0;
	FORi(0,26,1)
	{
		if( !used[i] && (in[i]!=0 || out[i]!=0) )
		{
			cnt++;
			dfs(i);
		}
	}
	if(cnt>1) return false;
	return true;
}

int main()
{
	read;
	write;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&N);
		memset(in,0,sizeof(in));
		memset(out,0,sizeof(out));
		memset(mp,0,sizeof(mp));
		memset(used,0,sizeof(used));
		FORi(0,N,1)
		{
			scanf("%s",st);
			sz = strlen(st);
			out[st[0]-'a']++;
			in[st[sz-1]-'a']++;
			mp[st[0]-'a'][st[sz-1]-'a'] = mp[st[sz-1]-'a'][st[0]-'a'] = 1;
		}
		if(Iscon() && Isok()) printf("Ordering is possible.\n");
		else
			printf("The door cannot be opened.\n");
	}
	return 0;
}
posted @ 2011-04-07 10:51  AC2012  阅读(311)  评论(0编辑  收藏  举报