HDU4734 F(x) (数位DP)

F(x)

Time Limit: 1000/500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3900 Accepted Submission(s): 1442

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
3
0 100
1 10
5 100

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

Source
2013 ACM/ICPC Asia Regional Chengdu Online

Recommend
liuyiding | We have carefully selected several similar problems for you: 5775 5774 5773 5772 5771

#include 
#include 
#include 
#include 
#include 
const int maxn = (1<<10)*10+5;
using namespace std;
int numa[20],numb[20];
int weight;
int dp[20][maxn];

int dfs(int pos,int sum,int over)
{
    if(pos<0)
    {
        return sum>=0;
    }
    if(sum<0)
        return 0;
    if(dp[pos][sum]!=-1&&!over)
        return dp[pos][sum];
    int last=over?numb[pos]:9;
    int ans=0;
    for(int i=0;i<=last;i++)
    {
        int now;
        now=i*pow(2,pos);
        //if(sum<=weight)
        ans+=dfs(pos-1,sum-now, over&&i==last);
    }
    if(!over)
        dp[pos][sum]=ans;
    return ans;
}
int solve(int a,int b)
{
    weight=0;
    int lena=0,lenb=0;
    while(a)
    {
        numa[lena++]=a%10;
        a/=10;
    }
    for(int i=lena;i>=1;i--)
    {
        weight+=numa[i-1]*pow(2,i-1);
    }

    while(b)
    {
        numb[lenb++]=b%10;
        b/=10;
    }
    return dfs(lenb-1,weight,true);
}

int main()
{
    int cas;
    scanf("%d",&cas);
    int t=1;
    memset(dp,-1,sizeof(dp));
    while(cas--)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        printf("Case #%d: %d\n",t++,solve(a,b));
    }
    return 0;
}

你可能感兴趣的:(DP)