HDU 3709 Balanced Number 数位DP -

本文提供了一道来自HDU在线评测系统的编程题(编号3709)的解决方案。该题通过枚举支点位置的方法解决了一个特定的数位DP问题,代码实现了递归搜索所有可能的支点位置,并计算了每种情况下的有效数字数量。

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

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=3709

枚举支点位置就好了

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxp=21;
typedef long long LL;
LL d[maxp][maxp][1601];
int digit[maxp];
LL DFS(int pos,int point,int preSum,bool limit)
{     //当前位置|  支点位置|  前面的和|  是否在上界
	if(pos==-1) return preSum==0;
	if(preSum<0) return 0;

	LL& ans=d[pos][point][preSum];
	if(!limit && ans!=-1) return ans;
	LL temp=0;
	int up=limit?digit[pos]:9;
	for(int i=0;i<=up;i++)
		temp+=DFS(pos-1,point,preSum+(pos-point)*i,limit&&i==up);
	if(!limit) ans=temp;
	return temp;
}
LL solve(LL x){
	int len=0;
	while(x){
		digit[len++]=x%10;
		x/=10;
	}
	LL ans=0;

	for(int i=0;i<len;i++)  //因为每次DFS都会计算全为0的情况,所以ans要减去(len-1)
		ans+=DFS(len-1,i,0,true);

	return ans-len+1;
}
int main(int argc, char const *argv[])
{
	int T; LL s,e;
	scanf("%d",&T);
	memset(d,-1,sizeof(d));
	while(T--){
		scanf("%lld%lld",&s,&e);
		if(s==0) cout<<solve(e)<<endl;
		else cout<<solve(e)-solve(s-1)<<endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值