hdu 4734

F(x)

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


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
 
数位dp,用dp【x】【y】代表取到第x位小于等于F(Y)的个数,dfs多开一维记录F(Y),逐减看F(Y)的值
 
 
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
int dp[10][10240];
int bit[10];
int dfs(int len,int num,bool flag) //flag为1代表前位已选定,答案完整
{                                  //否则答案还不完整
    if(len==-1) return num>=0;
    if(num<0) return 0;
    if(!flag&&dp[len][num]!=-1) return dp[len][num];
    int end=flag?bit[len]:9;
    int ans=0;
    for(int i=0;i<=end;i++)
    {
        ans+=dfs(len-1,num-(i*(pow(2,len))),flag&&i==end);
    }
    if(!flag) dp[len][num]=ans;
    return ans;
}
int F(int A)
{
    int x=1;
    int ans=0;
    while(A)
    {
        ans+=(A%10)*x;
        x<<=1;
        A/=10;
    }
    return ans;
}
int cacu(int x,int A)
{
    int top=0;
    while(x)
    {
      bit[top++]=x%10;
      x/=10;
    }
    return dfs(top-1,F(A),1);
}
int main()
{
   int T,ca=1;
   memset(dp,-1,sizeof(dp));
   for(scanf("%d",&T);T;T--)
   {
       int A,B;
       scanf("%d%d",&A,&B);
       printf("Case #%d: %d\n",ca++,cacu(B,A));
   }
   return 0;
}
View Code

 

 
posted @ 2016-04-17 19:14  江南何采莲  阅读(150)  评论(0编辑  收藏  举报