hdu4734F(x)-数位DP

Posted yelir

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu4734F(x)-数位DP相关的知识,希望对你有一定的参考价值。

题目描述:

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).
输入格式:
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 every case,you should output "Case #t: " at first, without quotes. The t is the case number starting from 1. Then output the answer.

输入样例:

3
0 100
1 10
5 100

输出样例:

Case #1: 1
Case #2: 2
Case #3: 13 

思路:

设f[i] [j] [k] 表示第i位,首元素为j,当前计算的值为k 

转移方程f[i][j][l]+=f[i-1][k][l-(j<<(i-1))];

先预处理,由于多组数据,预处理一下前缀和,查询时先求和一下整数的部分,其余之后再求:

int i,j,p,di=1,ans=1 + (calc(n)<=m);
	for(i=1;b[i]<=n;i++)
	for(j=1;j<10;j++)
	ans+=f[i][j][m];
	for(;i;i--)
	   
		p=n/b[i-1]%10;
		for(j=di;j<p;j++)ans+=f[i][j][m];
		m-=p<<(i-1),di=0;//求残余的部分,每次减去之前加的m
		if(m<0)break;
	
	return ans;

  

代码:

#include<cstdio>
#include<iostream>
#include<cstdlib>
using namespace std;
int f[10][10][10500],b[100];
int calc(int x)

	int t=1,tot=0;
	while(x) tot+=(x%10)*t,x/=10,t<<=1;
	return tot;

void init()

	int i,j,k,l;
	f[0][0][0]=b[0]=1;
	for(int i=1;i<10;i++)
	
		b[i]=b[i-1]*10;
		for(j=0;j<10;j++)
		for(k=0;k<10;k++)
		for(l=j<<(i-1);l<=10000;l++)
		f[i][j][l]+=f[i-1][k][l-(j<<(i-1))];		
	
	for( i=1;i<10;i++)
	for( j=0;j<10;j++)
	for( k=1;k<=10000;k++)
	f[i][j][k]+=f[i][j][k-1];

int sum(int n,int m)

	int i,j,p,di=1,ans=1 + (calc(n)<=m);
	for(i=1;b[i]<=n;i++)
	for(j=1;j<10;j++)
	ans+=f[i][j][m];
	for(;i;i--)
	
		p=n/b[i-1]%10;
		for(j=di;j<p;j++)ans+=f[i][j][m];
		m-=p<<(i-1),di=0;
		if(m<0)break;
	
	return ans;

int main()

	
	int T,i,a,bb;
	init();
	scanf("%d",&T);
	for(i=1;i<=T;i++)
		scanf("%d%d",&a,&bb);
		printf("Case #%d: %d\n",i,sum(bb,calc(a)));
	
	return 0;

  

以上是关于hdu4734F(x)-数位DP的主要内容,如果未能解决你的问题,请参考以下文章

HDU 4389——X mod f(x)(数位DP)

HDU 2089 不要62(数位dp入门)

HDU X mod f(x) (数位DP)

HDU 4734 F(x) 数位DP

HDU - 4734 - F(x) (数位DP)

hdu 4734 F(x) 数位DP