Time Limit: 1 second(s) | Memory Limit: 32 MB |
It is 2012, and it's a leap year. So there is a "February 29" in this year, which is called leap day. Interesting thing is the infant who will born in this February 29, will get his/her birthday again in 2016, which is another leap year. So February 29 only exists in leap years. Does leap year comes in every 4 years? Years that are divisible by 4 are leap years, but years that are divisible by 100 are not leap years, unless they are divisible by 400 in which case they are leap years.
In this problem, you will be given two different date. You have to find the number of leap days in between them.
Input
Input starts with an integer T (≤ 550), denoting the number of test cases.
Each of the test cases will have two lines. First line represents the first date and second line represents the second date. Note that, the second date will not represent a date which arrives earlier than the first date. The dates will be in this format - "month day, year", See sample input for exact format. You are guaranteed that dates will be valid and the year will be in between 2 * 103 to 2 * 109. For your convenience, the month list and the number of days per months are given below. You can assume that all the given dates will be a valid date.
Output
For each case, print the case number and the number of leap days in between two given dates (inclusive).
Note
The names of the months are {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November" and "December"}. And the numbers of days for the months are {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 and 31} respectively in a non-leap year. In a leap year, number of days for February is 29 days; others are same as shown in previous line.
大意:找出给的两个日期之间有几个 2 月 29 日。
思路:容斥原理,中间的年数 4 的倍数减去 100 的倍数加上 400 的倍数,然后特判开始和结束的年和月,再对结果进行调整。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct date{
char s[15];
int x;
int y;
}a,b;
int run(int m)
{
if(m%4==0&&m%100!=0||m%400==0)
return 1;
else
return 0;
}
int main()
{
int t;
scanf("%d",&t);
int k=1,num;
while(t--)
{
scanf("%s%d,%d",&a.s,&a.x,&a.y);
scanf("%s%d,%d",&b.s,&b.x,&b.y);
num=b.y/4-b.y/100+b.y/400-(a.y/4-a.y/100+a.y/400);
char J[15]="January",F[15]="February";
if(run(a.y)&&((strcmp(a.s,J)==0)||(strcmp(a.s,F)==0&&a.x<=29)))
num++;
if(run(b.y)&&(strcmp(b.s,J)==0||(strcmp(b.s,F)==0)&&b.x<29))
num--;
printf("Case %d: %d\n",k++,num);
}
return 0;
}