Balanced number (Digital DP)

Source: Internet
Author: User
Balanced number Time limit:3000 Ms Memory limit:0 KB 64bit Io format:% LLD & % LlU

Description

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

 

Digital DP

It indicates that the search does not time out ..

 

#include<cstdio>#include<cstring>long long f[20][20][2000];int a[20];long long dfs(int pos,int z,int l,bool pd){    if(pos<=0) return l==0;    if(l<0) return 0;    if(!pd&&f[pos][z][l]!=-1) return f[pos][z][l];    int i,j,k,en;    en=pd?a[pos]:9;    long long ans=0;    for(i=0;i<=en;i++)        ans+=dfs(pos-1,z,l+(pos-z)*i,pd&&i==en);    if(!pd) f[pos][z][l]=ans;    return ans;}long long sum(long long x){    int i,n=0;    while(x){        a[++n]=x%10;        x=x/10;    }    long long ans=0;    for(i=n;i>0;i--)        ans+=dfs(n,i,0,1);    return ans-n+1;}int main(){    int tt;    long long x,y;    scanf("%d",&tt);    while(tt--){        scanf("%lld%lld",&x,&y);        memset(f,-1,sizeof(f));        printf("%lld\n",sum(y)-sum(x-1));    }    return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.