HDU - 4722 Good Numbers(数位dp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chimchim04/article/details/88843179

Good Numbers

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

2
1 10
1 20

Sample Output

Case #1: 0
Case #2: 1

        
  

Hint

The answer maybe very large, we recommend you to use long long instead of int.

题目大意:求[ a , b ] 有多少个数是 各个位数的和mod10等于0 的数

思路:比赛的时候想到要用数位dp,但是很久没用有点忘了,没推对

数位dp   dp [ i ] [ j ]  为长度为 i  和mod10为 j   的个数  

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
const int N=20;
ll dp[20][10];
int d[20];
ll dfs(int len,int k,int lim)   
{
    if(len==0) return k==0;
    if(!lim&&dp[len][k]!=-1) return dp[len][k];
    int maxx=lim?d[len]:9;
    ll ans=0;
    for(int i=0;i<=maxx;i++)
        ans+=dfs(len-1,(i+k)%10,lim&&(i==maxx));
    if(!lim) dp[len][k]=ans;
    return ans;
}
ll solve(ll x)
{
    int k=0;
    while(x)
    {
        d[++k]=x%10;
        x/=10;
    }
    return dfs(k,0,1);
}

int main()
{
    int T,t=1;
    scanf("%d",&T);
    memset(dp,-1,sizeof(dp));
    while(T--)
    {
        ll a,b;
        scanf("%lld%lld",&a,&b);
        ll ans=solve(b)-solve(a-1);
        printf("Case #%d: %lld\n",t++,ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/chimchim04/article/details/88843179