HDU 3709 Balanced Number

来源:互联网 发布:手机放线软件 编辑:程序博客网 时间:2024/06/04 23:15

Balanced Number

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 6344    Accepted Submission(s): 3030


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].
 

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
20 97604 24324
 

Sample Output
10

897

题意:一个数为平衡数当且仅当如果将某一位数作为支点则该位左右不分的segma(d[i]*(loc-i))相等。

dp[len][loc][sum]记忆化搜索。一个数最多只有一个支点,所以可以先枚举支点,由于0的特殊性,每一位都会多算一次所以应该减去。

#include<stdio.h>#include<algorithm>#include<string.h>using namespace std;#define ll long longll dp[20][20][2005], d[20];ll dfs(ll len, ll loc, ll sum, ll flag){if (len < 0) return sum == 0;if (sum < 0) return 0;if (!flag&&dp[len][loc][sum] != -1) return dp[len][loc][sum];int k = flag ? d[len] : 9;ll ans = 0;for (int i = 0;i <= k;i++)ans += dfs(len - 1, loc, sum + (ll)i*(len - loc), flag&&i == k);if (!flag) dp[len][loc][sum] = ans;return ans;}ll query(ll n){if (n < 0) return 0;int len = 0;ll ans = 0;while (n) d[len++] = n % 10, n /= 10;for (int i = len - 1;i >= 0;i--)ans += dfs(len - 1, i, 0, 1);return ans - len + 1;}int main(){ll a, b, t;memset(dp, -1, sizeof(dp));scanf("%lld", &t);while (t--){scanf("%lld%lld", &a, &b);printf("%lld\n", query(b) - query(a - 1));}return 0;}