把每个莫斯密码存下来然后一一对应就可以了。
紫书上描述有问题。 第一:如果有多个精确匹配的, 要输出字典序最小的, 这里因为他给的序列就是按字典序排好的, 所以输出第一个精确匹配的; 第二: 只要是模糊匹配, 都要输出“?”。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <string>
#include <algorithm>
#define MAXN 110
using namespace std;
int morse_n, dic_n;
string s, morse_code[MAXN], morse_secret[MAXN], dic[MAXN], morse_dic[MAXN];
int main() {
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif // ONLINE_JUDGE
int i, j;
char c;
morse_n = 0;
while(cin >> c) {
if(c == '*') break;
morse_code[morse_n] = c;
cin >> morse_secret[morse_n++];
}
while(cin >> s) {
if(s == "*") break;
int len = s.size();
dic[dic_n] = s;
for(i = 0; i < len; i++) {
for(j = 0; j < morse_n; j++)
if(morse_code[j][0] == s[i]) break;
morse_dic[dic_n] += morse_secret[j];
}
dic_n++;
}
while(cin >> s) {
if(s == "*") break;
int match = 0;
for(i = 0; i < dic_n; i++) {
if(morse_dic[i] == s) {
if(!match) cout << dic[i];
match++;
}
}
if(match > 1) cout << "!\n";
else if(match == 1) cout << "\n";
else {
int match_n = 0, best_match = 100;
for(i = 0; i < dic_n; i++) {
int MAX_LEN = max(s.size(), morse_dic[i].size());
int MIN_LEN = min(s.size(), morse_dic[i].size());
for(j = 0; j < MIN_LEN; j++)
if(s[j] != morse_dic[i][j]) break;
if(j == MIN_LEN&& MAX_LEN - MIN_LEN < best_match) {
match_n = i;
best_match = MAX_LEN - MIN_LEN;
}
}
cout << dic[match_n] << "?\n";
}
}
return 0;
}