Problem Description
Problem Analysis
My first impressions upon seeing this problem:
【Algorithm】Algorithm Is a Way of Thinking
At the time, I didn’t use a loop on this problem because I was afraid of TLE.
(Thinking about it, it only needs to loop 18 times—how could that TLE…)
So I wrote code like this:
(multiple WAs)
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
| #include<stdio.h>
int run(int m) {
if(m%100==0) {
if(m%400==0)
return 1;
else return 0;
} else if(m%100!=0&&m%4==0)
return 1;
else
return 0;
}
int main() {
int T,y,m,d;
int t;
scanf("%d",&T);
while(T--) {
scanf("%d-%d-%d",&y,&m,&d);
if(m==2&&d==29) {
printf("-1\n");
} else if(run(y))
if(m<=2)
printf("6575\n");
else
printf("6574\n");
else if(run(y+1))
printf("6575\n");
else if(run(y+2))
if(m<=2)
printf("6574\n");
else
printf("6575\n");
else if(run(y+3))
printf("6574\n");
}
return 0;
}
|
This approach assumes that leap years occur once every four years.
Then you only need to check whether the current year, the next year, the year after that, and the year three years later are leap years, and you can reason case by case and directly output the result.
After all, the answer is only 6574 or 6575.
However, leap years are not strictly once every four years.
Years divisible by 100 are not leap years; years divisible by 400 are.
So the assumption behind the approach was wrong, which made the code incorrect.
So I decided to honestly solve it with a loop:
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
| #include<stdio.h>
int run(int m) {
if((m%400==0)||(m%100!=0&&m%4==0))
return 1;
else
return 0;
}
int main() {
int T,y,m,d;
scanf("%d",&T);
while(T--) {
scanf("%d-%d-%d",&y,&m,&d);
int sum=0;
if(m==2&&d==29) {
printf("-1\n");
} else {
if(m<=2) {
for(int i=0; i<18; i++) {
if(run(y++))
sum+=366;
else
sum+=365;
}
} else {
for(int i=0; i<18; i++) {
if(run(++y))
sum+=366;
else
sum+=365;
}
}
printf("%d\n",sum);
}
}
return 0;
}
//用循环很轻松就AC了
//当时为什么脑抽坚持直接判定呢……
//有时候太强不是好事啊
//对代码简洁的强迫症有时候真难办
//一会再看看我那个代码究竟是错在哪里了
//(现在知道还是闰年的关系)
|
At the same time, I also tweaked the if statement for determining leap years
to make it look a little nicer.
Problem link: 【HDU】[1201]18th Birthday