Good Numbers
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 5316 Accepted Submission(s): 1689
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.
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).
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: 1HintThe answer maybe very large, we recommend you to use long long instead of int.
题意:找出A~B中各个数位的和能被10整除的数的个数;
数据范围是1e18,所以直接暴力肯定会超时,我们发现该题同样是与数位的运算有关,所以很明显是数位DP;
数位DP其实是有模板的,上一篇DP入门题已经提到过;一般情况下函数中有三个参数(int per, int state, bool fp)per表示数的第几位,state表示状态,fp则用来限制数位的取值;在本题中一共有10个状态,因为模10有十种结果嘛;
好下面看一下代码:
#include <iostream>
#include <cstring>
using namespace std;
long long dp[25][15], digit[25];
long long dfs(int per, int state, bool fp){
if(per==0) //当per为零时表示这个数我已经枚举完,此时如果状态为零即模10为零,结果就加1;
return state==0;
if(!fp && dp[per][state]!=-1)
return dp[per][state];
long long ret=0;
int maxfp = fp? digit[per] : 9;
for(int i=0; i<=maxfp; i++){
int _state=(state+i)%10; //注意这里一定要定义一个新的变量来储存新的状态,因为这里是递归,不定义新变量就会改变原先的值;
ret+=dfs(per-1, _state, i==maxfp && fp);
}
if(!fp)dp[per][state]=ret;
return ret;
}
long long Cnt(long long n){
int per=0;
memset(dp, -1, sizeof(dp));
memset(digit, 0, sizeof(digit));
while(n){
digit[++per]=n%10;
n/=10;
}
return dfs(per, 0, true);
}
int main(){
int T, X;
cin >> T;
X=0;
while(T--){
X++;
long long A, B;
cin >> A >> B;
cout << "Case #" << X << ": " << Cnt(B)-Cnt(A-1) << endl;
}
return 0;
}