F(x)
Time Limit : 1000/500ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 12 Accepted Submission(s) : 7
Problem Description
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[sup]9[/sup])
Output
For every case,you should output "Case #t: " at first, without quotes. The [I]t[/I] 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
//题意:
求k属于[0,B]中,f(k)<=f(a)的个数。
//思路:
dp[pos][val]:pos表示数的位数,val表示a,dp[pos][val]表示pos位的数中比f(k)值比val小的数的个数。
每次val减去那一位的贡献,若val小于0,即不符合要求,return 0;
状态转移方程:dp[pos][val]+=dp[pos-1][val-i*pow(2,pos-1)];
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
int a,b;
int val;
int bit[20];
int dp[20][10009];
int dfs(int pos,int res,int flag)
{
if(pos<=0)
return (res>=0);
if(res<0)
return 0;
if(!flag&&dp[pos][res]!=-1)
return dp[pos][res];
int num=flag?bit[pos]:9;
int ans=0;
for(int i=0;i<=num;i++)
{
ans+=dfs(pos-1,res-i*pow(2,pos-1),flag&&i==num);
}
if(!flag)
dp[pos][res]=ans;
return ans;
}
int solve(int num)
{
int cnt=0;
memset(bit,0,sizeof(bit));
while(num)
{
bit[++cnt]=num%10;
num/=10;
}
if(cnt==0)
return 1;
else
return dfs(cnt,val,1);
}
int main()
{
int T;
int Case=1;
scanf("%d",&T);
memset(dp,-1,sizeof(dp));
while(T--)
{
scanf("%d%d",&a,&b);
printf("Case #%d: ",Case++);
int cnt=0;
val=0;
while(a)
{
val+=(a%10)*pow(2,cnt++);
a/=10;
}
int ans=solve(b);
printf("%d\n",ans);
}
return 0;
}