hdu3709 Balanced Number[數位dp]


Balanced Number

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


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

 

Author
GAO, Yuan
 

 

Source

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
typedef long long ll;
const int N=20;
ll l,r,f[N][N][N*101];int T,bits[N];
ll dfs(int pos,int x,int st,bool lim){
    if(!pos) return !st;
    if(st<0) return 0;
    ll &res=f[pos][x][st],ans=0;
    if(!lim&&(~res)) return res;
    int up=!lim?9:bits[pos];
    for(int i=0;i<=up;i++){
        ans+=dfs(pos-1,x,st+i*(pos-x),lim&&i==bits[pos]);
    }
    if(!lim) res=ans;
    return ans;
}
ll solve(ll x){
    if(x<0) return 0;
    int len=0;ll ans=0;
    for(;x;x/=10) bits[++len]=x%10;
    for(int i=1;i<=len;i++) ans+=dfs(len,i,0,1);
    return ans-len+1;
}
int main(){
    memset(f,-1,sizeof f);
    for(scanf("%d",&T);T--;)
        scanf("%I64d%I64d",&l,&r),
        printf("%I64d\n",solve(r)-solve(l-1));
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM