HDU 4734(数位DP)

来源:互联网 发布:淘宝的图片尺寸是多少 编辑:程序博客网 时间:2024/06/05 01:00

Problem Description
For a decimal number x with n digits (AnAn-1An-2 ... A2A1), we define its weight as F(x) = An * 2n-1 + An-1 * 2n-2 + ... + A2 * 2 + A1 * 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 < 109)
 

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
30 1001 105 100
 

Sample Output
Case #1: 1Case #2: 2Case #3: 13
 

Source
2013 ACM/ICPC Asia Regional Chengdu Online


思路

数位DP基础题,dp[pos][sum]表示枚举到pos位置<=sum的数量


代码示例

//#define LOCAL#include<iostream>#include<algorithm>#include<cstdio>#include<stdlib.h>#include<string.h>#include<algorithm>using namespace std;const int N=1e4+5;int dp[12][N];int A,b;int f(int x)//计算f(){    if(x==0) return 0;    int ans=f(x/10);    return ans*2+(x%10);}int a[12];//数位int dfs(int pos,int sum,bool limit){    if(pos==-1) return (sum>=0);    if(sum<0) return 0;    if(!limit && dp[pos][sum]!=-1) return dp[pos][sum];    int up=limit?a[pos]:9;    int ans=0;    for(int i=0;i<=up;++i){        ans+=dfs(pos-1,sum-i*(1<<pos),limit&&i==a[pos]);    }    if(!limit) dp[pos][sum]=ans;    return ans;}int solve(int x){    int pos=0;    while(x)    {        a[pos++]=x%10;        x/=10;    }    return dfs(pos-1,f(A),true);}int main(){    //std::ios::sync_with_stdio(false);    #ifdef LOCAL        freopen("read.txt","r",stdin);    #endif    //cout<<f(123)<<endl;    int t;    int kase=1;    cin>>t;    memset(dp,-1,sizeof(dp));    while(t--)    {        cin>>A>>b;        printf("Case #%d: %d\n",kase++,solve(b));    }    return 0;}





原创粉丝点击