HDU - 4734 数位DP

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

题意:给你两个数A,B,并给你一个公式求F(x),问[0,B]中有多少个数x,使得F(x)<=F(A)。

思路:先求出F(A),令sum=F(A),用二维数组dp[pos][sum-state]表示pos位数中F(A)与F(x)的差为sum-state的数的个数,F(x)<=F(A),即sum-state>=0。因为state随着搜索的进行,在一个分支中state只会越来越大,因此可以进行剪枝,当sum-state<0时直接return。

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;
ll dit[10],sum,dp[10][4600],aa[10];
ll f(ll x)
{
    if(x==0) return 0;
    ll ans=f(x/10);
    return ans*2+(x%10);
}
ll dfs(int pos,int st,int limit)
{
	if(pos<0) return (sum-st)>=0;
	if(sum-st<0) return 0;
	if(!limit&&dp[pos][sum-st]!=-1) return dp[pos][sum-st];
	int up=limit?dit[pos]:9;
	ll ans=0;
	for(int i=0;i<=up;i++)
	{
		ans+=dfs(pos-1,st+i*(1<<pos),limit&&i==dit[pos]);
	}
	if(!limit) dp[pos][sum-st]=ans;
	return ans;
}
ll solve(ll x)
{
	int len=0;
	while(x)
	{
		dit[len++]=x%10;
		x/=10;
	}
	return dfs(len-1,0,1);
}
int main()
{
	int t,cas;
	ll a,b;
	cin>>t;
	cas=1;
	memset(dp,-1,sizeof(dp));
	while(t--)
	{
		cin>>a>>b;
		sum=f(a);
		
		printf("Case #%d: %lld\n",cas++,solve(b));
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/why932346109/article/details/86761165