[动态规划][数位dp]F(x)

Problem Description
For a decimal number x with n digits (A nA n-1A n-2 ... A 2A 1), we define its weight as F(x) = A n * 2 n-1 + A n-1 * 2 n-2 + ... + A 2 * 2 + A 1 * 1. Now you are given two numbers A and B, please calculate how many numbers are there between 0 and B, inclusive, whose weight is no more than F(A).
 

 

Input
The first line has a number T (T <= 10000) , indicating the number of test cases.
For each test case, there are two numbers A and B (0 <= A,B < 10 9)
 

 

Output
For every case,you should output "Case #t: " at first, without quotes. The t is the case number starting from 1. Then output the answer.
 

 

Sample Input
3 0 100 1 10 5 100
 

 

Sample Output
Case #1: 1 Case #2: 2 Case #3: 13
思路:状态dp[i][j]表示位数为i的数中不大于j的数有多少;状态转移方程dp[i][j]=sum{dp[i-1][j-k*(1<<i-1)]}(k<=limit?digit[i]:9)
AC代码:
#include <iostream>
#include<cstdio>
typedef long long ll;
using namespace std;

ll dp[15][30100];
ll digit[15];

ll dfs(ll len,ll ans,bool limit){
  if(len==0) return 1;
  if(!limit && dp[len][ans]) return dp[len][ans];
  ll sum=0;
  for(ll i=0;i<=(limit?digit[len]:9);i++){
    if(i*(1<<(len-1))<=ans) sum+=dfs(len-1,ans-i*(1<<(len-1)),limit&&i==digit[len]);
  }
  if(!limit) dp[len][ans]=sum;
  return sum;
}

ll solve(ll x,ll a){
  digit[0]=0;
  while(x){
    digit[++digit[0]]=x%10;
    x/=10;
  }
  ll tot=0,tmp=1;
  while(a) tot+=a%10*tmp,a/=10,tmp*=2;
  return dfs(digit[0],tot,true);
}

int main()
{
    ll t;scanf("%lld",&t);
    for(ll k=1;k<=t;k++){
        ll a,b;scanf("%lld%lld",&a,&b);
        printf("Case #%lld: %lld\n",k,solve(b,a));
    }
    return 0;
}

转载于:https://www.cnblogs.com/lllxq/p/9429124.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值