HDU3709平衡数Balanced Number

Posted wuwendongxi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU3709平衡数Balanced Number相关的知识,希望对你有一定的参考价值。

Description

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


思路

  • 首先,对于某个非0的数,最多可能有一个pivot的位置。
  • 由于0对于每个位置都会被统计到,最后要再减去重复个数
  • dp[i][j][k],i是长度,j是支点,k是力矩和,dp[i][j][k]是以j为支点的平衡数的数量
  • sum在支点一侧增加,另一侧减小,最后和为0满足题目条件

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#define int long long
using namespace std;
int bit[20],dp[20][20][2005];
int dfs(int x,int point,int sum,int flag)
{
	if(x==1) return sum==0;
	if(sum<0) return 0;//小于0时一定不是支点,返回0
	if(!flag&&dp[x][point][sum]!=-1) return dp[x][point][sum];
	int count=flag?bit[x-1]:9,ans=0;
	for(int i=0;i<=count;++i) ans+=dfs(x-1,point,sum+(x-1-point)*i,flag&&i==count);
	return flag?ans:dp[x][point][sum]=ans;
}
long long start(long long x)
{
	int len=0; long long ans=0; memset(dp,-1,sizeof(dp));
	for(;x;x/=10) bit[++len]=x%10;
	for(int i=1;i<=len;++i) ans+=dfs(len+1,i,0,1);
	return ans-(len-1);
}
signed main()
{
	int n; scanf("%lld",&n);
	while(n--)
	{
		long long a,b; scanf("%lld%lld",&a,&b);
		printf("%lld
",start(b)-start(a-1));
	}
	return 0;
}




以上是关于HDU3709平衡数Balanced Number的主要内容,如果未能解决你的问题,请参考以下文章

HDU 3709 Balanced Number (数位DP)

HDU 3709 Balanced Number(数位dp)

hdu 3709 Balanced Number(数位dp)

hdu3709 Balanced Number

hdu3709 Balanced Number

HDU 3709 Balanced Number