[algorithm]2月29日
给定两个日期,计算这两个日期之间有多少个2月29日(包括起始日期)。
只有闰年有2月29日,满足以下一个条件的年份为闰年:
年份能被4整除但不能被100整除
年份能被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
1,模拟
这种方法只能过小数据,因为闰年是逐个判断的。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string.h>
using namespace std;
bool isLeap(int y)
{
if(y%4 == 0 && y%100 != 0)
return true;
else if (y%400 == 0)
return true;
else
return false;
}
int monthChange(const char *a)
{
if(strcmp(a,"January") == 0)return 1;
else if(strcmp(a,"February") == 0)return 2;
else if(strcmp(a,"March") == 0)return 3;
else if(strcmp(a,"April") == 0)return 4;
else if(strcmp(a,"May") == 0)return 5;
else if(strcmp(a,"June") == 0)return 6;
else if(strcmp(a,"July") == 0)return 7;
else if(strcmp(a,"August") == 0)return 8;
else if(strcmp(a,"September") == 0)return 9;
else if(strcmp(a,"October") == 0)return 10;
else if(strcmp(a,"November") == 0)return 11;
else if(strcmp(a,"December") == 0)return 12;
else return -1;
}
int main()
{
int N;
scanf("%d",&N);
for(int i=1; i<=N; i++)
{
char mon1[10];
char mon2[10];
int d1,d2,y1,y2;
int count = 0;
memset(mon1,0,10*sizeof(char));
memset(mon2,0,10*sizeof(char));
scanf("%s %d,%d",mon1,&d1,&y1);
scanf("%s %d,%d",mon2,&d2,&y2);
int m1 = monthChange(mon1);
int m2 = monthChange(mon2);
if (m1 > 2)
y1++;
if (m2 == 1 || (m2 == 2 && d2 < 29))
y2--;
for(int j = y1; j <= y2; j++)
{
if(isLeap(j))
count++;
}
printf("Case #%d: %d\n",i,count);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
2,较高效方法
可通过大数据,直接计算区间有多少个闰年。首先计算被4整除的年份个数,从中去掉被100整除的年份,再加入被400整除的年份。
#include <cstdio>
#include <cstring>
int main()
{
int N;
scanf("%d",&N);
for(int i=1; i<=N; i++)
{
char mon1[10],mon2[10];
int day1,day2,year1,year2;
scanf("%s %d,%d",mon1,&day1,&year1);
scanf("%s %d,%d",mon2,&day2,&year2);
int count = 0;
if (strcmp(mon1,"January") == 0 || strcmp(mon1,"February") == 0 && day1 <= 29)
year1 --;
if (strcmp(mon2,"January") == 0 || strcmp(mon2,"February") == 0 && day2 < 29)
year2 --;
count = (year2 / 4) - (year1 / 4);
count = count - ((year2 / 100) - (year1 / 100));
count += (year2 / 400) - (year1 / 400);
printf("Case #%d: %d\n",i,count);
}
return 0;
}