经典算法之-英文日期C++版

发布时间 2024-01-06 18:02:38作者: 神奇的萝卜丝

因为考研机试的原因,C和C++最好都准备一下,所以有C++版本。

#include <iostream>
#include <cstring>
#include <map>
using namespace std ;
int cmp(int year,int mouth,int day){
    if(year<2024 || year == 2024 && day < 6){
        return 0 ;
    }
    return 1 ;
}
int main( ){
    int A[13]={0,31,28,31,30,31,30,31,31,30,31,30,31} ;
    string s ;
    int mouth , day , year ;
    map<string,int>Mouthmap = {
            {"January",1},{"February",2},{"March",3},{"April",4},
            {" May",5},{"June",6},{"July",7},{"August",8},
            {"September",9},{ "October",10},{"November",11},{"December",12}
    };
    while(cin >> day >> s >> year){
        mouth =Mouthmap[s] ;
        int flag = 0 ;
        int pastyear=year,pastmouth=mouth,pastday=day;
        int futyear=2024,futmouth=1,futday=6;
        if( cmp(year,mouth,day) ){
            futday=pastday;
            futmouth=pastmouth;
            futyear=pastyear;
            pastmouth=1;
            pastyear=2024;
            pastday=6;
            flag = 1 ;
        }
        int gap = 0 ;
        while( pastyear!=futyear || pastmouth != futmouth || pastday != futday ){
            bool judge = pastyear % 400 == 0 || pastyear % 100 != 0 && pastyear % 4 == 0 ;
            if(judge){
                A[2]=29;
            }else{
                A[2]=28;
            }
            if( pastday <= A[pastmouth] ){
                pastday++;
                gap++;
            }else{
                pastmouth++;
                pastday = 1 ;
                if(pastmouth == 13){
                    pastyear++;
                    pastmouth=1;
                }
            }
        }
        gap %= 7;
        int x = 6 ;
        if(flag==0){
            x =(6 - gap + 7 ) % 7 ;
        }else{
            x =(6+ gap ) % 7 ;
        }
        flag = 0 ;
        string week[7]={"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        cout << week[x] << '\n';
    }
    return 0 ;
}

OJ时间过长未通过,不知道为啥。

Clion上结果如下: