暑假訓練 Play on Words (UVA
題目描述: Some of the secret doors contain a very interesting word puzzle. The team of archaeologists has to solve it to open that doors. Because there is no other way to open the doors, the puzzle is very important for us. There is a large number of magnetic plates on every door. Every plate has one word written on it. The plates must be arranged into a sequence in such a way that every word begins with the same letter as the previous word ends. For example, the word ‘acm’ can be followed by the word ‘motorola’. Your task is to write a computer program that will read the list of words and determine whether it is possible to arrange all of the plates in a sequence (according to the given rule) and consequently to open the door. Input
程式碼如下:
#include<cstdio>
#include<string.h>
#include<string>
#include<iostream>
using namespace std;
int in[26];
int out[26];
int graph[26][26];
int vis[26];
void dfs(int a)
{
for(int i = 0; i < 26; i++)
{
if(!vis[i] && (graph[a][i] || graph[i][a]))
{
vis[i] = 1;
dfs(i);
}
}
}
bool euler()
{
int cnt = 0, a = 0, b = 0;
for(int i = 0; i < 26; i++)
{
if((in[i] || out[i]) && !vis[i])
{
vis[i] = 1;
dfs(i);
cnt++;
}
}
if(cnt != 1)return false;
for(int i = 0; i < 26; i++)
{
if(in[i] == out[i])continue;
b++;
if(b > 2)return false;
if(in[i] - out[i] == 1){a++;continue;}
else if(out[i] - in[i] == 1){a += 2;continue;}
return false;
}
if(a != 3 && a != 0)return false;
else return true;
}
int main()
{
int t, n;
string a;
scanf("%d", &t);
while(t--)
{
memset(in, 0, sizeof in);
memset(out, 0, sizeof out);
memset(graph, 0, sizeof graph);
memset(vis, 0, sizeof vis);
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
cin>>a;
int a1 = a[0] - 'a';
int a2 = a[a.size()-1] - 'a';
in[a1]++;
out[a2]++;
graph[a1][a2] = 1;
}
if(!euler())printf("The door cannot be opened.\n");
else printf("Ordering is possible.\n");
}
return 0;
}
離散數學學過歐拉回路後,第一次真正使用。。。 歐拉回路的判斷標準:入讀等於出度,或僅有兩點入讀不等於出度,且這兩點其一入度比出度大一,另一點出度比入讀大一。還有就是要判斷所有點都在歐拉回路中。。。 感覺判斷的方法都很巧妙,真的學到了…………