码迷,mamicode.com
首页 > 其他好文 > 详细

【HDU3709】平衡数Balanced Number

时间:2020-07-16 00:05:52      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:rip   nta   个数   ++   turn   sam   ecif   namespace   numbers   

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\n",start(b)-start(a-1));
	}
	return 0;
}

【HDU3709】平衡数Balanced Number

标签:rip   nta   个数   ++   turn   sam   ecif   namespace   numbers   

原文地址:https://www.cnblogs.com/wuwendongxi/p/13307487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!