HDU 3709 Balanced Number

Balanced Number

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


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
2
0 9
7604 24324
 
Sample Output
10
897
 
Author
GAO, Yuan
 
Source
 
解题:枚举支点,进行数位dp
 
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long LL;
 4 const int maxn = 25;
 5 LL dp[maxn][maxn][2005];
 6 int b[maxn];
 7 LL dfs(int p,int pivot,int sum,bool flag){
 8     if(!p) return sum == 0;
 9     if(sum < 0) return 0;
10     if(flag && dp[p][pivot][sum] != -1)  return dp[p][pivot][sum];
11     LL ret = 0;
12     int u = flag?9:b[p];
13     for(int i = 0; i <= u; ++i)
14         ret += dfs(p-1,pivot,sum + (p - pivot)*i,flag||(i < u));
15     if(flag) dp[p][pivot][sum] = ret;
16     return ret;
17 }
18 LL solve(LL x){
19     int len = 0;
20     while(x){
21         b[++len] = x%10;
22         x /= 10;
23     }
24     LL ret = 0;
25     for(int i = 1; i <= len; ++i)
26         ret += dfs(len,i,0,false);
27     return ret - len + 1;
28 }
29 int main(){
30     int kase;
31     memset(dp,-1,sizeof dp);
32     scanf("%d",&kase);
33     while(kase--){
34         LL L,R;
35         scanf("%I64d%I64d",&L,&R);
36         printf("%I64d
",solve(R) - solve(L - 1));
37     }
38     return 0;
39 }
View Code
原文地址:https://www.cnblogs.com/crackpotisback/p/4782270.html