hud 3555 Bomb 数位dp

Bomb

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others) Total Submission(s): 19122    Accepted Submission(s): 7068

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
 
数位dp的比较好的题目把。。
 

 

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<cmath>
#define ls (u<<1)
#define rs (u<<1|1)
#define maxn 30
#define ll long long
#define INF 1e18+7
using namespace std;
#define max(a,b) (a)>(b)?(a):(b)
#define min(a,b) (a)<(b)?(a):(b)
int digit[maxn];
ll dp[maxn][3];
ll dfs(int pos,int flag,int limit){
    if(pos == -1){
        return flag == 2;//flag等于2的时候代表这个数满足条件
    }
    if(!limit && dp[pos][flag]!=-1){//达到极限且此时dp有值
        return dp[pos][flag];
    }
    ll sum = 0;
    int e = limit?digit[pos]:9;
    for(int i=0;i<=e;i++){
        int have = flag;
        if(flag == 1 && i == 9){
            have = 2;
        }
        if(flag == 0 && i == 4){
            have = 1;//此时为将要完成的状态
        }
        if(flag == 1 && i!=4 && i!=9){
            have = 0;
        }
        sum += dfs(pos-1,have,limit&&i==e);
    }
    if(!limit){//达到极限的情况
        dp[pos][flag] = sum;
    }
    return sum;
}
ll solve(ll n){
    int pos = 0;
    while(n){
        digit[pos++] = n%10;
        n /= 10;
    }
    return dfs(pos-1,0,1);
}
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        ll n;
        scanf("%lld",&n);
        memset(dp,-1,sizeof(dp));
        printf("%lld\n",solve(n));
    }
    return 0;
}

 

posted on 2017-08-05 20:35  九月旧约  阅读(158)  评论(0编辑  收藏  举报

导航