Balanced Number [数位DP]

14 篇文章 0 订阅

题意:一个数字是Balanced number当且仅当存在一个位置loc,使得一个数字的pos位置上的数字dig_pos*(pos-loc)的和是0。
询问区间内有多少这样的数字。
采用数位DP的方法,对于每一个位置,保存状态dp[pos][loc][sum]表示当前位pos位,中心位置为loc,前面的累加和为sum的状态的答案。
执行call()函数的时候,对于一个区间,loc从1到len遍历一次,由于除0以外,所有的数字最多有1个位置loc使得sum==0,0的话存在len个位置。所以要在结果中减去len-1。

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL dp[20][20][1800];
int dig[20];
LL dfs(int pos, int loc, int sum, int limit)
{
    if(!pos)
        return sum == 0 ? 1 : 0;
    if(sum < 0)
        return 0;
    if(!limit && dp[pos][loc][sum] != -1)
        return dp[pos][loc][sum];
    int n = limit?dig[pos]:9;
    LL res = 0;
    for(int i = 0; i <= n; ++i)
    {
        res += dfs(pos-1, loc, sum+i*(pos-loc), limit && i==n);
    }
    if(!limit) dp[pos][loc][sum] = res;
    return res;
}

LL call(LL x)
{
    if(x == -1) return 0;
    int len = 0;
    while(x)
    {
        dig[++len] = x%10;
        x /= 10;
    }
    LL res = 0;
    for(int i = len; i >= 1; --i)
        res += dfs(len, i, 0, 1);
    return res - len + 1;//important!
}
int main()
{
    ios::sync_with_stdio(false);
    memset(dp, -1, sizeof(dp));
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    #endif // ONLION_JUDGE
    int T;
    cin >> T;
    while(T--)
    {
        LL a, b;
        cin >> a >> b;
        cout << call(b) - call(a-1) << endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值