HDU3709 Balanced Number【数位DP】

Topic link: HDU3709 Balanced Number

Question meaning: Ask about the number of balanced numbers in the interval [l,r]. The balanced number refers to selecting a certain position as a fulcrum, and the sum of the value * moment of each digit on the left and right sides is equal;

Analysis: dp[len][pos][sum] represents the number of length len. When the pivot is pos, the torque is the number of sum numbers; the transfer is the number of length len-1 + the lenth position. Come, so dp[len][pos][sum]+=dp[len-1][pos][sum+i*(pos-x)], i is the number that may appear in the lenth position, and there is no need to take it here When abs, sum is 0, it means balance;

#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll dp[20][20][1800];
int num[20];
ll dfs(int len,int pos,int sum,bool flag)
{
    if (!len) return sum==0?1:0;
    if (sum<0) return 0;
    if (!flag && dp[len][pos][sum]!=-1) return dp[len][pos][sum];
    int mx=flag?num[len]:9;
    ll res=0;
    for (int i=0;i<=mx;i++) res+=dfs(len-1,pos,sum+i*(len-pos),flag && i==mx);
    if (!flag) dp[len][pos][sum]=res;
    return res;
}
ll solve(ll n)
{
    if (n<0) return 0;
    int len=0;
    for (;n;n/=10) num[++len]=n%10;
    ll sum=0;
    for (int i=1;i<=len;i++) sum+=dfs(len,i,0,true);
    return sum-(len-1);
}
int main()
{
    memset(dp,-1,sizeof(dp));
    int T;
    ll a,b;
    scanf("%d",&T);
    while (T--)
    {
        scanf("%lld%lld",&a,&b);
        printf("%lld\n",solve(b)-solve(a-1));
    }
    return 0;
} 

 

Guess you like

Origin blog.csdn.net/qq_43813163/article/details/102582752