GYM 101653 R.Ramp Number(数位DP)

Description

一个数字称为斜坡数字当且仅当该数字从高位到低位的数字不减,给出一整数 n ,判断 n 是否为一个斜坡数字,如果是则求所有不超过 n 的斜坡数字数量,如果不是则输出 1

Input

第一行一整数 T 表示用例组数,每组用例输入一个长度不超过 80 的整数 n

Output

如果 n 不是一个斜坡数字则输出 1 ,否则输出所有不超过 n 的斜坡数字个数

Sample Input

5
11
123
101
1111
99999

Sample Output

10
65
-1
220
2001

Solution

首先判断 n 是否为斜坡数字,之后数位 D P 求不超过 n 的斜坡数字个数,以 d p [ p o s ] [ p r e ] 表示从高位开始确定到第 p o s 位且前一位数字为 p r e 时的斜坡数字个数,那么第 p o s 位所取数字必然不小于 p r e ,以此转移即可

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f;
ll dp[100][10];
int n,T;
char s[100];
ll dfs(int pos,int pre,int fp)
{
    if(pos==n)return 1;
    if(!fp&&~dp[pos][pre])return dp[pos][pre];
    ll ans=0;
    int fpmax=fp?s[pos]-'0':9;
    for(int i=pre;i<=fpmax;i++)ans+=dfs(pos+1,i,fp&&i==fpmax);
    if(!fp)dp[pos][pre]=ans;
    return ans;
}
int main()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s",s);
        n=strlen(s);
        int flag=1;
        for(int i=1;i<n;i++)
            if(s[i]<s[i-1])
            {
                flag=0;
                break;
            }
        if(!flag)printf("-1\n");
        else 
        {
            memset(dp,-1,sizeof(dp));
            printf("%lld\n",dfs(0,0,1)-1);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/v5zsq/article/details/80407257