Balanced Number
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 3733 Accepted Submission(s): 1736
Problem 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 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].
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
Author
GAO, Yuan
Source
写在前面:其实这个是寒假做的题,才发现没有写博客,而且用的dfs的原理我现在才懂==补上
题意:从L到R有多少个“平衡数”比方说4139在3处是平衡的4*2 + 1*1 = 9 and 9*1 = 9 9==9
做法:常规dfs,枚举每位以及每个平衡点,dfs记录到当前位的时候的总和,最终==0时候是平衡数。注意这里flag变量的作用:
我们都知道flag代表的是是否受限,受限和不受限有什么区别呢?当前面有限制的时候,dp即使下标都相同,但是情况出现的比不受限制的少,那么dp值就不会是相同的
/************
hdu3709
2016.3.11
************/
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
long long dp[30][30][3000];
int num[30];
long long dfs(int pos,int center,int sum,bool flag)
{
if(pos==0) return sum==0;
if(sum<0) return 0;
if(!flag&&dp[pos][center][sum]!=-1) return dp[pos][center][sum];
long long ans=0;
int maxn=flag?num[pos]:9;
for(int i=0;i<=maxn;i++)
{
ans+=dfs(pos-1,center,sum+i*(pos-center),i==maxn&&flag);
}//pos-center
if(!flag) dp[pos][center][sum]=ans;
return ans;
}
long long cal(long long x)
{
long long ans=0;
int pos=0;
while(x)
{
num[++pos]=x%10;
x/=10;
}
for(int i=1;i<=pos;i++)
ans+=dfs(pos,i,0,1);
return ans-pos+2;
}
int main()
{
//freopen("cin.txt","r",stdin);
int t;
long long n,m;
memset(dp,-1,sizeof(dp));
scanf("%d",&t);
while(t--)
{
scanf("%I64d%I64d",&n,&m);
printf("%I64d\n",cal(m)-cal(n-1));
}
return 0;
}