Balanced number
Time limit:5 seconds Memory limit:65536 KB
A balanced number is a non-negative integer that can be balanced if a packet is placed at some digit. more specifically, imagine each digit as a box with weight indicated by the digit. when a distance is placed at some digit of the number, the distance from a digit to the distance is the offset between it and the distance. 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 specified at some of its digits. for example, 4139 is a balanced number with 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 casesT(0 <T≤ 30). For each case, there are two integers separated by a space in a line,XAndY. (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
10897
Author:Gao, Yuan
Source:The 2010 ACM-ICPC Asia Chengdu Regional Contest
A good number of DP questions.
The value must be the number of balances. One Dimension is added to indicate the torque.
/* * HDU 3709 * balanced number, enumeration pivot * DP [I] [J] [k] I indicates the number of processed digits, J indicates the pivot, and K indicates the torque and */ # Include <Iostream> # Include <Stdio. h> # Include <Algorithm> # Include < String . H> Using Namespace STD; Long Long DP [ 20 ] [ 20 ] [ 2000 ]; Int Bit [ 20 ]; Long Long DFS ( Int POs, Int Center, Int PRE, Bool Flag ){ If (Pos =- 1 )Return Pre = 0 ; If (Pre < 0 ) Return 0 ; // Current Torque is negative, pruning If (! Flag & DP [POS] [center] [pre]! =- 1 ) Return DP [POS] [center] [pre]; Int End = flag? Bit [POS]: 9 ; Long Long Ans = 0 ; For ( Int I = 0 ; I <= end; I ++ ) Ans + = DFS (POS- 1 , Center, pre + I * (POS-center), flag & I = End ); If (! Flag) DP [POS] [center] [pre] =Ans; Return Ans ;} Long Long Calc ( Long Long N ){ Int Len = 0 ; While (N) {bit [Len ++] = N % 10 ; N /= 10 ;} Long Long Ans = 0 ; For ( Int I = 0 ; I <Len; I ++ ) Ans + = DFS (LEN- 1 , I, 0 , 1 ); Return Ans-(LEN- 1 ); // Remove all zeros } Int Main (){ // Freopen ("in.txt", "r", stdin ); // Freopen ("out.txt", "W", stdout ); Int T; Long Long X, Y; memset (DP, - 1 ,Sizeof (DP )); // Do not forget this initialization. Scanf ( " % D " ,& T ); While (T -- ) {Scanf ( " % I64d % i64d " , & X ,& Y); printf ( " % I64d \ n " , Calc (y)-Calc (X- 1 ));} Return 0 ;}