Bomb
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 19226 Accepted Submission(s): 7116
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.
Author
fatboy_cw@WHU
Source
2010 ACM-ICPC Multi-University Training Contest(12)——Host by WHU
Recommend
zhouzeyong | We have carefully selected several similar problems for you: 3554 3556 3557 3558 3559
题目概述:不要49,即对于一个数n,相邻两个数位不能是4和9,如果存在相邻两个位上的数是4和9,则记为一个满足答案要求的数。
可以观察到,n<=2^63-1,暴力肯定是会超时的/一点都不留情面:-D/。
所以我们想到用数位DP来解决。
跟模板类似,我们用flag1来记录当前状态
flag1=0:取了i位且不包含49
flag1=1:取了i位不包含49且前一位取4
flag1=2:取了i位且包含49;
用flag2记录是否达到上限
转移见代码。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#define ll long long
using namespace std;
ll dp[100][3];
int digit[100];
ll dfs(int len,int flag1,int flag2){
if(!len) return flag1==2;
if(!flag2 && dp[len][flag1]!=-1) return dp[len][flag1];
int top=9;
ll sum=0;
if(flag2) top=digit[len];
for(int i=0;i<=top;i++){
int status=flag1;
if(!flag1 && i==4) status=1;
else if(flag1==1 && i!=4 && i!=9) status=0;
else if(flag1==1 && i==9) status=2;
sum+=dfs(len-1,status,flag2 && i==top);
}
if(!flag2) dp[len][flag1]=sum;
return sum;
}
ll solve(ll x){
int len=0;
while(x){
digit[++len]=x%10;
x/=10;
}
return dfs(len,0,1);
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
memset(dp,-1,sizeof(dp));
ll n;
scanf("%I64d",&n);
printf("%I64d\n",solve(n));
}
return 0;
}