题意:
给n个字符串,两个字符串若头尾字符相同可以连接起来,问你是否可以把n个字符串连接起来。
做法:
对于一个单词,把它头尾的字符之间连一条有向边,然后问题转化为求这个图是否存在欧拉路径。
一个有向图存在欧拉路径的判断方式:
- 图弱连通
- 所有点的入度都等于出度;或只有两个点的入度不等于出度,且这两个点一个入度-出度=1,另一个出度-入度=1.
代码:
/*************************************************************
Problem: poj 1386 Play on Words
User: bestFy
Language: C++
Result: Accepted
Time: 329MS
Memory: 660K
Submit_Time: 2018-01-24 11:19:16
*************************************************************/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cctype>
#include<cstdlib>
#include<cmath>
using namespace std;
typedef long long ll;
inline ll read() {
char ch = getchar(); ll x = 0; int op = 1;
for(; !isdigit(ch); ch = getchar()) if(ch == '-') op = -1;
for(; isdigit(ch); ch = getchar()) x = x*10+ch-'0';
return x*op;
}
inline void write(ll a) {
if(a < 0) putchar('-'), a = -a;
if(a >= 10) write(a/10); putchar('0'+a%10);
}
int n;
char s[1010];
int fa[100], in[100], out[100];
inline int getfa(int x) { return fa[x] == x ? x : fa[x] = getfa(fa[x]); }
int main() {
int test = read();
while(test --) {
n = read(); int st = 0;
memset(in, 0, sizeof in); memset(out, 0, sizeof out);
for(int i = 1; i <= 26; i ++) fa[i] = i;
for(int i = 1; i <= n; i ++) {
scanf("%s", s); int len = strlen(s);
int x = s[0]-'a'+1, y = s[len-1]-'a'+1, fx, fy;
in[y] ++; out[x] ++; st = x;
fx = getfa(x); fy = getfa(y);
if(fx != fy) fa[fx] = fy;
} bool flag = 1; int t1 = 0, t2 = 0;
for(int i = 1; i <= 26; i ++) {
if(in[i]+out[i] == 0) continue;
if(getfa(st) != getfa(i) || abs(in[i]-out[i]) > 1) { flag = 0; break; }
if(abs(in[i]-out[i]) == 1) if(in[i]-out[i] == 1) t1 ++; else t2 ++;
}
if(flag && (t1 == 0 && t2 == 0 || t1 == 1 && t2 == 1)) puts("Ordering is possible.");
else puts("The door cannot be opened.");
}
return 0;
}