HDU 4722 Good Numbers(数位DP)

来源:互联网 发布:mac lol 编辑:程序博客网 时间:2024/05/01 21:33

原题地址:传送门  http://acm.hdu.edu.cn/showproblem.php?pid=4722

Good Numbers

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4094    Accepted Submission(s): 1309


Problem Description
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.
 

Input
The first line has a number T (T <= 10000) , indicating the number of test cases.
Each test case comes with a single line with two numbers A and B (0 <= A <= B <= 1018).
 

Output
For test case X, output "Case #X: " first, then output the number of good numbers in a single line.
 

Sample Input
21 101 20
 

Sample Output
Case #1: 0Case #2: 1
Hint
The answer maybe very large, we recommend you to use long long instead of int.



题目大意就是,求区间内每个位数相加的和能整除10的数的数量。


简单的数位DP。

只要在搜索时把每一位加起来对10求余,到最后是否为0就好。


直接贴代码:

#include<cstdio>#include<cstring>#include<cstdlib>using namespace std;long long int dp[20][13];int digit[20];long long int dfs(int pos,int pre,bool limit){    if(pos==-1)    {        return pre==0;    }    if(!limit&&dp[pos][pre]!=-1)    {        return dp[pos][pre];    }    long long int res=0;    int tmp=limit? digit[pos]:9;    for(int i=0;i<=tmp;i++)    {        int Npre=(i+pre)%10;        res+=dfs(pos-1,Npre,limit&&i==tmp);    }    if(!limit)    {        dp[pos][pre]=res;    }    return res;}long long int cal(long long int a){    int len=0;    while(a)    {        digit[len++]=a%10;        a=a/10;    }    return dfs(len-1,0,1);}int main(){    long long int t,a,b,cake=1;    scanf("%lld",&t);    while(t--)    {        memset(dp,-1,sizeof(dp));        scanf("%lld%lld",&a,&b);        printf("Case #%lld: %lld\n",cake++,cal(b)-cal(a-1));    }    return 0;}


0 0