标签:
An integer is divisible by 3 if the sum of its digits is also divisible by 3. For example, 3702 is divisible by 3 and 12(3+7+0+2) is also divisible by 3. This property also holds for the integer 9.
In this problem, we will investigate this property for other integers.
Input
The first line of input is an integer T(T<100) that indicates the number of test cases. Each case is a line containing 3 positive integers A, B and K. 1 <= A <= B < 2^31 and 0<K<10000.
Output
For each case, output the number of integers in the range [A, B] which is divisible by K and the sum of its digits is also divisible by K.
Sample Input |
Output for Sample Input |
3 1 20 1 1 20 2 1 1000 4 |
20 5 64 |
数位DP基础版,没什么好说的。
但是因为A,B<=2^31所以,A,B不会超过10位,所以各位数字相加之和不会超过90;
所以如果k大于90的时候直接输出0,因为这种情况不会mod k为0.
注意到为0时符合条件。
#include<cstdio> #include<cstring> #include<algorithm> #include<vector> #include<string> #include<iostream> #include<queue> #include<cmath> #include<map> #include<stack> #include<bitset> using namespace std; #define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i ) #define REP( i , n ) for ( int i = 0 ; i < n ; ++ i ) #define CLEAR( a , x ) memset ( a , x , sizeof a ) typedef long long LL; typedef pair<int,int>pil; const int INF = 0x3f3f3f3f; int num[20]; int t,k; LL a,b; LL dp[20][100][100]; LL dfs(int pos,int pre,int sum,int flag) { if(pos==0) return pre==0&&sum%k==0; if(!flag&&dp[pos][pre][sum]!=-1) return dp[pos][pre][sum]; int ed=flag?num[pos]:9; LL res=0; for(int i=0;i<=ed;i++) res+=dfs(pos-1,(pre*10+i)%k,sum+i,flag&&(i==ed)); if(!flag) dp[pos][pre][sum]=res; return res; } LL solve(LL x) { int pos=0; while(x) { num[++pos]=x%10; x/=10; } return dfs(pos,0,0,1); } int main() { scanf("%d",&t); while(t--) { scanf("%lld%lld%d",&a,&b,&k); if(k>90) { puts("0"); continue; } CLEAR(dp,-1); LL ans=solve(b)-solve(a-1); printf("%lld\n",ans); } return 0; } /* 3 1 20 1 1 20 2 1 1000 4 */
UVA 11361 Investigating Div-Sum Property(数位DP)
标签:
原文地址:http://blog.csdn.net/u013582254/article/details/45122715