1082. 数字游戏

题目链接

1082. 数字游戏

科协里最近很流行数字游戏。

某人命名了一种不降数,这种数字必须满足从左到右各位数字呈非下降关系,如 \(123\)\(446\)

现在大家决定玩一个游戏,指定一个整数闭区间 \([a,b]\),问这个区间内有多少个不降数。

输入格式

输入包含多组测试数据。

每组数据占一行,包含两个整数 \(a\)\(b\)

输出格式

每行给出一组测试数据的答案,即 \([a,b]\) 之间有多少不降数。

数据范围

\(1 \le a \le b \le 2^{31}-1\)

输入样例:

1 9
1 19

输出样例:

9
18

解题思路

数位dp

1081. 度的数量 一样,每一位每一位分析,即假设有一个 \(n\) 位的数,枚举到 \(i\) 位时,如果 \(A[i]<A[i-1]\) 说明这位不可能有贡献,直接 break,否则为了非降,从 \(A[i-1]\)\(A[i]-1\) 枚举该位数,后面 \(n-(i+1)+1\) 位数可从 \(A[i],A[i]+1,\dots,9\) 这些数中可重复选取,即这部分贡献为 \(C_{9-A[i]+1+n-(i+1)+1-1}^{n-(i+1)+1}\),另外如果本身该数就是非降,则还应该加上该数的贡献

  • 时间复杂度:\(O(logw)\)

代码

// Problem: 数字游戏
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/1084/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
// #define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=30;
int C[N][N],a,b,s[15],A[15],n;
void init()
{
	for(int i=0;i<30;i++)
		for(int j=0;j<=i;j++)
			if(!j)C[i][j]=1;
			else
				C[i][j]=C[i-1][j-1]+C[i-1][j];
	for(int i=1;i<=10;i++)
	{
		s[i]=C[9+i-1][i];
		s[i]+=s[i-1];
	}
	
}
int get(int x)
{
	if(x==0)return 0;
	int res=0;
	n=0;
	do
	{
		A[++n]=x%10;
		x/=10;
	}while(x);
	res+=s[n-1];
	reverse(A+1,A+1+n);
	for(int i=1;i<=n;i++)
	{
		if(i>1&&A[i]<A[i-1])break;
		for(int j=max(1,A[i-1]);j<A[i];j++)res+=C[9-j+1+n-i-1][n-i];	
		if(i==n)res++;
	}
	return res;
}
int main()
{
	init();
    while(~scanf("%d%d",&a,&b))
    	printf("%d\n",get(b)-get(a-1));
    return 0;
}
posted @ 2022-12-07 16:33  zyy2001  阅读(30)  评论(0编辑  收藏  举报