1. 程式人生 > >BZOJ P4521 [CQOI2016] 手機號碼【數位DP】

BZOJ P4521 [CQOI2016] 手機號碼【數位DP】

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
#define rep(i,x,y) for(ll i=(x);i<=(y);i++)
#define repl(i,x,y) for(ll i=(x);i<(y);i++)
#define repd(i,x,y) for(ll i=(x);i>=(y);i--)
using namespace std;

const ll N=15;
const ll Inf=1e18;

ll x,y,w[N],f[N][N][2][2][2][2][2];

inline ll read() {
	ll x=0;char ch=getchar();bool f=0;
	while(ch>'9'||ch<'0'){if(ch=='-')f=1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
	return f?-x:x;
}

void split(ll x) {
	w[0]=0;
	while(x) {
		w[++w[0]]=x%10;x/=10;
	}
	rep(i,1,w[0]/2) swap(w[i],w[w[0]+1-i]);
}

ll dp() {
	ll ans=0;
	f[0][10][0][0][0][0][1]=1;
	repl(i,0,w[0]) rep(j,0,10) rep(a,0,1) rep(b,0,1) rep(c,0,1) rep(d,0,1) rep(e,0,1) if(f[i][j][a][b][c][d][e]) rep(k,0,9) {
		ll aa,bb,cc,dd,ee;
		if(e&&k>w[i+1]) continue;
		
		if(k==j) aa=1; else aa=0;
		if(b) bb=b; else bb=(a+aa==2);
		if(c) cc=c; else cc=(k==4);
		if(d) dd=d; else dd=(k==8);
		
		if(cc+dd==2) continue;
		
		if(e&&(k==w[i+1])) ee=1; else ee=0;
		
		f[i+1][k][aa][bb][cc][dd][ee]+=f[i][j][a][b][c][d][e];
	}

	rep(j,0,9) rep(a,0,1) rep(c,0,1) rep(d,0,1) {
		if(c+d<2) ans+=f[w[0]][j][a][1][c][d][0];
		else break;
	}	

	return ans;
}

ll calc(ll x) {
	memset(f,0,sizeof(f));split(x);
	return dp();
}

int main() {
	x=read(),y=read();
	
	printf("%lld",calc(y+1)-calc(x));

	return 0;
}