HDU3709 Balanced Number

来源:互联网 发布:网络博客游戏怎么举报 编辑:程序博客网 时间:2024/06/14 01:16

Balanced Number

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


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
10897
 

Author
GAO, Yuan
 

Source
2010 Asia Chengdu Regional Contest
————————————————————————————————————
题目的意思是求一段区间里的平衡数的有几个,平衡数的定义是一个数以某一个数为中心,左右各算出数值*和中心的距离之和,如果一样就是。
思路:数位dp,先枚举以哪一位为中心,3位数组表示到len位置,以pos为中心的,和为sum的数有几个,dfs求解
#include <iostream>#include <cstring>#include <string>#include <vector>#include <queue>#include <cstdio>#include <set>#include <cmath>#include <map>#include <algorithm>#define INF 0x3f3f3f3f#define MAXN 10000005#define Mod 10001using namespace std;#define LL long longLL dp[20][20][2000];int a[100];LL dfs(int len,int pos,int sum,bool limit){    if(len<0)        return sum==0;    if(sum<0)        return 0;    if(dp[len][pos][sum]!=-1&&!limit)        return dp[len][pos][sum];    int up=limit?a[len]:9;    LL ans=0;    for(int i=0; i<=up; i++)    {            ans+=dfs(len-1,pos,sum+i*(len-pos),limit&&i==up);    }    return limit?ans:dp[len][pos][sum]=ans;}LL solve(LL x){    if(x<0)        return 0;    int cnt=0;    while(x>0)    {        a[cnt++]=x%10;        x/=10;    }    LL ans=0;    for(int i=cnt-1; i>=0; i--)        ans+=dfs(cnt-1,i,0,1);    return ans-(cnt-1);}int main(){    LL n,m;    int T;    memset(dp,-1,sizeof dp);    for(scanf("%d",&T); T--;)    {        scanf("%lld%lld",&m,&n);        printf("%lld\n",solve(n)-solve(m-1));    }    return 0;}


原创粉丝点击