码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 4734 数位dp

时间:2015-02-16 23:30:52      阅读:352      评论:0      收藏:0      [点我收藏+]

标签:

http://acm.hdu.edu.cn/showproblem.php?pid=4734

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

/**
hdu 4734  数位dp 记忆化搜索
题目大意:求给定区间1~B中所有小于f(A)的数。
解题思路:记忆化搜索, 标记dp[i][j]表示i位数比j小的数的个数。时间卡的很紧,不用记忆化会超时的
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;

int A,B,dp[11][50000],a[25];
int len;

int f(int n)
{
    int ans=0,len=1;
    while(n)
    {
        ans+=n%10*len;
        len*=2;
        n/=10;
    }
   /// printf("f(a)=%d\n",ans);
    return ans;
}

int dfs(int len,int ans,int flag)
{
    if(len<0) return ans>=0;
    if(ans<0) return 0;
    int sum=0;
    if(!flag&&dp[len][ans]!=-1)return dp[len][ans];
    int end=flag?a[len]:9;
    for(int i=0; i<=end; i++)
    {
        sum+=dfs(len-1,ans-i*(1<<len),flag&&i==end);
    }
    if(!flag)dp[len][ans]=sum;
    return sum;
}
int main()
{
    int T,tt=0;
    scanf("%d",&T);
    memset(dp,-1,sizeof(dp));
    while(T--)
    {
        scanf("%d%d",&A,&B);
        len=0;
        while(B)
        {
            a[len++]=B%10;
           /// printf("%d ",a[len-1]);
            B/=10;
        }
        ///printf("\n");
        printf("Case #%d: %d\n",++tt,dfs(len-1,f(A),1));
    }
    return 0;
}


hdu 4734 数位dp

标签:

原文地址:http://blog.csdn.net/lvshubao1314/article/details/43857301

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!