HDU 4734 F[x] (数位dp)

本文介绍了一种通过深度搜索算法解决计数问题的方法,对于给定的两个十进制数A和B,计算0到B(含)范围内,有多少个数的权重不超过F(A)。权重定义为每个位上的数字乘以对应位置的2的幂次和。

#include <stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[20];
int dp[20][6000];
int p[50];
int all;
int dfs(int pos,int sta,bool limit)
{
	if(pos==-1)
	return 1;
	if(!limit&&dp[pos][sta]!=-1)
	{
		return dp[pos][sta]; 
	}
	int up=limit?a[pos]:9;
	int sum=0,i;
	for(i=0;i<=up;i++)
	{
		int k=sta-i*p[pos];
		if(k<0) continue;
		sum+=dfs(pos-1,k,limit&&i==up);
	}
	if(!limit)
	dp[pos][sta]=sum;
	return sum;
}
int solve(int x)
{
	int cnt=0;
	while(x)
	{
		a[cnt++]=x%10;
		x/=10;
	}
	return dfs(cnt-1,all,1);
}
int main(int argc, char *argv[])
{
	int t,i,cs=1;
	scanf("%d",&t);
	memset(dp,-1,sizeof(dp));
	p[0]=1;
	for(i=1;i<30;i++)
	{
		p[i]=p[i-1]*2;
	}
	while(t--)
	{
		int A,B;
		while(scanf("%d %d",&A,&B)!=EOF)
		{
			all=0;
			int cnt1=0;
			while(A)
			{
				all+=(A%10)*p[cnt1++];
				A/=10;
			}
			printf("Case #%d: ",cs++);
			printf("%d\n",solve(B));
		}
	}
	return 0;
}

Time Limit: 1000/500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6851    Accepted Submission(s): 2649


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)
 

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值