Numbers game 1 non-decreasing numbers in the interval, digital DP winter vacation training

Digital games are very popular in the Science Association recently. Someone named a non-decreasing number. This number must satisfy the relationship that the digits from left to right are less than or equal to, such as 123,446. Now everyone decides to play a game, specify an integer closed interval [a, b], and ask how many non-decreasing numbers are in this interval.

Input format There
are multiple sets of test data. Each group contains only two numbers, a and b, with meaning as described in the title.

Output format
Each line gives an answer to the test data, that is, how many non-decreasing numbers are between [a, b].

Sample
Input Output
1 9
1 19
9
18
Data Range and Reminder
For all data, 1≤a≤b≤231−1.
Simple questions, just remember to sort the digits

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <map>
#include <stack>
#include <set>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <cstdio>
#define ls (p<<1)
#define rs (p<<1|1)
#define ll long long
using namespace std;
const int maxn = 2e6+5;
const int INF = 0x3f3f3f3f;
ll dp[50][15];//dp[pos][pre]记录了遍历第pos为位时,前一位为pre时的状态数
ll a[30],b[30];
// void init(){
    
    
//     dp[0][0]=1;
//     dp[0][1]=dp[0][2]=0;
//     for(int i=1;i<25;i++){
    
    
//         dp[i][0]=10*dp[i-1][0]-dp[i-1][1];//长度为i不含有49的个数
//         dp[i][1]=dp[i-1][0];//最高位为9但不含49的个数
//         dp[i][2]=10*dp[i-1][2]+dp[i-1][1];//含有49的个数
//     }
// }
ll dfs(ll pos,ll pre,bool limit){
    
    //pos表示当前遍历的是第几位,pre表示前一位是几,limit为限制标志 
    if(pos==-1) return 1;//找到一个没有49的数
    if(!limit&&dp[pos][pre]!=-1)
        return dp[pos][pre];
    ll up;
    if(limit)
        up=a[pos];//确定当前数的最大值
    else up=9;//无限制
    ll ans=0;
    for(int i=0;i<=up;i++){
    
    
        if(pre>i)
            continue;
        else
            ans+=dfs(pos-1,i,limit&&i==a[pos]);//向下搜素并且
    }
    if(!limit)  
        dp[pos][pre]=ans;//无限制更新
    return ans;
}

ll init(ll n)
{
    
    
    ll len = 0;
    while(n) {
    
    
        a[len++] = n % 10;
        n /= 10;
    }
    return dfs(len - 1, 0, 1);
}

void solve(){
    
    
    ll x,y;
    memset(dp,-1,sizeof(dp));
    while(scanf("%lld %lld",&x,&y)!=EOF){
    
    
        if(x==0&&y==0) break;
        cout<<init(y)-init(x-1)<<endl;
    }
}
int main()
{
    
    
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    solve();
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45891413/article/details/112909688