您的位置:首页 > 编程语言 > Go语言

HDU 4722 Good Numbers(数位DP)

2016-07-20 16:47 483 查看
原题地址:传送门  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


[align=left]Problem Description[/align]
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.
 

[align=left]Input[/align]
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).
 

[align=left]Output[/align]
For test case X, output "Case #X: " first, then output the number of good numbers in a single line.
 

[align=left]Sample Input[/align]

2
1 10
1 20

 

[align=left]Sample Output[/align]
Case #1: 0
Case #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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息