For a decimal number x with n digits (A
nA
n-1A
n-2 ... A
2A
1), we define its weight as F(x) = A
n * 2
n-1 + A
n-1 * 2
n-2 + ... + A
2 * 2 + A
1 * 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 < 10 9)
For each test case, there are two numbers A and B (0 <= A,B < 10 9)
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
一个N位的数X (AnAn-1An-2 ... A2A1),F(x) = An * 2n-1 + An-1 * 2n-2 + ... + A2 * 2 + A1 * 1,求当x分别取0到B(包括B),共有多少个数符合F(B)<=F(A)
一开始把memset放在while(t--)里,结果一直超时。以后记住,记忆化深搜的东西是可以在多组数据间通用的。
由F(x)的公式很容易想出该用数位dp,dp[pos][num]表示x从1位取到pos位数,F(x)的值比F(A)小(或等于)的有几个。num=F(A)-当前数x的F(x)。num>=0表示F(x)的值比F(A)小(或等于)。
http://acm.hdu.edu.cn/showproblem.php?pid=4734
#include<iostream>
#include<algorithm>
#include<string>
#include<map>
#include<vector>
#include<cmath>
#include<queue>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
#define ll long long
using namespace std;
ll a,b;
ll dp[11][200000];
int bit[11];
int dfs(int pos,int num,int flag){ //flag是个妙点
if(num<0)
return 0;
else if(pos==-1)
return 1;
if(flag==0&&dp[pos][num]!=-1)
return dp[pos][num];
ll s=0;
int end=(flag==1?bit[pos]:9); //flag=0表示这个数字前面的位上已经放了比B的那一位小的数字,因此这个数字肯定比B小,因此后面的位能任意取0-9
for(int i=0;i<=end;++i) //遍历这一位上能放的所有数字
s+=dfs(pos-1,num-i*(1<<pos),flag&&i==end); //i==end是针对flag=1的时候,从前面数到这一位还没有比B小
if(flag==0) //注意条件
dp[pos][num]=s;
return s;
}
int main(){
int t;
scanf("%d",&t);
int cnt=0;
memset(dp,-1,sizeof(dp)); //记忆化深搜(结果通用)
while(t--){
int a,b;
scanf("%d%d",&a,&b);
int l=-1;
while(b){
bit[++l]=b%10; //存B每一位上的数
b/=10;
}
int FA=0,len=-1;
while(a){
FA+=(a%10)*(1<<(++len); //算F(A)
a/=10;
}
printf("Case #%d: %d\n",++cnt,dfs(l,FA,1));
}
return 0;
}