题意: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). (0 <= A,B < 109)
解法:数位DP。第一步dp[i][j]记录着i位长度内,F值等于j的数的个数
转移方程为:dp[i][j]+=dp[i-1][j-k*(1<<(i-1))];
然后进行一遍dp[i][j]+=dp[i][j-1];这时dp[i][j]表示i位长度内,F值等于小于j的数的个数。然后就可以进行搜索了,注意一些边界情况就行。
代码:
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int dp[12][5000];
int A,B;
int change(int k)
{
int ans=0;int t=0;
while(k){
ans+=k%10*(1<<t);t++;k/=10;
}
return ans;
}
int rem[12];
int help(int k)
{
int t=0;
while(k){
rem[t++]=k%10;k/=10;
}
return t;
}
int getans(int k,int sum)
{
k++;
if(sum<0||k<0)
return 0;
if(k==1)
return min(sum,rem[0])+1;
if(sum==0) return 1;
int t=rem[k-1];
int ans=0;
for(int i=0;i<t;i++)
if(sum-i*(1<<(k-1))>=0)
ans+=dp[k-1][sum-i*(1<<(k-1))];
ans+=getans(k-2,sum-t*(1<<(k-1)));
return ans;
}
int main()
{
dp[0][0]=1;
for(int i=1;i<=9;i++)
{
for(int j=0;j<5000;j++)
{
for(int k=0;k<=9;k++)
{
if(j-k*(1<<(i-1))>=0)
dp[i][j]+=dp[i-1][j-k*(1<<(i-1))];
}
}
}
for(int i=1;i<=9;i++)
for(int j=1;j<5000;j++)
dp[i][j]+=dp[i][j-1];
int t;cin>>t;int cas=1;
while(t--){
memset(rem,0,sizeof rem);
scanf("%d%d",&A,&B);
int t=change(A);
printf("Case #%d: %d\n",cas++,getans(help(B),change(A)));
}
return 0;
}