最近把算法竞赛入门经典的前半部分看完了,开始看算法笔记入门算法。
看了前半部分的例题,很多是算法竞赛入门经典中出现过的,但是感觉这本书写的更适合初学者,而且真的很像考试笔记,通俗易懂。
//日期问题
#include <iostream>
using namespace std;
const int month[13][2] = //第二维:0:非闰年,1:闰年
{
{0, 0}, //方便取
{31,31}, //1
{28,29}, //2
{31,31}, //3
{30,30}, //4
{31,31}, //5
{30,30}, //6
{31,31}, //7
{31,31}, //8
{30,30}, //9
{31,31}, //10
{30,30}, //11
{31,31} //12
};
bool is_leap(int a)
{
if ( ((a % 100 != 0)&&(a % 4 == 0)) || (a % 400 == 0) )
{
return 1;
}
else return 0;
}
int main()
{
int time1, year1, month1, day1;
int time2, year2, month2, day2;
scanf("%d%d", &time1, &time2);
if(time1 > time2) swap(time1, time2); //保证第一个日期小于第二个日期
//printf("time1 %d
time2 %d
", time1, time2);
day1 = time1 % 100;
time1 /= 100;
month1 = time1 % 100;
time1 /= 100;
year1 = time1;
//printf("%02d
%02d
%04d
", day1, month1, year1);
day2 = time2 % 100;
time2 /= 100;
month2 = time2 % 100;
time2 /= 100;
year2 = time2;
int cnt = 1; //计数器,用于计算两个日期之间的差日
不设置为0设置为1是因为如果两个日期是连续的,规定它们之间的天数为两天。
//对1的数据进行每日加加,直至等于2的数据。
while ( year1<year2 || month1<month2 || day1<day2 )
{
day1++;
// cnt++;
if(day1 > month[month1][is_leap(year1)])
{
month1++;
day1 = 1;
}
if(month1 > 12)
{
year1++;
month1 = 1;
}
cnt++;
}
cout << cnt << endl;
//cout << is_leap(2020) <<endl;
system("pause");
}