版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/niiick/article/details/82874319
Time limit 500 ms
Memory limit 32768 kB
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)
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.
题目分析
表示处理到第
位,剩余没填的位允许的最大weight为
的数字个数
套上数位DP的记搜版子就好
注意dp数组只用在最开始进行一次赋初值-1,否则会T
#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long lt;
int read()
{
int f=1,x=0;
char ss=getchar();
while(ss<'0'||ss>'9'){if(ss=='-')f=-1;ss=getchar();}
while(ss>='0'&&ss<='9'){x=x*10+ss-'0';ss=getchar();}
return f*x;
}
const int maxn=11;
int T,A,B;
int dp[maxn][4600],dig[maxn];
int tpow[]={1,2,4,8,16,32,64,128,256,512,1024,2048};
int F(int x)
{
int res=0,k=0;
while(x)
{
res+=(x%10)*tpow[k++];
x/=10;
}
return res;
}
int DP(int len,int lim,int pre)
{
if(len==0) return 1;
if(!pre&&dp[len][lim]!=-1) return dp[len][lim];
int res=0,mx=pre?dig[len]:9;
for(int i=0;i<=mx;++i)
{
int add=i*tpow[len-1];
if(lim-add<0) break;
res+=DP(len-1,lim-add,pre&&i==mx);
}
if(!pre) dp[len][lim]=res;
return res;
}
int solve(int x)
{
int len=0;
while(x)
{
dig[++len]=x%10;
x/=10;
}
return DP(len,F(A),1);
}
int main()
{
T=read();
memset(dp,-1,sizeof(dp));//只用在最开始赋一次初值
for(int i=1;i<=T;++i)
{
A=read();B=read();
printf("Case #%d: %d\n",i,solve(B));
}
return 0;
}