hdu3709(数位dp)

11 篇文章 0 订阅

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<cstdio>
#include<cstring>
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;
}  

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值