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.
题意:给你一个数n,让你在0~n的区间里查找有多少个带有连续49的数字。
思路:这道题的话,是个很明显的数位DP,因为题里是让你查找49,所以我们可以在dfs里这样写,dfs(pos,if4,limit)分别代表了第几位,是不是4,还有上界判断条件。然后因为找49,所以当if(if4 && i==9)的时候 ,我们剪掉49这一枝。剩下的套一下模板就好了。
AC代码:
#include <bits/stdc++.h>
typedef long long ll;
const int maxx=10010;
const int inf=0x3f3f3f3f;
using namespace std;
ll a[20];
ll dp[20][maxx];
ll dfs(int pos,bool if4,bool limit)
{
if(pos==-1)
return 1;
if(!if4 && !limit && dp[pos][if4]!=-1)
return dp[pos][if4];
ll ans=0;
int up=limit?a[pos]:9;
for(int i=0;i<=up;i++)
{
if(if4 && i==9)
continue;
ans+=dfs(pos-1,i==4,limit && i==a[pos]);
}
if(!if4 && !limit)
dp[pos][if4]=ans;
return ans;
}
ll solve(ll x)
{
int pos=0;
while(x)
{
a[pos++]=x%10;
x/=10;
}
return dfs(pos-1,false,true);
}
int main()
{
int t;
scanf("%d",&t);
ll n;
memset(dp,-1,sizeof(dp));
while(t--)
{
scanf("%lld",&n);
printf("%lld\n",n+1-solve(n));
}
return 0;
}