How many 9s

How many 9s

看了很多题解,都是预处理的,尽管想想不预处理,其实算起来也挺快,但是数据很多,你必须保证O(1)就可以算出来,我的程序里每一次都是要循环比较多的,所以超时也就不难理解了。预处理出所有的日期,最后直接相减即可。这个模拟借鉴网上的代码,感觉写的挺漂亮。

代码
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
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
int mon[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int leap(int year)
{
if((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
return 1;
return 0;
}
int check(int num)
{
int sum = 0;
while(num)
{
sum += (num % 10 == 9) ? 1 : 0;
num /= 10;
}
return sum;
}
int num(int y,int m,int d)
{
int sum = 0;
sum += check(y) + check(m) + check(d);
return sum;
}
int sum[10005][15][32], pre[10005][15][32];
int calculate(int y1,int m1,int d1,int y2,int m2,int d2)
{
int tem = 0;
while(y1 != y2 || m1 != m2 || d1 != d2)
{
mon[2] = leap(y1) + 28;
pre[y1][m1][d1] = tem;
tem += num(y1,m1,d1);
sum[y1][m1][d1] = tem;
if( ++d1 > mon[m1])
{
d1 = 1;
if(++ m1 > 12)
{
m1 = 1;
y1++;
}
}

}
}
int main()
{
calculate(2000,1,1,10000,1,1);
int t,y1,m1,d1,y2,m2,d2;
scanf("%d",&t);
while(t--)
{
scanf("%d %d %d %d %d %d",&y1,&m1,&d1,&y2,&m2,&d2);
printf("%d\n",sum[y2][m2][d2] - pre[y1][m1][d1]);
}
}