HDU- 3709 Balanced Number(数位dp)

博客围绕一道题目展开,题目要求计算[a,b]之间满足特定条件的平衡数个数,如4139以3为中心时左右两边相等即为平衡数。解题思路采用数位dp,通过遍历中心pos进行计算,当len<0且sum=0时判定为平衡数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:点此传送
题目
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
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
题意

很简单,就是求[a,b]之间满足条件的数有多少个,条件举个例子来说(平衡数),例如4139 这个当中心是3时左边为1*1+4*2=9右边为1*9,左边等于右边这算是一个平衡数,问你有多少这样的平衡数

思路

数位dp,dp[len][pos][sum] len代表第几位数字,pos代表以pos为中心,sum代表平衡数两边的的差,这道题可以遍历中心pos来进行数位dp,当len<0且sum=0时代表是一个平衡数,sum可以用一种方法表示,到pos的距离乘以的d[i](第i位)

代码
#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
#define ll long long
#define rd(a) scanf("%d",&a)
#define rld(a) scanf("%lld",&a)
#define rs(a) scanf("%s",a)
#define me(a,b) memset(a,b,sizeof(a))
#define pb(a)  push_back(a)
const ll maxn=3e5+10;
const ll mod =1e9+7;
const ll inf =0x3f3f3f3f;
const double PI=acos(-1);
int d[20];
ll dp[20][20][2000];
ll dfs(int len,int pos,int limit,int sum){
    if(len<0) return sum==0;
    if(sum<0) return 0;
    if(!limit&&dp[len][pos][sum]!=-1) return dp[len][pos][sum];
    int end=limit?d[len]:9;
    ll ans=0;
    for(int i=0;i<=end;i++){
        ans+=dfs(len-1,pos,limit&(i==end),sum+i*(len-pos));
    }
    if(!limit) dp[len][pos][sum]=ans;
    return ans; 

}
ll solve(ll x){
    int len=0;
    while(x){
        d[len++]=x%10;
        x/=10;
    }
    ll ans=0;
    for(int i=0;i<len;i++)
    ans+=dfs(len-1,i,1,0);
    return ans-len+1;
}

int main(){

    me(dp,-1);
    int t;
    rd(t);
    while(t--){
      ll a,b;
      rld(a),rld(b);
      printf("%lld\n",solve(b)-solve(a-1));

    }


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值