题目描述

实现
码前思考
- 由于输入存在空格,所以需要一次性输入字符串,使用
getline(cin,string)
;
代码实现
#include <cstdio>
#include <iostream>
#include <map>
#include <string>
using namespace std;
map<int,string> mpLow;
map<int,string> mpHigh;
map<string,int> reMpLow;
map<string,int> reMpHigh;
string input;
void trans2Mars(){
int number = stoi(input);
if(number >= 13){
cout<<mpHigh[number/13];
if(number%13 != 0){
cout<<" "<<mpLow[number%13]<<endl;
}else{
cout<<endl;
}
}else{
cout<<mpLow[number]<<endl;
}
}
void trans2Earth(){
if(input.size() >= 5){
int high = reMpHigh[input.substr(0,3)]*13;
int low = reMpLow[input.substr(4,input.size()-4)];
int res = high+low;
printf("%d\n",res);
}else{
if(reMpLow.count(input)){
int res = reMpLow[input];
printf("%d\n",res);
}else{
int res = reMpHigh[input]*13;
printf("%d\n",res);
}
}
}
int main(){
mpLow[0] = "tret";
mpLow[1] = "jan";
mpLow[2] = "feb";
mpLow[3] = "mar";
mpLow[4] = "apr";
mpLow[5] = "may";
mpLow[6] = "jun";
mpLow[7] = "jly";
mpLow[8] = "aug";
mpLow[9] = "sep";
mpLow[10] = "oct";
mpLow[11] = "nov";
mpLow[12] = "dec";
mpHigh[1] = "tam";
mpHigh[2] = "hel";
mpHigh[3] = "maa";
mpHigh[4] = "huh";
mpHigh[5] = "tou";
mpHigh[6] = "kes";
mpHigh[7] = "hei";
mpHigh[8] = "elo";
mpHigh[9] = "syy";
mpHigh[10] = "lok";
mpHigh[11] = "mer";
mpHigh[12] = "jou";
for(map<int,string>::iterator it = mpLow.begin();it!=mpLow.end();it++){
reMpLow[it->second] = it->first;
}
for(map<int,string>::iterator it = mpHigh.begin();it!=mpHigh.end();it++){
reMpHigh[it->second] = it->first;
}
int N;
scanf("%d\n",&N);
while(N--){
getline(cin,input);
if(input[0] >= '0' && input[0] <= '9'){
trans2Mars();
}else{
trans2Earth();
}
}
return 0;
}
码后反思
- 这道题目我把它想复杂了,其实直接用数组
hash
就好了,没有必要使用map
; - 柳神的代码如下:
#include <iostream>
#include <string>
using namespace std;
string a[13] = {"tret", "jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec"};
string b[13] = {"####", "tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou"};
string s;
int len;
void func1(int t) {
if (t / 13) cout << b[t / 13];
if ((t / 13) && (t % 13)) cout << " ";
if (t % 13 || t == 0) cout << a[t % 13];
}
void func2() {
int t1 = 0, t2 = 0;
string s1 = s.substr(0, 3), s2;
if (len > 4) s2 = s.substr(4, 3);
for (int j = 1; j <= 12; j++) {
if (s1 == a[j] || s2 == a[j]) t2 = j;
if (s1 == b[j]) t1 = j;
}
cout << t1 * 13 + t2;
}
int main() {
int n;
cin >> n;
getchar();
for (int i = 0; i < n; i++) {
getline(cin, s);
len = s.length();
if (s[0] >= '0' && s[0] <= '9')
func1(stoi(s));
else
func2();
cout << endl;
}
return 0;
}
- 如果
getline()
函数之前还有换行没有吸收,一定要先吸收,不然getline()
就会读取这个换行了。。。比如上面的代码中:scanf("%d\n",&N);
while(N--){
getline(cin,input);
if(input[0] >= '0' && input[0] <= '9'){
trans2Mars();
}else{
trans2Earth();
}
}