HDU 3709 Balanced Number【数位DP+思维】

题意:以数字中某一位为对称中心,两边的每位分别乘以中心距,两边的和相等就称为Balanced Number。
分析:想了好久,看一下题解恍然大悟,水题。。。
枚举中心,对于一个中心位进行dp,用模板dfs出口时判断val = 0就行了。
注意前导0,我多开了一维记录前导状态,开三维(中心位:pos位:val位)当然也是可行的,最后要减掉,因为枚举的每一个中心位状态0都满足。

#pragma GCC optimize ("O3")
#pragma GCC optimize ("O2")
#include <bits/stdc++.h>
#include <ext/rope>
using namespace std;
using namespace __gnu_cxx;
#define met(s) memset(s, 0, sizeof(s))
#define rep(i, a, b) for(int i = a; i <= b; ++i)
template <class T> inline void scan_d(T &ret) {
char c; ret = 0;
while ((c = getchar()) < '0' || c > '9');
while (c >= '0' && c <= '9') {
ret = ret * 10 + (c - '0'), c = getchar();}}
typedef long long LL;
typedef unsigned long long ull;
typedef pair<int, int> pii;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int MAXN = 1e4 + 10;
int a[20]; LL dp[20][20][4000][2];

inline LL dfs(int pos, int val, int x, int lead, int limit) {
    if(pos < 0 || val < 0) return val == 0 && !lead;
    if(!limit && dp[x][pos][val][lead] >= 0) return dp[x][pos][val][lead];
    int up = limit ? a[pos] : 9;
    LL ans = 0;
    for(int i = 0; i <= up; ++i) {
        int res = val + i * (pos - x);
        ans += dfs(pos - 1, res, x, lead && !i, limit && i == up) * 1LL;
    }
    if(!limit) dp[x][pos][val][lead] = ans;
    return ans;
}

inline LL so(LL x) {
    if(x < 0) return 0;
    int p = 0;
    while(x) {
        a[p++] = x % 10;
        x /= 10;
    }
    LL ans = 0;
    for(int i = 0; i < p; ++i) ans += dfs(p - 1, 0, i, 1, 1);
    return ans + 1;
}

int main() {
    int T; memset(dp, -1, sizeof(dp));
    scanf("%d", &T);
    while(T--) {
        LL a, b;
        scanf("%lld %lld", &a, &b);
        printf("%lld\n", so(b) - so(a - 1));
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值