zoj3416 数位DP

Balanced Number

Time Limit: 5 Seconds Memory Limit: 65536 KB

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 4*2 + 1*1 = 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 casesT (0 <T ≤ 30). For each case, there are two integers separated by a space in a line,x andy. (0 ≤ xy ≤ 1018).

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

题意:给出两个数a,b算[a,b]范围内有多少个平衡数,如4139,当它以3为轴时,左边有4*2+1*1=9,右边为1*9=9,所以左右相等

思路:只要想到怎么计算他们的和其实就不难了,只要枚举轴在第几位,然后把每一位到轴的指加上,轴左边为正右边为负,当所有位累加完之后,只要判断是否抵消和为0,即可。最后只要减去多余的,因为0会重复算,0只需要算一次,用数位dp会算len次,即是数字的长度,减去len-1即是最后答案

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
long long dp[20][20][2000];
int s[20];
long long dfs(int now,int sum,int cur,int flag){
	if(now<=0) return sum==0;
	if(!flag&&dp[now][cur][sum]!=-1)
		return dp[now][cur][sum];
	int num=(flag?s[now]:9);
	long long ans=0;
	for(int i=0;i<=num;i++){
		int temp=sum+(now-cur)*i;
		if(temp>=0)
		ans+=dfs(now-1,temp,cur,flag&&i==num);
	}
	if(!flag)
		dp[now][cur][sum]=ans;
	return ans;
	
}
long long slove(long long x){
	if(x==-1)
		return 0;
	int k=0;
	while(x){
		s[++k]=x%10;
		x/=10;
	}
	long long ans=0;
	for(int i=1;i<=k;i++)
		ans+=dfs(k,0,i,1);
	ans=ans-k+1;
	return ans;
}
int main(void){
	long long a,b;
	int t;
	scanf("%d",&t);
	memset(dp,-1,sizeof(dp));
	while(t--){
		scanf("%lld%lld",&a,&b);
		printf("%lld\n",slove(b)-slove(a-1));
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值