Balanced Number HDU-3709 Finding Moment Digital DP Winter Camp Training

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 42 + 11 = 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
2
0 9
7604 24324
Sample Output
10
897

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <map>
#include <stack>
#include <set>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <cstdio>
#define ls (p<<1)
#define rs (p<<1|1)
#define ll long long
using namespace std;
const int maxn = 2e6+5;
const int INF = 0x3f3f3f3f;
ll dp[30][82][2010];
ll a[30];
ll dfs(int pos,int pre,int mo,bool limt){
    
    //pre支点,力矩为mo
    if(pos==0){
    
    
        if(mo==0) return 1;
        else return 0;
    } 
    if(mo<0) return 0;
    if(!limt&&dp[pos][pre][mo]!=-1)
        return dp[pos][pre][mo];
    ll up;
    if(limt){
    
    
        up=a[pos];
    }
    else up=9;
    ll ans=0;
    for(int i=0;i<=up;i++){
    
    
        int tmp=mo+i*(pos-pre);
        ans+=dfs(pos-1,pre,tmp,limt&&i==a[pos]);
    }
    if(!limt)
        dp[pos][pre][mo]=ans;
    return ans;
    
}
ll init(ll x){
    
    
    if(x<0) return 0;
    int len=0;
    while(x){
    
    
        a[++len]=x%10;
        x/=10;
    }
    ll ans=0;
    for(int i=1;i<=len;i++){
    
    
        ans+=dfs(len,i,0,1);
    }
    return ans-len+1;
}
void solve(){
    
    
    int t;
    cin>>t;
    memset(dp,-1,sizeof(dp));
    memset(a,0,sizeof(a));
    int cas=0;
    while(t--){
    
    
        ll n,m;
        cin>>n>>m;
        cout<<init(m)-init(n-1)<<endl;
    }
}
int main()
{
    
    
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    solve();
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45891413/article/details/113001042