cunzai_zsy0531

关注我

P4127 [AHOI2009]同类分布 题解

题面

罕见的数位dp好题。

首先感觉这个题想数位dp有点困难,很多东西都在变。注意到每个数位数字和其实最大也才一百多,考虑枚举这个和,统计被这个和整除且数位和等于这个和的数的个数就完事了。

点击查看代码
#include<iostream>
#include<cstdio>
#include<cstring>
typedef long long ll;
int a[20],Tmp;
ll f[20][170][170];
ll dfs(int len,int rest,int sum,bool flag){
	if(!len) return sum==Tmp&&!rest;
	if(!flag&&f[len][rest][sum]!=-1) return f[len][rest][sum];
	int up=(flag?a[len]:9);ll res=0;
	for(int i=0;i<=up;++i) res+=dfs(len-1,((rest<<3)+(rest<<1)+i)%Tmp,sum+i,flag&&i==up);
	if(!flag) f[len][rest][sum]=res;
	return res;
}
inline ll calc(ll x){
	if(!x) return 0;
	memset(f,-1,sizeof f);
	int len=0;while(x) a[++len]=(x%10),x/=10;
	return dfs(len,0,0,1);
}
int main(){
	ll l,r,ans=0;scanf("%lld%lld",&l,&r);
	for(int i=1;i<=162;++i) Tmp=i,ans+=calc(r)-calc(l-1);
	printf("%lld\n",ans);
	return 0;
}
posted @ 2022-05-20 11:54  cunzai_zsy0531  阅读(22)  评论(0编辑  收藏  举报