原题链接:https://vjudge.net/problem/UVA-508
分类:函数
备注:阅读理解,中级模拟
前言:能成功主要还是感谢一篇博客:https://blog.csdn.net/mrcrack/article/details/53048026。因为不想用C++的东西,好不容易才找到一篇C的,这有点久远的东西了,而且描述的意思并没有很清楚,有点乱,但是看了他怎么处理翻译摩尔斯电码的代码,终于让我搞出来了…
分析
其实每一步都挺好操作的,主要还是要理解好题目意思。先把摩尔斯电码以及context的单词存下来,并且直接把单词翻译出的电码也存下来以用于后续比较。
主要还是精准匹配,模糊匹配的问题。我不知道其它的正确方式,但是我AC的代码中,精准匹配只有一个则直接输出,精准匹配有多个输出则输出第一个再加感叹号。如果是模糊匹配则输出第一个再加问号。可能既没有精准匹配也没有模糊匹配。设题目给的摩尔斯电码和用来比较的context中的单词翻译成的电码中更小的长度为len,则从第一个字符到第len个字符都应该是相等才是模糊匹配,否则不匹配。如果完全没匹配的输出context中的第一个。
并没有按字典序排序,而是直接用的context的单词顺序。
代码如下:
#include<stdio.h>
#include<string.h>
const int inf = 0x3f3f3f3f;
int cnt;
struct str
{
char code[20] = { 0 };//不超过6个
}c[256];
struct context
{
int len;
char word[20] = { 0 };//不超过10个
char decode[105] = { 0 };//不超过80个
context() { len = 0; }
}wd[110];//不超过100个
char read()
{
char ch = getchar();
while (ch == ' ' || ch == '\n')ch = getchar();
return ch;
}
void In_code()//存Morse码
{
while (1)
{
char x = read();
if (x == '*')break;
scanf("%s", c[x].code);
}
}
void In_word()//存单词
{
while (1)
{
scanf("%s", wd[cnt].word);
if (wd[cnt].word[0] == '*')break;
int chang = strlen(wd[cnt].word), xb = 0;
for (int i = 0; i < chang; i++)
for (int j = 0; c[wd[cnt].word[i]].code[j] != NULL; j++)
wd[cnt].decode[xb++] = c[wd[cnt].word[i]].code[j];
wd[cnt++].len = xb;
}
}
void translate()//翻译
{
while (1)
{
char mor[105] = { 0 };
scanf("%s", mor);
if (mor[0] == '*')break;
int ans = 0, num = 0, chang = strlen(mor);
for (int i = 0; i < cnt; i++)
if (chang == wd[i].len)
if (strcmp(wd[i].decode, mor) == 0)
{
num++;
if (num == 2)break;
ans = i;
}
if (num)//精确匹配
{
printf("%s", wd[ans].word);
if (num == 2)printf("!");
printf("\n");
continue;
}
int len = inf, cha, common;//模糊匹配
for (int i = 0; i < cnt; i++)
{
for (common = 0; common < chang && common < wd[i].len; common++)
if (wd[i].decode[common] != mor[common]) break;
if (common == chang)cha = wd[i].len - chang;
else if (common == wd[i].len)cha = chang - wd[i].len;
else cha = inf;//完全不匹配
if (cha < len) {len = cha; ans = i; }
}
printf("%s?\n", wd[ans].word);
}
}
int main(void)
{
In_code();
In_word();
translate();
return 0;
}