zoukankan      html  css  js  c++  java
  • 【hdu4734】F(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
    ",i,sum(bb,calc(a)));
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    java的Scanner获取输入内容
    Java数据类型的转换
    Java十进制数转二进制的方法
    Java查看项目目录以及导入项目
    ios 证书申请和发布流程
    Spring 注解大全
    Spring Boot开发Web应用
    Spring Boot中Web应用的统一异常处理
    Spring Boot中使用AOP统一处理Web请求日志
    Spring Boot属性配置文件详解
  • 原文地址:https://www.cnblogs.com/yelir/p/11417523.html
Copyright © 2011-2022 走看看