F(x)
Time Limit: 1000/500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4990 Accepted Submission(s): 1857
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 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
Source
刚开始用dp(pos, sum)表示当前枚举到第pos位,当前和为sum时的方案数,结果超时。后来仔细想了下,这样表示状态在记忆化搜索时剪枝的机会很少。为什么呢,前面那个dp表示第pos位,和为sum时的方案数,这里面还有一个限制,这个方案数是在满足最终结果小于等于f(A)时的数目。当前算出来的dp值不能应用到以后的输入中(除非输入的A都相同)。
所以用dp(pos, sum)表示当前枚举到第pos位,还差sum的方案数。则这个dp方程不受f(A)的限制,对以后的数据输入也有效。
#include<cstdio>
#include<cstring>
#include<string>
#include<cctype>
#include<iostream>
#include<set>
#include<map>
#include<cmath>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 1e4 + 5;
int dp[12][maxn];
int a[12];
int all, kase;
int f(int m) {
if(!m) return 0;
return f(m/10)*2+m%10;
}
int dfs(int pos, int num, bool limit) {
if(pos == -1) return num >= 0;
if(num < 0) return 0;
if(!limit && dp[pos][num] >= 0) return dp[pos][num];
int up = limit ? a[pos] : 9;
int ans = 0;
for(int i = 0; i <= up; i++) {
ans += dfs(pos-1, num-(1<<pos)*i, limit && i == a[pos]);
}
if(!limit) dp[pos][num] = ans;
return ans;
}
int solve(int A, int B) {
int pos = 0;
while(B) {
a[pos++] = B % 10;
B /= 10;
}
return dfs(pos-1, f(A), true);
}
int main()
{
int T;
kase = 1;
scanf("%d", &T);
memset(dp, -1, sizeof dp);
while(T--) {
int A, B;
scanf("%d%d", &A, &B);
printf("Case #%d: %d\n", kase++, solve(A, B));
}
return 0;
}