PAT A1100 Mars Numbers (20分)


这是一个字符串映射问题,由于字符串长度可能最大有10位作用
所以不能采用hash映射来解决,但是由于字符串总共才有169种,所以直接用map进行映射更加方便;
由于字符串长度不一样,每次要读入一行,我们采用getline(cin,string)来进行一行的读入
但是由于第一行读入了n,getline函数又是从第一行开始的,所以采用getchar()或者getline空读进行第一行的跳过(debug最久的地方)
其次在判断的地方最好加一个备注来理清思路以及注重字符串转数字和数字转字符串,基础字符‘0’不要忘记

#include <map>
#include <string>
#include <iostream>
#include <algorithm>

using namespace std;
const int M = 168;
map<string ,int> marToEar;//0~168
string lower[13] = {"tret","jan", "feb", "mar", "apr","may","jun","jly","aug", "sep", "oct", "nov", "dec"};
string higher[12] = {"tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou"};

void initmar(){
    int n = M;
    int temp[2];
    string s;
    for(int i = 0;i<=n;i++){
        temp[1]= i%13;//lower
        temp[0] =i/13;//higher
        if(temp[0] ==0){
            s = lower[temp[1]];
        }else if(temp[1]!=0){
            s = higher[temp[0]-1]+" "+lower[temp[1]];
        }else{
            s = higher[temp[0]-1];
        }
        marToEar.insert(make_pair(s,i));
    }
    return;
}

bool isEar(string s){
    char flag = s[0];//只检查第一位
    if(flag<='9'&&flag>='0'){
        return true;
    }else{
        return false;
    }
}

int sToint(string s){
    int a[3];
    fill(a,a+3,0);
    int n;
    for(int i = 0;i<s.size();i++){//从低往高赋值
        a[2-i] = s[s.size()-i-1]-'0';
    }
    n = a[0]*100+a[1]*10+a[2];
    return n;
}

int main(){
    int n;
    cin>>n;
    initmar();
    string s;
    getchar();
    for(int i = 0;i<n;i++){
        
        getline(cin, s);
        if(isEar(s)==false){
            cout<<marToEar[s]<<endl;
        }else{
            int changeToint = sToint(s);
            for(map<string,int>::iterator it = marToEar.begin();it!=marToEar.end();it++){
                if(changeToint == it->second) cout<<it->first<<endl;
            }
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/shuibeng/p/13584082.html