hdu3709 Balanced Number

108 篇文章 0 订阅

Balanced Number

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


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
dp[i][j][k]表示有i位时,第j个数字做为中心,最后算得的权重为k,再用一下记忆化搜索就可以了,对于任意一个平衡数,一定只有一个中心使得其为平衡数,所以就可以枚举中心搜索,但是这样,会产生0,00,000,000...等这样的数,要最后减去就可以了!
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define M 23
__int64 pri[M],dp[M][M][2050];
__int64 dfs(int pos,int cen,__int64 pre,int flag){
    if(pos==0)return pre==0;
    if(pre<0)return 0;
    if(!flag&&dp[pos][cen][pre]!=-1)return dp[pos][cen][pre];
    int u=flag?pri[pos]:9;__int64 ans=0;
    for(int i=0;i<=u;i++)
    ans+=dfs(pos-1,cen,pre+(__int64)(i*(pos-cen)),flag&&i==u);
    return flag?ans:dp[pos][cen][pre]=ans;
}
__int64 solve(__int64 x){
    int cnt=0;
    while(x){
        pri[++cnt]=x%10;x/=10;
    }
    __int64 ans=0;
    for(int i=cnt;i>0;i--)
    ans+=dfs(cnt,i,0,1);
    return ans-cnt+1;
}
int main()
{
    int tcase;__int64 n,m;
    scanf("%d",&tcase);
    while(tcase--){
        scanf("%I64d%I64d",&n,&m);
        memset(dp,-1,sizeof(dp));
        printf("%I64d\n",solve(m)-solve(n-1));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值