首页 > 代码库 > BZOJ 1833 数字计数(数位DP)

BZOJ 1833 数字计数(数位DP)

经典数位DP模板题。

 

技术分享
# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi acos(-1.0)
# define eps 1e-9
# define MOD 1024523
# define INF 1000000000
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<1,l,mid
# define rch p<<1|1,mid+1,r
# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
    int x=0,f=1;char ch=getchar();
    while(ch<0||ch>9){if(ch==-)f=-1;ch=getchar();}
    while(ch>=0&&ch<=9){x=x*10+ch-0;ch=getchar();}
    return x*f;
}
void Out(int a) {
    if(a<0) {putchar(-); a=-a;}
    if(a>=10) Out(a/10);
    putchar(a%10+0);
}
const int N=55;
//Code begin...

LL dp[10][15][10], p[15], d[15];
int wei[15];

LL dfs(int pos, int pre, int limit, int lead, int x){
    if (pos==0) return pre==x;
    if (!limit&&!lead&&~dp[x][pos][pre]) return dp[x][pos][pre];
    int up=limit?wei[pos]:9;
    LL res=0;
    if (x||!lead) {
        if (pre==x) {
            if (limit) res+=d[pos]+1;
            else res+=p[pos];
        }
    }
    FOR(i,0,up) res+=dfs(pos-1,i,limit&&i==wei[pos],lead&&i==0,x);
    if (!limit&&!lead) dp[x][pos][pre]=res;
    return res;
}
LL sol(int x, LL val){
    int pos=0;
    while (val) wei[++pos]=val%10, val/=10, d[pos]=wei[pos]*p[pos-1]+d[pos-1];
    return dfs(pos,0,1,1,x);
}
int main ()
{
    LL a, b;
    mem(dp,-1);
    p[0]=1; FOR(i,1,15) p[i]=p[i-1]*10;
    scanf("%lld%lld",&a,&b);
    FO(i,0,10) printf(i==0?"%lld":" %lld",sol(i,b)-sol(i,a-1));
    putchar(\n);
    return 0;
}
View Code

 

BZOJ 1833 数字计数(数位DP)