hdu3555——Bomb(数位dp)

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

求1~n中出现49的数的个数
根据题意,只要数字中出现了49,后面的数字可以是0~9的任何一个,所以关键是判断是否能出现49
设3个状态s,s==0时dp[i][0]表示长度为i但不含49的方案数,dp[i][1]表示长度为i但末尾为4的方案数,dp[i][2]表示出现49的方案数。
当s==0且当前选择的数字为4是,说明可能会进入49的状态,所以s改为1
当s==1且当前正好选择了9,说明出现了49,状态不会再改变
当s==1且当前既不为4也不为9,说明这个4肯定不会组成49,状态设为0

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
using namespace std;
long long n,dp[25][25];
int dight[25];
long long dfs(int pos,int status,bool limit)
{
    if(pos==-1)
        return status==2;
    if(!limit&&dp[pos][status]!=-1)
        return dp[pos][status];
    long long ans=0;
    int s,end=limit?dight[pos]:9;
    for(int i=0;i<=end;++i)
    {
        s=status;
        if(status==1&&i==9)
            s=2;
        if(status==0&&i==4)
            s=1;
        if(status==1&&i!=4&&i!=9)
            s=0;
        ans+=dfs(pos-1,s,limit&&i==end);
    }
    if(!limit)
        dp[pos][status]=ans;
    return ans;
}
long long cal(long long n)
{
    int cnt=-1;
    while(n)
    {
        dight[++cnt]=n%10;
        n/=10;
    }
    return dfs(cnt,0,1);
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(dp,-1,sizeof(dp));
        scanf("%I64d",&n);
        printf("%I64d\n",cal(n));
    }
    return 0;
}

你可能感兴趣的:(c,dp,ACM)