hdu3555Bomb(记忆优化,数位dp)

来源:互联网 发布:武汉鲨鱼网络直播 编辑:程序博客网 时间:2024/05/20 11:23

题意:

找出n范围内含有49的数的个数。

题解:

之前做过这题这次用记忆优化在做一边试了下,发现记忆优化好处很多,尤其是数位dp很容易实现。

#include<stdio.h>#include<string.h>#include<algorithm>#include<iostream>#include<math.h>using namespace std;typedef long long lld;#define oo 0x3f3f3f3f#define mod 1000000007#define maxn 30+5lld dp[maxn][10][2];int bit[maxn];lld dfs(int pos,int pre,int is,int f){    if(pos<1) return is;    if(!f&&dp[pos][pre][is]!=-1) return dp[pos][pre][is];    int last = f ? bit[pos] : 9;    lld res=0;    for(int i=0;i<=last;i++)    {        res+=dfs(pos-1,i,is||(pre==4&&i==9),f&&i==last);    }    if(!f) dp[pos][pre][is]=res;    return res;}lld GetAns(lld n){    int len=0;    while(n)    {        bit[++len]=n%10;        n/=10;    }    return dfs(len,0,0,1);}int main(){    lld n;    int T;    memset(dp,-1,sizeof dp);    scanf("%d",&T);    while(T--)    {        cin>>n;        cout<<GetAns(n)<<endl;    }return 0;}


0 0