Balanced Number HDU - 3709 数位DP

本文介绍了一种算法,用于计算给定范围内平衡数的数量。平衡数是指以某位数字为中心轴,该位左边数字乘以其到中心的距离之和等于右边数字乘以其到中心的距离之和的数。算法通过深度优先搜索和动态规划实现高效计算。

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

A balanced number is a non-negative integer that can be balanced if a pivot is placed at some digit. More specifically, imagine each digit as a box with weight indicated by the digit. When a pivot is placed at some digit of the number, the distance from a digit to the pivot is the offset between it and the pivot. Then the torques of left part and right part can be calculated. It is balanced if they are the same. A balanced number must be balanced with the pivot at some of its digits. For example, 4139 is a balanced number with pivot fixed at 3. The torqueses are 42 + 11 = 9 and 9*1 = 9, for left part and right part, respectively. It’s your job
to calculate the number of balanced numbers in a given range [x, y].

Input
The input contains multiple test cases. The first line is the total number of cases T (0 < T ≤ 30). For each case, there are two integers separated by a space in a line, x and y. (0 ≤ x ≤ y ≤ 10 18).

Output
For each case, print the number of balanced numbers in the range [x, y] in a line.

Sample Input
2
0 9
7604 24324

Sample Output
10
897

题意:求给出区间 [l,r] 内平衡数的个数:平衡数:以某位数字作为中心轴,此位左边的 数字X距离的和与右边的数字X距离的和相等的数的个数。

思路:我们枚举每一位数作为中心轴,然后dfs搜索其余位上的数字,记录一个sum,sum表示左边的数字X距离的和与右边的数字X距离的和的差值,即题目要求sum=0的数的个数,值得注意的一点是,我们是从高位向低位搜索,因此sum是先变大后变小,当sum<0时,不可能再重新回到0,因此我们可以剪枝,sum小于0时直接return。我们用一个三维数组dp[pos][st][sum],表示pos位数以st为轴时左边的数字X距离的和与右边的数字X距离的和的差值为sum的数的个数。

#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
ll dp[20][20][1600],dit[20];
ll dfs(int pos,int st,int sum,int limit)
{
	if(pos<0) return sum==0;
	if(sum<0) return 0;	
	if(!limit&&dp[pos][st][sum]!=-1) return dp[pos][st][sum];
	int up=limit?dit[pos]:9;
	ll ans=0;
	for(int i=0;i<=up;i++)
	{
		ans+=dfs(pos-1,st,sum+(pos-st)*i,limit&&i==dit[pos]);
	}
	if(!limit) dp[pos][st][sum]=ans;
	return ans;
}
ll solve(ll x)
{
	int len=0;
	ll ans=0;
	while(x)
	{
		dit[len++]=x%10;
		x/=10;
	}
	for(int i=0;i<len;i++)
		ans+=dfs(len-1,i,0,1);
	return ans-(len-1);//00,000,0000....为重复的,因此需要减去
int main()
{
	int t;
	ll n,m;
	cin>>t;
	memset(dp,-1,sizeof(dp));
	while(t--)
	{
		cin>>n>>m;
		cout<<solve(m)-solve(n-1)<<endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值