Balanced Number HDU - 3709

本文介绍了一种算法,用于计算给定区间内平衡数的数量。平衡数是指一个非负整数,通过找到合适的支点,使得该支点左边的力矩和等于右边的力矩和。文章提供了一个具体的实现方案,利用动态规划的方法来高效地解决问题。

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

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,yx,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,yx,y in a line.
Sample Input
2
0 9
7604 24324
Sample Output
10
897

大致题意:当一个数存在一个平衡点,使得平衡点左侧的力矩和等于右侧的力矩和时,这个数是平衡数,
问你区间[x,y]中平衡数的个数。

思路:加一维表示力矩和,枚举支点。

代码如下

#include<iostream>
#include<algorithm>
#include<string>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<cstring>
#include<cmath>
#define LL long long  
#define ULL unsigned long long  
using namespace std;
LL dp[20][20][2000];//dp[l][dian][he] 第i位, 支点 dian  力矩和 he   
int digit[20];


LL dfs(int l, int dian,int he,int jud) {
    if ( l==-1) return he==0;
    if(he<0) return 0;//因为力矩和是先增大后减少的,如果此时已经小于0则说明这种情况不行,剪枝
    if ( !jud && dp[l][dian][he]!=-1) return dp[l][dian][he];
    LL ans = 0;
    int nex = jud ? digit[l] : 9;
    for (int i = 0; i <=  nex; i++)
    {
       ans += dfs( l-1 ,dian, he+i*(l-dian),jud && i==nex );
    }
    if(!jud)
    {
        dp[l][dian][he]=ans;
    }
    return ans;
}

LL f(LL num){
    memset(dp,-1,sizeof(dp));

    int tol = 0;

    while(num){
        digit[tol++]=num%10;
        num/=10;
    }
    LL sum=0;
    for(int i=0;i<tol;i++)//枚举支点为i
       {
       sum+=dfs(tol-1,i,0,1);
   }
    return sum-tol+1;//减去全为0的情况
}

int main()
{
    int T;
    LL x,y;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld",&x,&y);
        printf("%lld\n",f(y)-f(x-1));
    }
    return 0; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值