uva 921 - A Word Puzzle in the Sunny Mountains

contents

  1. 1. Problem
  2. 2. Sample Input
  3. 3. Sample Output
  4. 4. Solution

Problem

將一個數字對應一個字母,現在已經有一些字典的單字,先將 seed 字串對應到第一組加密數字。接著找到一種對應方式,使得每一組加密數字都可以對應到字典單字中。

Sample Input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
1
11
7
1 2 3 4 5 3 0
1 5 1 0
1 6 3 4 0
7 3 4 8 1 0
9 3 4 8 1 0
9 1 9 10 11 0
10 11 6 3 0
ADORNO
ADORNO
AMOR
ANA
ARLINDO
ANTUNES
HORTA
PORTA
PORTAO
PORTAL
PAPEL
PARVO
ELMO
ESTE
ESSE
ARMADURA
HELENA
ERGONOMICO
EVA
ERVA
CARMO
COUVE
*

Sample Output

1
ADORNMHTPEL

Solution

題目看起來挺嚇人,直接窮舉即可,保證只有一解。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <string.h>
using namespace std;
int match[105][105], msize[105];
char seed[105], dictionary[105][105];
int dlen[105];
int mp[52];
int N, M, D;
int dfs(int idx) {
if(idx == N) {
int f = 1;
for(int i = 1; i <= M; i++)
f &= mp[i] != -1;
return f;
}
for(int i = 0; i < D; i++) {
if(dlen[i] != msize[idx]) continue;
int ok = 1;
for(int j = 0; j < msize[idx] && ok; j++) {
if(mp[match[idx][j]] != -1 && mp[match[idx][j]] != dictionary[i][j])
ok = 0;
}
if(ok) {
int cp[52];
for(int i = 1; i <= M; i++) cp[i] = mp[i];
for(int j = 0; j < msize[idx] && ok; j++)
mp[match[idx][j]] = dictionary[i][j];
if(dfs(idx+1)) return 1;
for(int i = 1; i <= M; i++) mp[i] = cp[i];
}
}
return 0;
}
int main() {
int testcase;
scanf("%d", &testcase);
while(testcase--) {
scanf("%d %d", &M, &N);
for(int i = 0; i < N; i++) {
int j;
for(j = 0; scanf("%d", &match[i][j]) && match[i][j]; j++);
msize[i] = j;
}
scanf("%s", seed);
memset(mp, -1, sizeof(mp));
for(int i = 0; seed[i]; i++)
mp[match[0][i]] = seed[i];
for(D = 0; scanf("%s", &dictionary[D]) && dictionary[D][0] != '*'; D++) {
dlen[D] = strlen(dictionary[D]);
}
dfs(0);
for(int i = 1; i <= M; i++)
printf("%c", mp[i]);
puts("");
}
return 0;
}