HDU 3709 Balanced Number ZOJ 3416 Balanced Number(数位DP)

Balanced Number
Time Limit: 5 Seconds      
Memory Limit: 65536 KB

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 [xy].

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 [xy] in a line.

Sample Input

2
0 9
7604 24324

Sample Output

10
897

Author: GAO, Yuan
Source: The 2010 ACM-ICPC Asia Chengdu Regional Contest

 

 

 

很好的数位DP题目。

要求是平衡数,增加一维表示力矩。

/*
 * HDU 3709
 * 平衡数,枚举支点
 * dp[i][j][k] i表示处理到的数位,j是支点,k是力矩和
 */

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
long long dp[20][20][2000];
int bit[20];
long long dfs(int pos,int center,int pre,bool flag)
{
    if(pos==-1)return pre==0;
    if(pre<0)return 0;//当前力矩为负,剪枝
    if(!flag&&dp[pos][center][pre]!=-1)
        return dp[pos][center][pre];
    int end=flag?bit[pos]:9;
    long long ans=0;
    for(int i=0;i<=end;i++)
        ans+=dfs(pos-1,center,pre+i*(pos-center),flag&&i==end);
    if(!flag)dp[pos][center][pre]=ans;
    return ans;
}
long long calc(long long n)
{
    int len=0;
    while(n)
    {
        bit[len++]=n%10;
        n/=10;
    }
    long long ans=0;
    for(int i=0;i<len;i++)
        ans+=dfs(len-1,i,0,1);
    return ans-(len-1);//去掉全0的情况
}
int main()
{
//    freopen("in.txt","r",stdin);
//    freopen("out.txt","w",stdout);
    int T;
    long long x,y;
    memset(dp,-1,sizeof(dp));//这个初始化一定别忘记
    scanf("%d",&T);
    while(T--)
    {
        scanf("%I64d%I64d",&x,&y);
        printf("%I64d\n",calc(y)-calc(x-1));
    }
    return 0;
}

 

 

 

    原文作者:算法小白
    原文地址: https://www.cnblogs.com/kuangbin/archive/2013/05/01/3052842.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞