您的位置:首页 > 其它

Codeforces 55D Beautiful Number (数位统计)

2013-06-17 21:54 337 查看
把数位dp写成记忆化搜索的形式,方法很赞,代码量少了很多。

下面为转载内容:

   a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits.
问一个区间内[l,r]有多少个Beautiful数字
范围9*10^18

数位统计问题,构造状态也挺难的,我想不出,我的思维局限在用递推去初始化状态,而这里的状态定义也比较难
跟pre的具体数字有关

问了NotOnlySuccess的,豁然开朗 Orz

一个数字要被它的所有非零位整除,即被他们的LCM整除,可以存已有数字的Mask,但更好的方法是存它们的LCM{digit[i]}
int MOD = LCM{1,2,

const int MOD = 2520;

LL dp[21][MOD][50];
int digit[21];
int indx[MOD+5];

void init() {
int num = 0;
for(int i = 1; i <= MOD; ++i) {
if(MOD%i == 0) indx[i] = num++;
}
CL(dp, -1);
}

LL gcd(LL a, LL b) {
return b == 0 ? a : gcd(b, a%b);
}

LL lcm(LL a, LL b) {
return a/gcd(a, b)*b;
}

LL dfs(int pos, int presum, int prelcm, bool edge) {
if(pos == -1)    return presum%prelcm == 0;
if(!edge && dp[pos][presum][indx[prelcm]] != -1)
return dp[pos][presum][indx[prelcm]];
int ed = edge ? digit[pos] : 9;
LL ans = 0;
for(int i = 0; i <= ed; ++i) {
int nowlcm = prelcm;
int nowsum = (presum*10 + i)%MOD;
if(i)   nowlcm = lcm(prelcm, i);
ans += dfs(pos - 1, nowsum, nowlcm, edge && i == ed);
}
if(!edge)    dp[pos][presum][indx[prelcm]] = ans;
return ans;
}

LL cal(LL x) {
CL(digit, 0);
int pos = 0;
while(x) {
digit[pos++] = x%10;
x /= 10;
}
return dfs(pos - 1, 0, 1, 1);
}

int main() {
//Read();

init();
int T;
LL a, b;
cin >> T;
while(T--) {
cin >> a >> b;
cout << cal(b) - cal(a - 1) << endl;
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: