uva 11361

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值