hdu 3709 数字dp(小思)

http://acm.hdu.edu.cn/showproblem.php?pid=3709

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 ≤ 1018).
 

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
/**
hdu 3709   数位dp(小思维)
解题思路:有一个非常好的转化技巧,不然会超时。搜索的时候初始值定为f(x),然后最后和0比較。不要搜f(i) 和f(x)比較
*/
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
typedef long long LL ;
LL dp[25][25][2000],l,r;
int bit[25];
LL dfs(int len,int pos,int sum,int flag)
{
    if(len<0)
    {
        //printf("%d %d>>>>
",suml,sumr);
        return sum==0;
    }
    if(flag==0&&dp[len][pos][sum]!=-1)
        return dp[len][pos][sum];
    int end=flag?bit[len]:9;
    LL ans=0;
    for(int i=0;i<=end;i++)
    {
        //printf("len-1:%d
",len-1);
        ans+=dfs(len-1,pos,(sum+(len-pos)*i),flag&&i==end);
    }
    if(flag==0)
    {
        dp[len][pos][sum]=ans;
    }
    return ans;
}
LL solve(LL n)
{
    if(n==-1)return 0;
    int len=0;
    while(n)
    {
        bit[len++]=n%10;
        n/=10;
    }
    LL ans=0;
    for(int i=0;i<len;i++)
    {
       // printf("len-1:%d
",len-1);
        ans+=dfs(len-1,i,0,1);
    }
    return ans-len+1;
}
int main()
{
    int T;
    scanf("%d",&T);
    memset(dp,-1,sizeof(dp));
    while(T--)
    {
        scanf("%I64d%I64d",&l,&r);
        printf("%I64d
",solve(r)-solve(l-1));
    }
    return 0;
}


版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/zfyouxi/p/4721587.html