HDU3709-Balanced Number-数位DP

(有任何问题欢迎留言或私聊 && 欢迎交流讨论哦

题意:传送门

 原题目描述最下面。
 栗子:4139。取第三位数字3为中心,左边的权值和为:4*2 + 1*1 = 9.右边的权值和为9*1 = 9.此数左右权值和相等则叫做平衡数,简称B数。
 问区间[L, R]内有多少个B数。

思路:

 普通的数位dp套个板子就行了,结构都是不变的。
 选择枚举中心点,求出对于每个上限数上以各个位置为中心点的B数的数量。累加求和。
 对于一个B数,他不可能有两个平衡点。
 然后要减去0,00,000这样有前导0,重复的情况。

AC代码:
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 1e4 + 7;
const int INF = 0x3f3f3f3f;
LL n, m;
int ar[N];
LL dp[19][19][3000];
LL dfs(int pos,int mid,int cur,bool limit){
  if(pos==-1) return cur==0;
  if(cur<0) return 0;
  if(!limit&&dp[pos][mid][cur]!=-1)return dp[pos][mid][cur];
  int up = limit? ar[pos]: 9;
  LL sum = 0;
  for(int i = 0; i <= up; ++i){
    int tmp = (pos-mid)*i;
    sum += dfs(pos-1,mid,cur+tmp,limit&&i==ar[pos]);
  }
  if(!limit) dp[pos][mid][cur] = sum;
  return sum;
}
LL solve(LL x){
  if(x<0) return 0;
  else if(x==0) return 1;
  int pos = 0;
  while(x){
    ar[pos++] = x % 10;
    x /= 10;
  }
  LL sum = 0;
  for(int i = pos-1; i >= 0; --i){
    sum += dfs(pos-1, i, 0, 1);
  }
  return sum-(pos-1);
}
int main(){
  int tim;
  scanf("%d", &tim);
  memset(dp, -1, sizeof(dp));
  while(tim--){
    scanf("%lld%lld", &n, &m);
    printf("%lld\n", solve(m)-solve(n-1));
  }
  return 0;
}


原题目描述:

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值