uva 11361

来源:互联网 发布:在淘宝买东西怎么付钱 编辑:程序博客网 时间:2024/05/22 05:13
An integer is divisible by 3 if the sum of its digits is also divisible by 3. For example, 3702 is divisibleby 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.InputThe rst line of input is an integerT(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.OutputFor 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.SampleInput31 20 11 20 21 1000 4SampleOutput20564

分析:数位dp,思路是按照刘汝佳大白书上的,代码如下

#include <cstdio>#include <cstring>#include <cstdlib>#include <cmath>#include <vector>#include <queue>#include <stack>#include <map>#include <set>#include <string>#include <algorithm>using namespace std;const int ten[] = {1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000};int f[11][90][90];vector<int> v[2];int a,b,k;void dev(int n,int index){if (n == 0){v[index].push_back(0);return ;}while (n){v[index].push_back(n % 10);n /= 10;}}int fun(const int &index,int sum,int m,int pos){if (pos < 0) return 0;int ans = 0;if (pos == 0){for (int i = 0; i <= v[index][pos]; ++i){if ((sum + i) % k == 0 && (m * 10 + i) % k == 0){++ans;}}return ans;}for (int i = 0; i < v[index][pos]; ++i){ans += f[pos][(k - (sum + i) % k) % k][(k - (m * 10 + i) * ten[pos] % k) % k];}return ans + fun(index,sum + v[index][pos],(m * 10 + v[index][pos]),pos-1);}int main(){int T;scanf("%d",&T);while (T--){scanf("%d%d%d",&a,&b,&k);if (k > 81){printf("0\n");continue;}memset(f,0,sizeof(f));for (int i = 0; i < 10; ++i){f[1][i % k][i % k]++;}for (int i = 1; i <= 9; ++i){for (int m1 = 0; m1 < k; ++m1){for (int m2 = 0; m2 < k; ++m2){for (int x = 0; x < 10; ++x){f[i][m1][m2] += f[i-1][(m1-x%k+k)%k][(m2-ten[i-1]*x%k+k)%k];}}}}for (int i = 0; i < 2; ++i){v[i].clear();}dev(b,0);dev(a-1,1);printf("%d %d\n",fun(0,0,0,v[0].size()-1) , fun(1,0,0,v[1].size()-1));}return 0;}


0 0
原创粉丝点击