题解:UVA508 摩尔斯密码 Morse Mismatches
题意:
输入每个字母的 Morse 编码、一个词典以及若干个编码。对于每个编码,判断它可能是哪个单词。如果有多个单词精确匹配,任选一个输出并且后面加上“!”;如果无法精确匹配,可以在编码尾部增加或删除一些字符以后匹配某个单词(增加或删除的字符应尽量少)。如果有多个单词可以这样匹配上,任选一个输出并且在后面加上“?”。
摩尔斯电码的细节参见原题。
分析:
输入时,首先建立对应 Morse 编码的映射 map。每输入一个单词,通过这个 map 将每一个字符翻译成 Morse 编码,然后建立所有 Morse 编码到对应单词的映射。
然后对于每一个输入的 Morse 编码
如果不存在对应的
代码:
#include <bits/stdc++.h>
#define _for(i, a, b) for(int i = (a); i < (b); ++ i)
#define _rep(i, a, b) for(int i = (a); i <= (b); ++ i)
using namespace std;
unordered_map<char, string> morse;
unordered_map<string, vector<string> > context;
// a 是 b 的前缀
bool isPrefixOf(const string& a, const string& b) {
return a.size() < b.size() && b.compare(0, a.size(), a) == 0;
}
void solve(const string& m) {
if(context.count(m)) {
const auto& v = context[m];
assert(!v.empty());
cout << v.front();
if(v.size() > 1) cout << "!";
cout << "\n";
return ;
}
map<int, string> ans;
for(const auto& p : context) {
const string& cm = p.first;
if(isPrefixOf(m, cm)) ans[cm.size() - m.size()] = p.second.front();
else if(isPrefixOf(cm, m)) ans[m.size() - cm.size()] = p.second.front();
}
cout << ans.begin()->second << "?" << "\n";
}
string C, M;
signed main() {
while(cin >> C && C != "*") {
cin >> M;
assert(C.size() == 1);
morse[C[0]] = M;
}
while(cin >> C && C != "*") {
M.clear();
for(auto c : C) M += morse[c];
context[M].push_back(C);
}
while(cin >> M && M != "*") solve(M);
return 0;
}