[Hdu4734] F (x) - Digital DP

Subject description:

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 formats:
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 formats:
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 

Ideas:

Set f [i] [j] [k] denotes the i-th bit, the first element of j, k is the current calculated 

Transfer equation f [i] [j] [l] + = f [i-1] [k] [l- (j << (i-1))];

First pre-treatment, due to the multiple sets of data, pre-processing and about the prefix, the first query about the integer part of the sum, and then seek after the rest:

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 << = (. 1-I), DI = 0; // find the residual portion added before each subtracting m 
		IF (m <0 ) BREAK; 
	} 
	return ANS;

  

Code:

#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;
}

  

Guess you like

Origin www.cnblogs.com/yelir/p/11417523.html