题目1043:Day of Week
上题为区间问题,可以通过预处理解决。
问题在于负数取余(取模MOD),不能简单地将数字变为正数然后再取余,这是错误的。
#include <iostream>
#include <map>
using namespace std;
#define ISLEAP(x) x % 4==0 && x%100!=0||x%400==0? 1:0
int dayOfMonth[32][2]={
0,0,
31,31,
28,29,
31,31,
30,30,
31,31,
30,30,
31,31,
31,31,
30,30,
31,31,
30,30,
31,31};
string week[7]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
struct Date{
int year;
int month;
int day;
void nextDay(){
day++;
if(day>dayOfMonth[month][ISLEAP(year)]){
day=1;
month++;
if(month>12){
month=1;
year++;
}
}
}
};
map<string,int> monthToInt;
int abs(int x)
{
return x>0?x:-x;
}
int offset[5001][13][32];
int main(void)
{
monthToInt.insert(pair<string,int>("January",1));
monthToInt.insert(pair<string,int>("February",2));
monthToInt.insert(pair<string,int>("March",3));
monthToInt.insert(pair<string,int>("April",4));
monthToInt.insert(pair<string,int>("May",5));
monthToInt.insert(pair<string,int>("June",6));
monthToInt.insert(pair<string,int>("July",7));
monthToInt.insert(pair<string,int>("August",8));
monthToInt.insert(pair<string,int>("September",9));
monthToInt.insert(pair<string,int>("October",10));
monthToInt.insert(pair<string,int>("November",11));
monthToInt.insert(pair<string,int>("December",12));
Date tmp;
int d1,y1;
string m1;
tmp.year=0;
tmp.month=1;
tmp.day=1;
int cnt=0;
while(tmp.year<5001){
offset[tmp.year][tmp.month][tmp.day]=cnt++;
tmp.nextDay();
}
while(cin>>d1>>m1>>y1){
int days=offset[y1][monthToInt[m1]][d1]-offset[2014][10][13]+1;
cout<<week[(days%7+7)%7]<<endl; //关键是这里,取余时处理负数的方法
}
return 0;
}