题目描述:
有两个日期,求两个日期之间的天数,如果 两个日期是连续的我们规定他们之间的天数为两天。
输入:
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD。
输出:
每组数据输出一行,即日期差值。
样例输入:
20110412
20110422
样例输出:
11
问题分析:
1.基本思想:把原区间问题统一到起点确定的区间问题上去,我们把问题统一为与0000年1月1日的天数差。当求两个特定日期的天数差时,我们只要把他们和0000年1月1日的日期差相减。
2.要特别注意闰年
#include<cstdio>
#define RUN(x) x%100!=0&&x%4==0||x%400==0?1:0 //判断是否是闰年,
// 闰年结果为1,不是闰年结果是0
int dayofmonth[13][2]={ //每个月的天数,用上面RUN(x)来控制2月的天数
0,0,
31,31,
28,29,
31,31,
30,30,
31,31,
30,30,
31,31,
31,31,
30,30,
31,31,
30,30,
31,31};
struct Date //日期,包括年,月,日和计算下一天
{
int day;
int month;
int year;
void nextday()
{
day++;
if(day>dayofmonth[month][RUN(year)])
{
day=1;
month++;
if(month>12)
{
month=1;
year++;
}
}
}
};
int buf[5001][13][32]; //buf矩阵保存0年1月1日一直到5000年12月31日每一天与0年1月1日的差
int Abs(int x) //求差的绝对值
{
return x<0?-x:x;
}
int main()
{
Date tmp;
int cnt=0;
tmp.year=0;tmp.month=1;tmp.day=1;
while(tmp.year<=5000)
{
buf[tmp.year][tmp.month][tmp.day]=cnt;//计算0年1月1日一直到5000年12月31日每一天与0年1月1日的差
tmp.nextday();
cnt++;
}
int y1,m1,d1,y2,m2,d2;
while(scanf("%4d%2d%2d",&y1,&m1,&d1)!=EOF)
{
scanf("%4d%2d%2d",&y2,&m2,&d2);
printf("%d\n",Abs(buf[y2][m2][d2]-buf[y1][m1][d1])+1);//利用矩阵buf取出和0年1月1日的差,做差取绝对值
} //根据题目连续两天差为2,需要给绝对值+1
return 0;
}