Balanced Number
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 5097 Accepted Submission(s): 2434
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
题意:求范围内的平衡数个数,平衡数即以某个数位为支点,其左边的数字乘以对应力矩的和等于右边数字的力矩和。
思路:枚举支点位置即可。
# include <stdio.h>
# include <string.h>
# define LL long long
int a[20];
LL dp[19][19][2000];
LL dfs(int pos, int piv, int l, bool limit)//数位,支点位置,当前力矩和,上界限制
{
if(pos==-1) return l==0;
if(!limit && dp[pos][piv][l] != -1) return dp[pos][piv][l];
if(l<0) return 0;
int up = limit?a[pos]:9;
LL tmp = 0;
for(int i=0; i<=up; ++i)
{
long long tmp2 = l;
tmp2 += (pos-piv)*i;
tmp += dfs(pos-1, piv, tmp2, limit&&i==a[pos]);
}
if(!limit)
dp[pos][piv][l] = tmp;
return tmp;
}
LL solve(LL num)
{
int cnt = 0;
LL ans = 0;
while(num)
{
a[cnt++] = num%10;
num /= 10;
}
for(int i=0; i<cnt; ++i)
ans += dfs(cnt-1, i, 0, true);
ans -= cnt; //减去全为0的情况。
return ans;
}
int main()
{
memset(dp, -1, sizeof(dp));
int t;
LL n, m;
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld",&n,&m);
printf("%lld\n",solve(m)-solve(n-1));
}
return 0;
}
本文介绍了一种计算特定范围内平衡数数量的算法。平衡数定义为可在某一位上找到支点,使左侧数字乘以其到支点的距离之和等于右侧数字相应乘积之和的整数。文章详细阐述了通过递归深度优先搜索来高效解决此问题的方法。
9295

被折叠的 条评论
为什么被折叠?



