计数类dp讲解

在这里插入图片描述

import java.util.*;
public class Main{
    
    
    static int power10(int i){
    
    
        int res = 1;
        while(i!=0){
    
    
            res*=10;
            i--;
        }
        return res;
    }
    static int get(List<Integer> list,int a,int b){
    
    
        int res = 0;
        for(int i=a;i>=b;i--){
    
    
            res = res*10+list.get(i);
        }
        return res;
    }
    static int count(int n,int x){
    
    
        if(n==0) return 0;
        List<Integer> list = new ArrayList<Integer>();
        while(n!=0){
    
    
            list.add(n%10);
            n/=10;
        }
        n = list.size();
        int res = 0;
        //当x为0的时候我们需要从n-2开始,因为不能有前导0,我们要从n-2来计算0的个数,那么我们在分类
        for(int i=n-1-(x==0?1:0);i>=0;i--){
    
    
            //考虑第一大类情况,这类情况只有在不是最左边的那个列的时候才存在
            //并且我们要注意如果x=0的话,那么我们的的第一种情况里面就应该是1-(abc-1)而不是0-(abc-1)
            if(i<n-1){
    
    
                res+=get(list,n-1,i+1)*power10(i);
                if(x==0) res-=power10(i);
            }
            if(x==list.get(i)){
    
    
                res+=get(list,i-1,0)+1;
            }else if(list.get(i)>x){
    
    
                res+=power10(i);
            }
        }
        return res;
    }
    public static void main(String[] args){
    
    
        Scanner scan = new Scanner(System.in);
        int a,b;
        a = scan.nextInt();
        b = scan.nextInt();
        StringBuilder str = new StringBuilder();
        while(a!=0||b!=0){
    
    
            for(int i=0;i<=9;i++){
    
    
               str.append(count(Math.max(a,b),i)-count(Math.min(a,b)-1,i)+" ");
            }
            str.append("\n");
            a = scan.nextInt();
            b = scan.nextInt();
        }
        System.out.print(str);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44932835/article/details/109279899