Description
Given two dates, please calculate the number of February 29 between the two dates inclusively.
Only a leap year contains February 29. The year satisfying one of the following conditions is a leap year.
The year number can be divided by 4 but cannot be divided by 100.
The year number can be divided by 400.
Input
The first line contains an integer T, indicating the number of test cases.
Each test case contains two lines which are both in the format “Month Day, Year”, indicating the dates. Month is a string contained in {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November” , “December”}. Day and Year are two integers.
We guarantee that all the dates are valid. The first date comes before the second date or the two dates are the same.
Output
For each test case, output a line containing “Case #X: Y”. X is the test case number starting from 1, and Y is the answer.
Sample Input
4
January 12, 2012
March 19, 2012
August 12, 2899
August 12, 2901
August 12, 2000
August 12, 2005
February 29, 2004
February 29, 2012
Sample Output
Case #1: 1
Case #2: 0
Case #3: 1
Case #4: 3
可以用容斥做,我第一想到的是用周期做。每400年中有97个闰年。对于两个边界的日期特判.
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
string s[20]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November" , "December"};
bool leap(int y){
if(y%400 == 0 || (y%4==0&&y%100!=0)) return true;
else return false;
}
int main(){
int t;cin>>t;
string s1,s2;
int c1,c2,d1,d2,k1,k2;
for( int j = 1; j <= t; j++){
cin>>s1>>c1;
getchar();
cin>>d1;
cin>>s2>>c2;
getchar();
cin>>d2;
for( int i = 0; i<12; i++){
if(s[i]==s1) k1=i+1;
if(s[i]==s2) k2=i+1;
}
int sum = 0;
if(d1==d2){
if(leap(d1))
if(k1<=2&&k2>2) sum++;
else if(k1<=2&&k2==2&&c2==29) sum++;
cout<<"Case #"<<j<<": "<<sum<<endl;
continue;
}
if(d1+1==d2){
if(leap(d1)){
if(k1<=2) sum++;
}
else if(leap(d2)){
if(k2>2||(k2==2&&c2==29)) sum++;
}
cout<<"Case #"<<j<<": "<<sum<<endl;
continue;
}
int d = d2-d1-1;
sum += d/400*97;
int l = d%400;
for(int i = d1+1 ;i<(d1+l+1); i++){
if(leap(i)) {
sum++;
}
}
if(leap(d2)) if(k2>2||(k2==2&&c2==29)) sum++;
if(leap(d1)) if(k1<=2) sum++;
cout<<"Case #"<<j<<": "<<sum<<endl;
}
return 0;
}