1. 程式人生 > >[AHOI2009]同類分佈 數位dp

[AHOI2009]同類分佈 數位dp

題目描述

給出兩個數a,b,求出[a,b]中各位數字之和能整除原數的數的個數。

輸入輸出格式

輸入格式:

 

一行,兩個整數a和b

 

輸出格式:

 

一個整數,表示答案

 

輸入輸出樣例

輸入樣例#1: 複製

10 19

輸出樣例#1: 複製

3

明顯的數位dp;

我們要求的是每位數字和可以被原數整除的數個數;

但範圍達到10^{18},陣列範圍肯定開不下;

怎麼辦?考慮模數;

我們列舉模數,如果此時的總和可以整除模數且當前的模數就是各位數字之和,那麼答案就+1;

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<bitset>
#include<ctime>
#include<deque>
#include<stack>
#include<functional>
#include<sstream>
//#include<cctype>
//#pragma GCC optimize("O3")
using namespace std;
#define maxn 100005
#define inf 0x3f3f3f3f
#define INF 999999999999999
#define rdint(x) scanf("%d",&x)
#define rdllt(x) scanf("%lld",&x)
#define rdult(x) scanf("%lu",&x)
#define rdlf(x) scanf("%lf",&x)
#define rdstr(x) scanf("%s",x)
typedef long long  ll;
typedef unsigned long long ull;
typedef unsigned int U;
#define ms(x) memset((x),0,sizeof(x))
const long long int mod = 1e9 + 7;
#define Mod 100003
#define sq(x) (x)*(x)
#define eps 1e-3
typedef pair<int, int> pii;
#define pi acos(-1.0)
const int N = 1005;
#define REP(i,n) for(int i=0;i<(n);i++)
inline ll rd() {
	ll x = 0;
	char c = getchar();
	bool f = false;
	while (!isdigit(c)) {
		if (c == '-') f = true;
		c = getchar();
	}
	while (isdigit(c)) {
		x = (x << 1) + (x << 3) + (c ^ 48);
		c = getchar();
	}
	return f ? -x : x;
}

ll gcd(ll a, ll b) {
	return b == 0 ? a : gcd(b, a%b);
}
ll sqr(ll x) { return x * x; }

/*ll ans;
ll exgcd(ll a, ll b, ll &x, ll &y) {
	if (!b) {
		x = 1; y = 0; return a;
	}
	ans = exgcd(b, a%b, x, y);
	ll t = x; x = y; y = t - a / b * y;
	return ans;
}
*/

ll dp[30][200][200];
int a[30];
ll sum;
ll MOD;

ll dfs(int pos, int lead, int limit, ll sum, ll mod) {
	ll ans = 0;
	if (pos == 0 && lead) {
		if (sum == MOD && mod == 0)return 1;
		return 0;
	}
	if (limit == 0 && lead&&dp[pos][sum][mod] != -1)return dp[pos][sum][mod];
	int up = limit ? a[pos] : 9;
	for (int i = 0; i <= up; i++) {
		ans += dfs(pos - 1, lead || i, limit && (i == up), sum + i, (mod * 10 + i) % MOD);
	}
	if (lead&&limit == 0)dp[pos][sum][mod] = ans;
	return ans;
}

ll sol(ll x) {
	int pos = 0;
	while (x) {
		a[++pos] = x % 10; x /= 10;
	}
	ll ans = 0;
	for (MOD = 1; MOD <= 9 * pos; MOD++) {
		memset(dp, -1, sizeof(dp));
		ans += dfs(pos, 1, 1, 0, 0);
	}
	return ans;
}

int main()
{
	//ios::sync_with_stdio(false);
	ll a, b; rdllt(a); rdllt(b);
	cout << sol(b) - sol(a - 1) << endl;
    return 0;
}