HDU3555:Bomb

数位dp。。。要求不含49。dp[i][0]表示不含,dp[i][1]表示i位为6,dp[i][2]表示含。(long long 啊最近总是被long long坑啊!!!

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define rep(i,s,t) for(int i=s;i<=t;i++)
#define dwn(i,s,t) for(int i=s;i>=t;i--)
#define clr(x,c) memset(x,c,sizeof(x))
#define ll long long
ll read(){
	ll x=0;char c=getchar();
	while(!isdigit(c)) c=getchar();
	while(isdigit(c)) x=x*10+c-'0',c=getchar();
	return x;
}
const int nmax=25;
ll dp[nmax][3];int bit[nmax];
void init(){
	clr(dp,0);dp[0][0]=1;
	rep(i,1,20) {
		dp[i][0]=dp[i-1][0]*10-dp[i-1][1];
		dp[i][1]=dp[i-1][0];
		dp[i][2]=dp[i-1][2]*10+dp[i-1][1];
	}
}
ll work(ll x){
	ll tmp=x,ans=0;int cnt=0;
	while(tmp) bit[++cnt]=tmp%10,tmp/=10;
	bit[cnt+1]=0;bool flag=false;
	dwn(i,cnt,1){
		ans+=bit[i]*dp[i-1][2];
		if(flag) ans+=bit[i]*dp[i-1][0];
		else if(bit[i]>4) ans+=dp[i-1][1];
		if(bit[i+1]==4&&bit[i]==9) flag=true;
	}
	return ans;
}
int main(){
	ll cas=read();init();
	while(cas--){
		ll tmp=read();
		printf("%lld\n",work(tmp+1));
	}
	return 0;
}

 upd:记忆化搜索版。代码量比较少。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define rep(i,s,t) for(int i=s;i<=t;i++)
#define dwn(i,s,t) for(int i=s;i>=t;i--)
#define ll long long
#define clr(x,c) memset(x,c,sizeof(x))
ll read(){
	ll x=0;char c=getchar();bool f=true;
	while(!isdigit(c)){
		if(c=='-') f=false;c=getchar();
	}
	while(isdigit(c)) x=x*10+c-'0',c=getchar();
	return f?x:-x;
}
ll dp[25][3];
int cnt,bit[25];
ll work(int cur,int op,bool flag){
	if(!cur) return op==0;
	if(!flag&&dp[cur][op]!=-1) return dp[cur][op];
	ll ans=0;int end=flag?bit[cur]:9;
	rep(i,0,end){
		int tmp=op;
		if(op==1&&i==9) tmp=0;
		if(op==2&&i==4) tmp=1;
		if(op==1&&i!=9&&i!=4) tmp=2;
		ans+=work(cur-1,tmp,flag&&i==end);
	}
	if(!flag) dp[cur][op]=ans;
	return ans;
}
void getbit(ll x){
	cnt=0;
	while(x) bit[++cnt]=x%10,x/=10;
}
int main(){
	ll cas=read();
	while(cas--){
		clr(dp,-1);
		ll n=read();getbit(n);
		printf("%lld\n",work(cnt,2,1));
	}
	return 0;
}

  

posted @ 2016-07-30 10:18  BBChq  阅读(137)  评论(0编辑  收藏  举报