算法提高 日期計算
時間限制:1.0s 內存限制:256.0MB問題描述已知2011年11月11日是星期五,問YYYY年MM月DD日是星期幾?注意考慮閏年的情況。尤其是逢百年不閏,逢400年閏的情況。
輸入格式輸入只有一行YYYY MM DD
輸出格式輸出只有一行W
數據規模和約定1599 <= YYYY <= 29991 <= MM <= 121 <= DD <= 31,且確保測試樣例中YYYY年MM月DD日是一個合理日期1 <= W <= 7,分別代表周一到周日
樣例輸入
2011 11 11
樣例輸出
5
c++:
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 using namespace std; 5 6 int a[2][13]={{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}}; 7 8 bool isRun(int year){//判斷是否為閏年 9 if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0) 10 return true; 11 return false; 12 } 13 14 int calDay(int year){ 15 int index = 0; 16 if(!isRun(year)) index = 1; 17 int tot = 0; 18 for(int i=1; i<=12; ++i) 19 tot += a[index][i]; 20 return tot; 21 } 22 23 int Day(int y, int m, int d){//計算從0年0月0日到y年m月d日的時間天數 24 int ans = 0; 25 for(int i=1; i<y; ++i) 26 ans+=calDay(i); 27 int index = 0; 28 if(!isRun(y)) index = 1; 29 for(int i=1; i<m; ++i) 30 ans += a[index][i]; 31 ans += d; 32 return ans; 33 } 34 35 int main(){ 36 int y, m, d; 37 cin>>y>>m>>d; 38 int diff = Day(y, m, d) - Day(2011, 11, 11);//已知2011-11-11這一天是星期5 39 if(diff > 0) cout<<(4+diff%7)%7+1<<endl; 40 else{ 41 for(int i=1; i<=7; ++i) 42 if((i-1 + -diff%7)%7 + 1 == 5){ 43 cout<<i<<endl; 44 break; 45 } 46 } 47 return 0; 48 }
?