1044 火星数字 (20分)
火星人是以 13 进制计数的:
地球人的 0 被火星人称为 tret。
地球人数字 1 到 12 的火星文分别为:jan, feb, mar, apr, may, jun, jly, aug, sep, oct, nov, dec。
火星人将进位以后的 12 个高位数字分别称为:tam, hel, maa, huh, tou, kes, hei, elo, syy, lok, mer, jou。
例如地球人的数字 29 翻译成火星文就是 hel mar;而火星文 elo nov 对应地球数字 115。为了方便交流,请你编写程序实现地球和火星数字之间的互译。
输入格式:
输入第一行给出一个正整数 N(<100),随后 N 行,每行给出一个 [0, 169) 区间内的数字 —— 或者是地球文,或者是火星文。
输出格式:
对应输入的每一行,在一行中输出翻译后的另一种语言的数字。
输入样例:
4
29
5
elo nov
tam
输出样例:
hel mar
may
115
13
思路:
先说一下这个题需要注意的地方:
1.火星文中十位有数字而个位是零的时候,如13,对应的火星文是"tam"而不是“tam tret”
2.火星文在输入的时候中间可能会带空格,所以要用get一类的函数,还要处理掉多余的换行符。
常见的思路是:先判断输入的火星文还是地球文,然后朝另一个转化。
实际上在有一个常见的做题思路就是——打表,我看了很多博客,很少有人用这种方法。
首先数字的范围很小,使得打表成为可能。而且,火星文和地球文其实是一对一的关系,所以,把每一个地球文转成火星文,然后用哈希表链接起来,就很方便了。
统计数据:
题解 方法一:
#include <bits/stdc++.h>
using namespace std;
int n,tp;
unordered_map<string,string> dict;
string numb,gewei[]={"tret","jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec"};
string shiwei[]={"tret","tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou"};
int main(){
for(int i=0;i<169;i++){ //磨刀不误砍柴工,先打表
string tmpst="";
i/13? tmpst += shiwei[i/13]:""; //如果有十位则先把十位写好
if(i%13!=0 || i==0){ //处理个位上的数字,则需要处理个位上的数字
i/13 ? tmpst += " ":""; //如果十位和个位均需要输出,中间加空格
tmpst += gewei[i%13]; //写好个位上的字母
}
dict[to_string(i)] = tmpst; //用哈希表将数字和火星文建立双向的链接
dict[tmpst] = to_string(i);
}
scanf("%d%c",&n,&tp); //tp是为了吸收掉换行符,scanf和get系列函数一起使用时尤其要注意。
for(int i=0;i<n;i++){
getline(cin,numb);
cout<< dict[numb] << "\n";
}
return 0;
}
题解 方法二:
传统方法
#include <bits/stdc++.h>
using namespace std;
int n,tp,k;
unordered_map<string,int> dict;
string numb,digit,tps,gewei[]={"tret","jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec"};
string shiwei[]={"tret","tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou"};
int main(){
for(int i=0;i<=12;i++){ //把字符串转换成对应的地球数字
dict[gewei[i]] = i;
dict[shiwei[i]] = i*13;
}
for(scanf("%d%c",&n,&tp);n;n--){
getline(cin,numb);
if(isdigit(numb[0])){ //地球文转火星文
string tmps = "";
int k = stoi(numb);
k/13? tmps+=shiwei[k/13] : "";
if(k%13!=0 || k==0){
k/13? tmps += " " : "";
tmps += gewei[k%13];
}
printf("%s\n",tmps.c_str());
}
else{ //火星文转地球文
stringstream stream(numb);
k=0;
while(stream >> tps)
k += dict[tps];
printf("%d\n",k);
}
}
return 0;
}