题目链接如下:
这道题我觉得题意有点问题,它写“If multiple context words match morse perfectly, then select the matching word with the fewest characters.”,但按这个题意写的代码无法AC,只能选择最先perfectly match的那个词。
AC代码如下:
#include <cstdio>
#include <string>
#include <map>
#include <vector>
#include <string.h>
#include <algorithm>
#include <iostream>
const int INF = 10000;
int pivot, minGap, pivotGap;
std::vector<std::string> word, strVec;
char ch[11];
std::string s;
std::map<char, std::string> mp;
bool flag;
int calGap(std::string a, std::string b){
for(int i = 0; i < std::min(a.size(), b.size()); ++i){
if(a[i] != b[i]){
return INF;
}
}
return std::max(a.size(), b.size()) - std::min(a.size(), b.size());
}
int main(){
while(scanf("%s", ch) == 1 && ch[0] != '*'){
std::cin >> s;
mp[ch[0]] = s;
}
while(scanf("%s", ch) == 1 && ch[0] != '*'){
std::string str;
for(int i = 0; i < strlen(ch); ++i){
str += mp[ch[i]];
}
word.push_back(ch);
strVec.push_back(str);
}
while(std::cin >> s && s != "*"){
bool exclamation = false;
flag = false;
minGap = INF;
for(int i = 0; i < strVec.size(); ++i){
if(strVec[i] == s){
if(!flag){
pivot = i;
flag = true;
} else{
exclamation = true;
}
} else{
int tmp = calGap(s, strVec[i]);
if(tmp < minGap){
minGap = tmp;
pivotGap = i;
}
}
}
if(flag){
printf("%s%s\n", word[pivot].c_str(), exclamation ? "!" : "");
} else{
printf("%s?\n", word[pivotGap].c_str());
}
}
return 0;
}