好久没有刷OJ了,今天从zoj随便抓起一道题,短短几十行,费了三个小时才搞定!真是荒了啊,眼高手低要不得,以后要坚持练习,唯熟能生巧。
问题的网址:
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1068
本题的思路其实很简单:
先从字符转换成摩斯密码,同时记下每个字符对应的数字,再反过来读数字并结合摩斯密码输出对应的字符即可。关键在于怎么映射,更快捷的方法是用hash或则map。
总结本次coding待解决的主要问题:
1.没有想清楚算法(尤其是细节!!)就开始写代码,导致越写越晕,越写越乱,陷入“泥沼”。
以后应该先写出算法或者好歹写出思路。
2.很多常用函数都忘记了,以及一些tricks,还得搜索然后再学习,也算是温习了吧。
3.还想补充下debug,有问题千万不能上火,impossible is no bug,耐下心来一点点看。
自己惯用的是先检查代码逻辑,包括看流程和用例测试,重点看条件和边界,再就是通过输出来判断代码各阶段是否ok,实在不行只好断点调试,再再不行重写吧...
附上最后AC的代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char dict[30][5] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "..--", "---.",".-.-", "----" };
char key[30] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_', '.', ',', '?' };
char code[1000],tmp[7];
int seq[110],tag;
int convert2(char letter){
if (letter >= 'A' && letter <= 'Z'){
strcat(code, dict[letter - 'A']);
return strlen(dict[letter - 'A']);
}
if (letter == '_')
strcat(code, dict[26]);
if (letter == '.')
strcat(code, dict[27]);
if (letter == ',')
strcat(code, dict[28]);
if (letter == '?')
strcat(code, dict[29]);
return 4;
}
void convert(char message[]){
memset(code, 0, sizeof(code));
int k = strlen(message);
tag = 0;
for (int i = 0; i<k; i++)
seq[i]=convert2(message[i]);
for (int i = k - 1; i >= 0; i--){
memset(tmp, 0, sizeof(tmp));
for (int j = 0; j < seq[i]; j++){
tmp[j] = code[tag++];
}
for (int j = 0; j < 30; j++){
if (strcmp(tmp, dict[j]) == 0){
printf("%c", key[j]);
break;
}
}
}
}
int main()
{
int num=0,n;
char message[110];
scanf("%d", &n);
getchar(); // !!
while (num<n){
num++;
gets(message);
printf("%d: ", num);
convert(message);
printf("\n");
}
return 0;
}