Problem Description
The counter-terrorists found a time bomb in the dust. But this time the terrorists improve on the time bomb. The number sequence of the time bomb counts from 1 to N. If the current number sequence includes the sub-sequence “49”, the power of the blast would add one point.
Now the counter-terrorist knows the number N. They want to know the final points of the power. Can you help them?
Input
The first line of input consists of an integer T (1 <= T <= 10000), indicating the number of test cases. For each test case, there will be an integer N (1 <= N <= 2^63-1) as the description.
The input terminates by end of file marker.
Output
For each test case, output an integer indicating the final points of the power.
Sample Input
3
1
50
500
Sample Output
0
1
15
Hint
From 1 to 500, the numbers that include the sub-sequence “49” are “49”,”149”,”249”,”349”,”449”,”490”,”491”,”492”,”493”,”494”,”495”,”496”,”497”,”498”,”499”,
so the answer is 15.
思路:
数位DP,模板题。看了一天的数位dp,大概有点思路了,还有很多细节需要琢磨。推荐一个博客 数位DP入门
数位dp的主要思想就是,按位来枚举数字。比如 235,从高位到地位枚举的时候 可以分为如下步骤:枚举百分位的时候取值范围是0,1,2 ,档百分位是0的时候,十分位取值可以为 0~9 为1 的时候同理,但是当百分位为2的时候,这时候就有限制了此时十分位的枚举范围只能是0,1,2,3了, 如此把所有位数枚举完。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int digit[65];
long long dp[65][2];
long long dfs(int pos, bool have, bool limit)
{
if (pos < 1)
return 1;
if (!limit && dp[pos][have] != -1) return dp[pos][have];
int num = limit?digit[pos]:9;
long long tmp = 0;
for (int i = 0; i <= num; ++i) {
if (have && i == 9) continue;
tmp += dfs(pos-1,i==4, limit && (i == num));
}
if (!limit) dp[pos][have] = tmp;
return tmp;
}
long long solve(long long x)
{
int len = 0;
while(x) {
digit[++len] = x%10;
x /= 10;
}
memset(dp,-1,sizeof(dp));
return dfs(len,false,true);
}
int main()
{
int t;
cin >> t;
long long x;
while(t--) {
cin >> x;
cout << x - solve(x) + 1 << endl;
}
return 0;
}