If we represent a date in the format YYYY-MM-DD (for example, 2017-04-09), do you know how many 9s will appear in all the dates between Y1-M1-D1 and Y2-M2-D2 (both inclusive)?
Note that you should take leap years into consideration. A leap year is a year which can be divided by 400 or can be divided by 4 but can't be divided by 100.
The first line of the input is an integer T (1 ≤ T ≤ 105), indicating the number of test cases. Then T test cases follow. For each test case:
The first and only line contains six integers Y1, M1, D1, Y2, M2, D2, their meanings are described above.
It's guaranteed that Y1-M1-D1 is not larger than Y2-M2-D2. Both Y1-M1-D1 and Y2-M2-D2are between 2000-01-01 and 9999-12-31, and both dates are valid.
We kindly remind you that this problem contains large I/O file, so it's recommended to use a faster I/O method. For example, you can use scanf/printf instead of cin/cout in C++.
<h4< dd="">For each test case, you should output one line containing one integer, indicating the answer of this test case.
<h4< dd="">4 2017 04 09 2017 05 09 2100 02 01 2100 03 01 9996 02 01 9996 03 01 2000 01 01 9999 12 31<h4< dd="">
4 2 93 1763534<h4< dd="">
For the first test case, four 9s appear in all the dates between 2017-04-09 and 2017-05-09. They are: 2017-04-09 (one 9), 2017-04-19 (one 9), 2017-04-29 (one 9), and 2017-05-09 (one 9).
For the second test case, as year 2100 is not a leap year, only two 9s appear in all the dates between 2100-02-01 and 2100-03-01. They are: 2017-02-09 (one 9) and 2017-02-19 (one 9).
For the third test case, at least three 9s appear in each date between 9996-02-01 and 9996-03-01. Also, there are three additional nines, namely 9996-02-09 (one 9), 9996-02-19 (one 9) and 9996-02-29 (one 9). So the answer is 3 × 30 + 3 = 93.
思路 : 模拟日期运行 大约8000 年 8000 * 400 大约 5000000 的数据量,由于查询较多所以先做前缀和数组。结合日期的特点,设置三维数组。
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;
int check(int m)
{
int cnt = 0;
while(m)
{
if(m%10 == 9) cnt ++;
m /= 10;
}
return cnt;
}
bool leap(int n)
{
return (n % 400 == 0|| (n %4 == 0 && n%100 != 0));
}
int ans [10000][13][32];
int month[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int a[6];// 存储数据
int main()
{
int t;
ll i = 0;
ll cnt = 0;
cnt = 0;
a[0] = 2000,a[1] =1,a[2] = 1;
while(!(a[0] == 10000 && a[1] == 1 && a[2] == 1))
{
month[2] = 28 + leap(a[0]);
cnt += check(a[0]) + check(a[1]) + check(a[2]);
ans[a[0]][a[1]][a[2]] = cnt;
a[2] ++;
if(a[2] > month[a[1]])
{
a[2] = 1;
a[1] ++;
if(a[1] > 12)
{
a[1] = 1;
a[0] ++;
}
}
}
scanf("%d",&t);
while(t--)
{
for(int i = 0; i < 6; i++)
scanf("%lld",&a[i]);
cnt = ans[a[3]][a[4]][a[5]] - ans[a[0]][a[1]][a[2]];
cnt += check(a[0]) + check(a[1]) + check(a[2]);
printf("%lld\n",cnt);
}
return 0;
}