您的位置:首页 > 其它

uva 11361

2016-01-10 15:39 316 查看
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 rst 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.
SampleInput
3
1 20 1
1 20 2
1 1000 4
SampleOutput
20
5
64


分析:数位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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: