hdu3709(数位dp)

Balanced Number

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 ≤ 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

题解:题目大意就是找区间[x,y]中满足条件的数。条件是在这个数中选一个数字作为支点,左右杠杆平衡。举个例子,如4139.选择3为支点,左边的力矩是4*2+1*1=9,右边是9*1=9。这道题是一道典型的数位dp题,其实也并不难,思路挺明显的,就是将这个数的每一位作为支点搜索一下,看看成不成立。

不过这题有一些细节,值得注意!

(1)计算力矩时,即sum+(pos-pivot)*i这句话,如果pos是从大到小搜的,那么pos和pivot顺序不能换,否则会数组越界。

(2)在dp中加上sum<0这句话可以加快速度,因为搜索时符合单调性

(3)计算结果ans需减掉pos-1,因为0这个数被多算了pos-1次(因为一共搜索了pos次)。

代码:

#include
#include
using namespace std; 
typedef long long ll;  
int a[20];
ll dp[20][20][2000];
ll dfs(int pos,int pivot,int sum,bool limit)
{  
    if(pos==-1) return sum==0?1:0;
    if(sum<0)  return 0;
    if(!limit&& dp[pos][pivot][sum]!=-1) return dp[pos][pivot][sum]; 
    int up=limit?a[pos]:9;
    ll ans=0;  
    for(int i=0;i<=up;i++)
    {   
        ans+=dfs(pos-1,pivot,sum+(pos-pivot)*i,limit && i==a[pos]) ;
    }  
    if(!limit) dp[pos][pivot][sum]=ans;  
    return ans;  
}  
ll solve(ll x)  
{  
    int pos=0;  
    while(x) 
    {  
        a[pos++]=x%10;
        x/=10;  
    }  
    ll res=0;
    for(int i=0;i<=pos-1;i++)
    res+=dfs(pos-1,pos-1-i,0,true);
    return res-pos+1;
}  
int main()  
{  
    ll le,ri;  
    int t;
    scanf("%d",&t);
    memset(dp,-1,sizeof(dp));
    for(int i=1;i<=t;i++)
    {
    	 scanf("%lld%lld",&le,&ri);
    	 printf("%lld\n",solve(ri)-solve(le-1));  
	}
    return 0;
}  

 

 

 

你可能感兴趣的:(dp,hdoj)