给定两个日期,计算这两个日期之间有多少个2月29日(包括起始日期)。
只有闰年有2月29日,满足以下一个条件的年份为闰年:
1. 年份能被4整除但不能被100整除
2. 年份能被400整除
第一行为一个整数T,表示数据组数。
之后每组数据包含两行。每一行格式为"month day, year",表示一个日期。month为{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November" , "December"}中的一个字符串。day与year为两个数字。
数据保证给定的日期合法且第一个日期早于或等于第二个日期。
对于每组数据输出一行,形如"Case #X: Y"。X为数据组数,从1开始,Y为答案。
1 ≤ T ≤ 550
小数据:
2000 ≤ year ≤ 3000
大数据:
2000 ≤ year ≤ 2×109
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
Case #1: 1 Case #2: 0 Case #3: 1 Case #4: 3
2.解题思路:本题要求输入两个日期,输出中间有多少个2月29日,实际上就是问中间有多少个闰年。根据闰年的定义,假设y2-y1=dy,那么不难由容斥原理得到区间(y1,y2]中闰年的个数是dy/4-dy/100+dy/400。接下来就是处理两个边界,如果第一个日期也包含了2.29日,就把结果+1,如果最后一个日期不包含2.29日,就把结果-1即可。
3.代码:
#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;
set<int>years;
const int MOD = 100007;
const int N = 2000000000;
const char*s[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
int id(char*str)
{
	int p = 0;
	for (p; strcmp(s[p], str) != 0; p++);
	return p + 1;
}
int solve(int m1,int d1,int y1,int m2,int d2,int y2)
{
	int num = (y2 / 4 - y1 / 4) - (y2 / 100 - y1 / 100) + (y2 / 400 - y1 / 400);//容斥原理计算(y1,y2]之间的闰年个数
	if (y1 % 400 == 0 || (y1 % 4 == 0 && y1 % 100 != 0))
	{
		if (m1 <= 2)num++;
	}
	if (y2 % 400 == 0 || (y2 % 4 == 0 && y2 % 100 != 0))
	{
		if (m2 < 2 || (m2 == 2 && d2 < 29))num--;
	}
	return num;
}
int main()
{
	//freopen("t.txt", "r", stdin);
	int T;
	cin >> T;
	int rnd = 0;
	while (T--)
	{
		char mon[15];
		int d1, y1,d2,y2;
		scanf("%s%d, %d", mon, &d1, &y1);
		int m1 = id(mon);
		scanf("%s%d, %d", mon, &d2, &y2);
		int m2 = id(mon);
		cout << "Case #" << ++rnd << ": ";
		cout << solve(m1, d1, y1, m2, d2, y2) << endl;
	}
	return 0;
}原文地址:http://blog.csdn.net/u014800748/article/details/45148391