传送门: http://acm.hdu.edu.cn/showproblem.php?pid=4734
题意:我们定义十进制数x的权值为f(x) = a(n)*2^(n-1)+a(n-1)*2(n-2)+…a(2)*2+a(1)*1,a(i)表示十进制数x中第i位的数字。给出a,b,求出0~b有多少个不大于f(a)的数。
分析:数位dp。
dp[i][j]表示i位数比j小的数的个数, 另外注意状态转移方程:
dp[i][j]+=dp[i-1][j-k*(1<<(i-1))];
#include <cstdio>
#include <cmath>
#include <cstring>
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <algorithm>
using namespace std;
#define mem(a,n) memset(a,n,sizeof(a))
#define pb push_back
#define fi first
#define se second
#define rep(i,a,n) for(int i=a; i<n; i++)
typedef long long ll;
typedef unsigned long long ull;
const int mod=1e9+7;
const double eps=1e-6;
const int INF=0x3f3f3f3f;
const int N=1e4+5;
int dp[10][N],digit[10];
int a,b;
int dfs(int pos,int pre,bool bounded)
{
if(pos==0) return pre>=0;///边界处理
if(pre<0) return 0; ///边界处理
int& ret=dp[pos][pre];
if(!bounded && ret!=-1) return ret;
int end = bounded ? digit[pos] : 9;
int ans=0;
for(int i=0;i<=end;i++)
ans+=dfs(pos-1,pre-i*(1<<(pos-1)),bounded&&i==end);///是pos-1 !!!
if(!bounded) ret=ans;
return ans;
}
int f(int x)
{
int ans=0,tmp=1;
while(x)
{
ans= ans + x%10*tmp;
x/=10;
tmp*=2;
}
return ans;
}
int cal(int x)
{
int len=0;
while(x)
{
digit[++len]=x%10;
x/=10;
}
return dfs(len,f(a),true);
}
int main()
{
int T;
scanf("%d",&T);
mem(dp,-1);
for(int cas=1;cas<=T;cas++)
{
scanf("%d%d",&a,&b);
printf("Case #%d: %d\n",cas,cal(b));
}
return 0;
}