数位DP学习笔记
CSP 前夕,写博客增长 RP。
数位 DP 是什么,怎么做
数位 DP 可以用于统计一个区间
考虑将询问差分,变成查询
DP 的过程类似于计数 DP,但是计数 DP 不用考虑一次拼起来的数要小于等于上界,数位 DP 相比计数 DP 值域较小,状态设计比较暴力。
数位 DP 有记忆化搜索和递推写法,个人感觉记忆化搜索比较好写,故本文将用记忆化搜索实现。
数位 DP 例题
不要 62
不吉利的数字为所有含有
4 或62 的号码。 求区间[L,R] 中有多少的数是吉利的数
记
转移直接搜索就可以,代码如下:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||'9'<ch){if(ch=='-')f=-1;ch=getchar();}
while('0'<=ch&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return f*x;
}
ll L,R;
ll f[15][15],a[15],m=0;
ll dfs(ll i, ll pre, bool flag){
if(i==0)return 1;// 只有一个数就返回一个答案
if(flag==0&&f[i][pre]!=-1)return f[i][pre];// 记忆化,要求当前没有顶着上界且答案已经统计过
ll sum=0,lim=(flag?a[i]:9);// 第 i 位的上界,如果是卡着上界上界就是 a[i],否则就是 9
for(ll x=0;x<=lim;x++){
if(x==4)continue;if(pre==6&&x==2)continue;// 非法情况
sum+=dfs(i-1,x,(flag==1&&x==lim));// 累积答案
}if(flag==0)f[i][pre]=sum;// 没有顶着上界才能记录
return sum;
}
ll calc(ll x){
if(!x)return 1;m=0;
while(x)a[++m]=x%10,x/=10;// 转成数组更好处理
return dfs(m,0,1);
}
int main(){
memset(f,-1,sizeof(f));
while(1){
L=read(),R=read();
if(L==0&&R==0)break;
printf("%lld\n",calc(R)-calc(L-1));// 差分即可
// printf("%lld %lld\n",calc(L-1),calc(R));
}
return 0;
}
P2657 [SCOI2009] windy 数
不含前导零且相邻两个数字之差至少为
2 的正整数被称为 windy 数。 求[L,R] 中 windy 数的数量。
考虑计数 DP,记
代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||'9'<ch){if(ch=='-')f=-1;ch=getchar();}
while('0'<=ch&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return f*x;
}
ll L,R;
ll m,a[15],f[15][15];
ll dfs(ll i,ll pre, bool flag,bool zero){
if(i==0)return 1;if(flag==0&&zero==0&&f[i][pre]!=-1)return f[i][pre];
ll sum=0,lim=(flag?a[i]:9),tmp;
for(ll x=0;x<=lim;x++)if(abs(pre-x)>=2){
tmp=x;if(zero&&x==0)tmp=-114;
sum+=dfs(i-1,tmp,(flag&&x==lim),(tmp==-114));
}if(!flag&&!zero)f[i][pre]=sum;return sum;
}
ll calc(ll x){
if(!x)return 1;m=0;
while(x){a[++m]=x%10,x/=10;}
return dfs(m,-114,1,1);
}
int main(){
memset(f,-1,sizeof(f));
L=read(),R=read();
printf("%lld",calc(R)-calc(L-1));
return 0;
}
P1831 杠杆数
计数 DP,假设支点在第
感性理解一下只有一个数只有一个支点。\
枚举支点位置,记
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||'9'<ch){if(ch=='-')f=-1;ch=getchar();}
while('0'<=ch&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return f*x;
}
const ll O = 0;
ll L,R,p;
ll a[25],m,f[25][2505][25];
ll dfs(ll i, ll sum, bool flag){
if(i==0)return sum==O;if(sum<O)return 0;
if(!flag&&f[i][sum][p]!=-1)return f[i][sum][p];
ll ans=0,lim=(flag?a[i]:9);
for(ll x=0;x<=lim;x++)ans+=dfs(i-1,sum+(i-p)*x,(x==lim&&flag));
if(!flag)f[i][sum][p]=ans;return ans;
}
ll calc(ll x){
if(!x)return 1;ll ans=0;
m=0;while(x)a[++m]=x%10,x/=10;
for(p=1;p<=m;p++)ans+=dfs(m,O,1);
return ans-m+1;
}
int main(){
L=read(),R=read();memset(f,-1,sizeof(f));
printf("%lld",calc(R)-calc(L-1));
return 0;
}