小记:欧拉图的判定还是蛮有用的
思路:因为要将所有的字符串合并,你头等于我尾的字符,这样这两个字符串才能连起来。而要所有的都连起来,那么这图就要是欧拉图。
我们可以用并查集判定字符连串是否只有一个,多余一个就不是欧拉图。必然不会有解。
而只有一个,那么就用欧拉图的判定来解决问题即可。
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
#define mst(a,b) memset(a,b,sizeof(a))
#define REP(a,b,c) for(int a = b; a < c; ++a)
#define eps 10e-8
const int MAX_ = 110;
const int N = 100010;
const int INF = 0x7fffffff;
int in[MAX_], out[MAX_], ans[MAX_];
int n,m,cnt;
int fa[MAX_];
char str[MAX_*10];
int findfa(int x)
{
if(fa[x] == x)return x;
return fa[x] = findfa(fa[x]);
}
int main() {
int T, s, t, tmp, temp;
string s1, s2;
bool flag;
scanf("%d", &T);
while(T-- && scanf("%d", &n)) {
mst(out, 0);
mst(in, 0);
REP(i, 1, 27){
fa[i] = i;
}
flag = 0;
tmp = 0;
REP(i, 1, n+1) {
scanf("%s", str);
s = str[0] - 'a' + 1;
t = strlen(str);
t = str[t-1] - 'a' + 1;
if(findfa(s) != findfa(t))fa[t] = s;
in[t] ++;
out[s] ++;
}
REP(i, 1, 27){
if(fa[i] == i && (in[i] || out[i]))++tmp;
}
if(tmp > 1){
printf("The door cannot be opened.\n");
continue;
}
s = 0; t= 0; temp = 0;
REP(i, 1, 27){
if(in[i] - out[i] == 1)++s;
else if(out[i] - in[i] == 1)++t;
else if(in[i] != out[i]) ++temp;
}
if((s == 1 && t == 1 && temp == 0) ||(!s&&!t&&!temp)){
printf("Ordering is possible.\n");
}
else
printf("The door cannot be opened.\n");
}
return 0;
}