描述
Click Here
\quad
For a decimal number x with n digits(AnAn-1An-2…A2A1), we define its weight as F(x)=F(x)=An*2n-1+An-1*2n-2+…+A2*21+A1*20. 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
Output the answer.
Sample Input
3
0 100
1 10
5 100
Sample Output
Case #1: 1
Case #2: 2
Case #3: 13
题解
代码搬运工。。。。。。,具体题解请看这篇博客。
-
dp[pos][sum]:代表枚举到数位pos,数位pos之后(包括数位pos)的数字的最大值不超过sum的数值个数
-
int dfs(int pos,int sum,bool limit); 该函数的功能是:枚举到数位pos,数位pos之前的数位(不包括数位pos)的二进制数值的值。
以样例 5 300为例: 百位为0 十位为0 返回结果dp[0][5]=6 即F(0) F(1) F(2) F(3) F(4) F(5) 百位为0 十位为1 返回结果dp[0][3]=4 即F(10) F(11) F(12) F(13) 百位为0 十位为2 返回结果dp[0][2]=2 即F(20) F(21) 百位为1 十位为0 返回结果dp[0][2]=2(已计算过) 即F(100) F(101)
代码
#include<cstdio>
#include<cstring>
#include<iostream>
#include<string>
using namespace std;
const int N=1e4+5;
int dp[12][N];
///x的二进制数
int f(int x)
{
if(x==0) return 0;
int ans=f(x/10);
return ans*2+(x%10);
}
int all;
int a[12];
int dfs(int pos,int sum,bool limit)
{
if(pos==-1) {return sum<=all;}
if(sum>all) return 0;
if(!limit && dp[pos][all-sum]!=-1) return dp[pos][all-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][all-sum]=ans;
return ans;
}
int solve(int x)
{
int pos=0;
while(x)
{
a[pos++]=x%10;
x/=10;
}
return dfs(pos-1,0,true);
}
int main()
{
int a,ri;
int T_T;
int kase=1;
scanf("%d",&T_T);
memset(dp,-1,sizeof dp);
while(T_T--)
{
scanf("%d%d",&a,&ri);
all=f(a);
printf("Case #%d: %d\n",kase++,solve(ri));
}
return 0;
}