天天看點

HDU4722數位DP

If we sum up every digit of a number and the result can be exactly divided by 10, we say this number is a good number.

You are required to count the number of good numbers in the range from A to B, inclusive.

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;


public class Main {
	public static void main(String[] args) {
		new Task().solve(); 
	}
}

class Task{
	InputReader in = new InputReader(System.in) ;
	PrintWriter out = new PrintWriter(System.out) ;
	
	void solve(){
		int t = in.nextInt() ;
		for(int cas = 1 ; cas <= t ; cas++){
			long l = in.nextLong() ;
			long r = in.nextLong() ;
			out.print("Case #" + cas + ": ");
			out.println(work(r) - work(l-1)) ;
		}
		out.flush();
	}
	
    int[] bit = new int[20] ;
    long[][] dp = new long[20][10] ;
    {
    	for(int i = 0 ; i < 20 ; i++) Arrays.fill(dp[i] , -1) ;
    }
    
	long dfs(int pos , int sum , boolean isEnd){
	    if(pos < 0){
	    	return sum == 0 ? 1 : 0 ;
	    }	
	    if(!isEnd && dp[pos][sum] != -1) return dp[pos][sum] ;
	    int d = isEnd ?  bit[pos] : 9 ;
	    long result = 0 ;
	    for(int i = 0 ; i <= d ; i++){
	    	result += dfs(pos-1 , (sum+i)%10 , isEnd&&i==d) ;
	    }
	    if(!isEnd) dp[pos][sum] = result ;
	    return result ;
	}
	
	long work(long x){
		if(x < 0) return 0 ;
		int len = 0 ; 
		while(x > 0){
			bit[len++] = (int) (x % 10) ;
			x /= 10 ; 
		}
		return dfs(len-1, 0, true) ;
	}
} 

class InputReader {  
    public BufferedReader reader;  
    public StringTokenizer tokenizer;  
  
    public InputReader(InputStream stream) {  
        reader = new BufferedReader(new InputStreamReader(stream), 32768);  
        tokenizer = new StringTokenizer("");  
    }  
  
    private void eat(String s) {  
        tokenizer = new StringTokenizer(s);  
    }  
  
    public String nextLine() {  
        try {  
            return reader.readLine();  
        } catch (Exception e) {  
            return null;  
        }  
    }  
   
    public boolean hasNext() {  
        while (!tokenizer.hasMoreTokens()) {  
            String s = nextLine();  
            if (s == null)  
                return false;  
            eat(s);  
        }  
        return true;  
    }  
  
    public String next() {  
        hasNext();  
        return tokenizer.nextToken();  
    }  
  
    public int nextInt() {  
        return Integer.parseInt(next());  
    }  
  
    public long nextLong() {  
        return Long.parseLong(next());  
    }  
  
    public double nextDouble() {  
        return Double.parseDouble(next());  
    }  
  
    public BigInteger nextBigInteger() {  
        return new BigInteger(next());  
    }  
  
}