GYM 101653 R.Ramp Number(数位DP)

本文介绍了一种算法,用于判断一个数字是否为斜坡数字,并计算所有不超过该数字的斜坡数字的数量。通过递归搜索策略实现,适用于长度不超过80的整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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

Input

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

Output

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

Sample Input

5
11
123
101
1111
99999

Sample Output

10
65
-1
220
2001

Solution

首先判断n是否为斜坡数字,之后数位DPDP求不超过nn的斜坡数字个数,以dp[pos][pre]表示从高位开始确定到第pospos位且前一位数字为prepre时的斜坡数字个数,那么第pospos位所取数字必然不小于prepre,以此转移即可

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值