F(x)
Time Limit: 1000/500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7529 Accepted Submission(s): 2944
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学习笔记
对于这一个题,我们先计算出
A
A
的值,然后状态记录枚举到当前位的
f(x)
f
(
x
)
值,最后返回的时候要判断是否小于
A
A
的,不需要判前导0;
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
const int MAXN=1e4+5;
using namespace std;
int A,B,n;
int dp[12][MAXN];
int Fina;
int a[12],Num;
int clac(int x)
{
if(x==0) return 0;
int ans=clac(x/10);
return ans*2+(x%10);
}
int dfs(int pos,int sum,bool limit)
{
if(pos==-1) return sum<=Fina;
if(sum>Fina) return 0;
if(dp[pos][Fina-sum]!=-1&&(!limit)) return dp[pos][Fina-sum];
int up=limit ? a[pos] : 9;
int Tmp=0;
for(int i=0;i<=up;i++)
{
Tmp+=dfs(pos-1,sum+i*(1<<pos),limit && i==a[pos]);
}
if(!limit) dp[pos][Fina-sum]=Tmp;
return Tmp;
}
int solve(int x)
{
Fina=clac(A);
int pos=0;
while(x)
{
a[pos++]=x%10;
x/=10;
}
return dfs(pos-1,0,true);
}
int main()
{
scanf("%d",&n);
memset(dp,-1,sizeof(dp));
for(int i=1;i<=n;i++)
{
scanf("%d%d",&A,&B);
printf("Case #%d: %d\n",++Num,solve(B));
}
return 0;
}