Balanced Number 数位DP+ 枚举

传送门

分析

这道题跟我前段时间写的一道数位DP的思路有点一致,但是居然没想出

来首先我们确定一下,任何一个平衡数的支点,都仅存在一个支点,所以,我们可以去枚举每一个支点,计算每一个支点下,平衡数的数量,然后相加即可

最后只需要注意一下,如果每一位都取0,那么任何一位都可以作为支点,但合法的数字只有一个0,所以最后答案需要特殊处理一下

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#pragma GCC target("avx2")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 20;
ll f[N][N][N*101];
int a[N];


ll dfs(int pos,int x,int res,bool st){
    if(!pos) return !res;
    if(res < 0) return 0;
    if(!st && f[pos][x][res] != -1) return f[pos][x][res];
    int ed = st ? a[pos] : 9;
    ll ans = 0 ;
    for(int i = 0;i <= ed;i++)
        ans += dfs(pos - 1,x,res + i * (pos - x),st && (i == ed));
    if(!st) f[pos][x][res] = ans;
    return ans;
}

ll solve(ll x){
    int cnt = 0;
    while(x){
        a[++cnt] = x % 10;
        x /= 10;
    }
    ll ans = 0;
    for(int i = 1;i <= cnt;i++) ans += dfs(cnt,i,0,1);
    return ans - cnt + 1;
}

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        ll x,y;
        memset(f,-1,sizeof f);
        scanf("%lld%lld",&x,&y);
        printf("%lld\n",solve(y) - solve(x - 1));
    }
    return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值