F - Balanced Number HDU - 3709 数位dp


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].
InputThe 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).OutputFor 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
题意:平衡数字是一个非负整数,如果主键位于某个数字位置,则该整数可以平衡。更具体地说,将每个数字想象为一个带有数字指示的重量的盒子。当一个枢轴放置在数字的某个数字处时,从数字到枢轴的距离就是它与枢轴之间的偏移量。然后可以计算左侧部分和右侧部分的扭矩。如果它们相同,它是平衡的。平衡数字必须与某些数字的枢轴平衡。例如,4139是一个平衡数字,其中枢轴固定为3.对于左侧部分和右侧部分,扭矩分别为4 * 2 + 1 * 1 = 9和9 * 1 = 9。*对于平衡数字来说,中轴的位置是确定的,对于不同的平衡数字来说中轴的位置不一定相同**

计算给定范围[x,y]中的平衡数字的数量。

思路:int dp[pos][sta][num];   pos代表第几位数,sta表示中轴位置,num表示数字是否平衡。

平衡数字的计算 : if(pos>sta) num+=i*(pos-sta),if(pos<sta) num-=i*(sta-pos),
合并为  num+=i*(pos-sta),, 当pos=-1时,num==0才满足题意。过程中num<0可以剪枝。

对于一个数字,枚举所有可能的中轴位置,00000000,0000000,000000,...0,重复计算,减去之后保留一个即可

#include <iostream>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <queue>
#include <algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
typedef long long LL;
const LL mod=1e9+7;
const int M=13;
using namespace std;
const int N =1e5+100;
LL a[20];
LL dp[20][20][2000];
LL dfs(LL pos,LL sta,LL num,LL limit)//数位dp板子
{
    if(pos==-1) return num==0;
    if(num<0) return 0;//剪枝
    if(!limit&&dp[pos][sta][num]!=-1) return dp[pos][sta][num];
    LL up=limit?a[pos]:9;
    LL ans=0;
    for(LL i=0; i<=up; i++)
        ans+=dfs(pos-1,sta,num+i*(pos-sta),limit&&i==up);
    return limit?ans:dp[pos][sta][num]=ans;
}
LL slove(LL x)
{
    if(x<0) return 0;//不存在负数
    LL pos=0;
    for(; x; x/=10)
        a[pos++]=x%10;
    LL ans=0;
    for(LL i=0; i<pos; i++)//枚举中轴位置
        ans+=dfs(pos-1,i,0,1);
    return ans-pos+1;//减去重复的00000,0000,000,00....
}
int main()
{
    mem(dp,-1);
    int t;
    scanf("%d",&t);
    while(t--)
    {
        LL l,r;
        scanf("%lld%lld",&l,&r);
        printf("%lld\n",slove(r)-slove(l-1));
    }
}



猜你喜欢

转载自blog.csdn.net/xiangaccepted/article/details/80513684