UVA 10129 Play on Words
题目大意:判断首字母与末尾字母形成的若安路是否形成欧拉通路
解题思路:判断是否连通,然后判断度数是否为偶数(起点和终点入度和出度可以相差1)
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stack>
using namespace std;
stack<int> sta[26];
int m;
int in[26], out[26];
int flag[26];
int num;
int all;
void dfs(int a) {
flag[a] = 0;
num++;
if(num == all)
return;
while(!sta[a].empty()) {
int b = sta[a].top();
if(flag[b] == 1) {
dfs(b);
}
sta[a].pop();
}
return;
}
int main() {
int n;
cin >> n;
while(n--) {
for(int i = 0; i < 26; i++)
while(!sta[i].empty())
sta[i].pop();
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
memset(flag, 0, sizeof(flag));
int x, y;
cin >> m;
getchar();
char ch[1000];
all= 0;
for(int i = 0; i < m; i++) {
gets(ch);
x = ch[0] - 'a';
y = ch[strlen(ch)-1] - 'a';
out[x]++;
in[y]++;
sta[x].push(y);
sta[y].push(x);
if(flag[x] == 0) {
all++;
flag[x] = 1;
}
if(flag[y] == 0) {
all++;
flag[y] = 1;
}
}
num = 0;
dfs(x);
int fir = 0;
int fin = 0;
if(num == all) {
for(int i = 0; i < 26; i++) {
if(fir > 1)
break;
if(fin > 1)
break;
if(in[i] == out[i])
continue;
if(in[i] - out[i] == 1)
fir++;
else if(out[i] - in[i] == 1)
fin++;
else {
num = -1;
break;
}
}
}
if(num == all && fir - fin == 0)
printf("Ordering is possible.\n");
else
printf("The door cannot be opened.\n");
}
return 0;
}