HDU 4734 F(x)
F(x)
Problem Description
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).
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 < 109)
For each test case, there are two numbers A and B (0 <= A,B < 109)
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
解题思路
给定A,B, 在[0,B]之间的数字假设为i,问你有多少数字 f[i] 值小于f[A]
解题思路:
数位DP,只需按照位数转移为缩短1位的子问题即可
解题代码:
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
const int maxn=50000;
int dp[10][maxn];
int DP(int len,int sum){
if(sum<0) return 0;
if(len==0) return 1;
if(dp[len][sum]!=-1) return dp[len][sum];
int ans=0;
for(int i=0;i<=9;i++){
ans+=DP(len-1,sum-i*(1<<(len-1)) );
}
return dp[len][sum]=ans;
}
int f(int x){
int s=0,sum=0;
while(x>0){
sum+=(1<<s)*(x%10);
x/=10;
s++;
}
return sum;
}
int dfs(int a,int b){
vector <int> v;
while(b>0){
v.push_back(b%10);
b/=10;
}
int ans=0,sum=f(a);
for(int i=v.size()-1;i>=0;i--){
for(int t=0;t<v[i];t++){
ans+=DP(i,sum);
sum-=(1<<i);
}
if(i==0) ans+=DP(i,sum);
}
return ans;
}
int main(){
memset(dp,-1,sizeof(dp));
int t,a,b;
cin>>t;
for(int i=1;i<=t;i++){
cin>>a>>b;
cout<<"Case #"<<i<<": "<<dfs(a,b)<<endl;
}
return 0;
}

浙公网安备 33010602011771号