Discription
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)
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
题意
给定f(x)的定义:F(x) = An * 2n-1 + An-1 * 2n-2 + ... + A2 * 2 + A1 * 1
,Ai是十进制数位,然后给出a,b求区间[0,b]内满足f(i)<=f(a)的i的个数。
思路
数位DP板子题,直接套板子就可以。
AC代码
#include<bits/stdc++.h>
using namespace std;
int dp[12][5000];
int num[12];
int m,n;
int F(int x)
{
int p=1,ans=0;
while(x)
{
ans+=(x%10)*p;
p<<=1;
x/=10;
}
return ans;
}//根据题意写出F(x)函数
int dfs(int pos,int value,int limit)
{
if(value<0)
return 0;//枚举到比0小就结束
if(pos<0)
return value>=0;//枚举到比0小就结束
if(!limit && dp[pos][value]!=-1)
return dp[pos][value];//表示枚举的这个数是合法的。
int ans=0;
int endd= limit?num[pos]:9;//根据limit判断枚举的上界up
for(int i=0; i<=endd; i++)
ans+=dfs(pos-1,value-i*(1<<pos),limit&&i==endd);//深搜状态转移
if(!limit)
dp[pos][value]=ans;
return ans;
}
int solve(int x)
{
int len=0;
while(x)
{
num[len++]=x%10;
x/=10;
}
return dfs(len-1,F(m),1);
}//将每一位分开
int main()
{
int t;
memset(dp,-1,sizeof(dp));
scanf("%d",&t);
for(int tt=1; tt<=t; tt++)
{
scanf("%d%d",&m,&n);
printf("Case #%d: %d\n",tt,solve(n));
}
return 0;
}
来源:CSDN
作者:爱吃老谈酸菜的DV
链接:https://blog.csdn.net/weixin_43460224/article/details/103245506