数位dp入门(含有49)

题意:1-n之间共有多少个含有49的数

/*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? 
*/
#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<queue>
#include<map>
#include<set>
using namespace std;
#define B(x) (1<<(x))
typedef long long ll;
void cmax(int& a,int b){ if(b>a)a=b; }
void cmin(int& a,int b){ if(b<a)a=b; }
const int oo=0x3f3f3f3f;
const int MOD=1000000007;
const int maxn=5100;
const int maxm=21000;
ll dp[66][66][66];
int bit[66];

ll dfs(int pos,int p1,int is,int f){
    //参数表明状态转移;
    if(pos<1) return is;//数位dp模板
    if(!f&&dp[pos][p1][is]!=-1) return dp[pos][p1][is];
    int last= f ? bit[pos] : 9;
    ll res=0;//从0到last遍历;
    for(int i=0;i<=last;i++){
        res+=dfs(pos-1,i,is||(p1==4&&i==9),f&&i==last);
    }//状态转移res+=dfs(pos-1,i,is||(p1==4&&i==9),f&i==last);
    if(!f) dp[pos][p1][is]=res;
    return res;//处理
}

ll Cnt(ll x){
    int len=0;
    while(x){
        bit[++len]=x%10;//分解数的每个位数;
        x/=10;
    }//先分解每个位置;
    return dfs(len,0,0,1);//处理1-x有多少个含有666的数//深搜处理数x;
//赋予其初始状态;
}
/*ll solve(int n){
    if(n>72915400)return (ll)10000000000;
    ll l=0,r=(ll)10000000000,mid,ans,t;
    while(l<r){
        mid=(l+r)>>1;//取之间的数;
        t=Cnt(mid);//含有多少个
        if(t<n)
            l=mid+1;//如果1-mid间含有的666数t小于n,证明mid太小
        else
            r=mid-1,ans=mid;//ans记录mid数;
//二分记录mid值;
    }
    t=Cnt(ans);//再次看t的值
    if(t>=n){
        while(Cnt(ans)>=n)ans--;
        ans++;//ans++;
    }else{
        while(Cnt(ans)<=n)ans++;
        ans--;//ans--;
    }
    return ans;//最终就是所求数;
}
 */
int main(){
    //freopen("G:\\read.txt","r",stdin);
    //freopen("G:\\a.txt","w",stdout);
    ll n,T;
    scanf("%lld",&T);
    memset(dp,-1,sizeof dp);
    while(T--){
            
        scanf("%lld",&n);
        printf("%lld\n",Cnt(n));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/82527713