Balanced NumberTime Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others) 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
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 ≤ 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
Author GAO, Yuan
Source 2010 Asia Chengdu Regional Contest
Recommend zhengfeng |
算法分析:
题意:
给定区间[a,b],求区间内平衡数的个数。所谓平衡数即有一位做平衡点,左右两边数字的力矩想等。
分析:
dp[len][pos][sum]表示len位数,支点pos,两边和位sum(左边力为正,右边为负),
遍历每一位做为平衡点,进行搜索,sum保存数字乘以距离的和,若sum为0,则说明平衡。
要注意因为遍历了len次,0每一次都会被算到,最后要减去(len - 1)。
还有个小技巧是当sum<0时就可以直接return了,可以加速。因为,len由大到小的过程中,sum是由大到小的变化,但绝不会小于0,否则就是不能平衡。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
#define LL long long
LL dp[20][20][2000];
int dis[20];
LL dfs(int len, int pos, int sum, bool limit)
{
if(len < 0)
return sum?0:1;
if(sum < 0)
return 0;
if(!limit && dp[len][pos][sum] != -1)
return dp[len][pos][sum];
LL ans = 0;
int end = limit?dis[len]:9;
for(int i=0; i<=end; i++)
{
ans += dfs(len-1, pos, sum+(len-pos)*i, limit&&i==dis[len]);
}
if(!limit)
dp[len][pos][sum] = ans;
return ans;
}
LL solve(LL n)
{
int len = 0;
while(n)
{
dis[len++] = n%10;
n /= 10;
}
LL ans = 0;
for(int i=0; i<len; i++)
ans += dfs(len-1, i, 0, 1);
return ans - (len-1);
}
int main()
{
int T;
scanf("%d", &T);
memset(dp, -1, sizeof(dp));
while(T--)
{
LL l, r;
scanf("%lld%lld", &l, &r);
printf("%lld\n", solve(r) - solve(l-1));
}
return 0;
}