【HDU3555】Bomb【数位DP】【记忆化搜索】

【题目链接】

赶紧学习一发数位DP。

听说记忆化搜索的写法比较通用,那么就不用for循环了。

/* Telekinetic Forest Guard */
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

const int maxn = 20;

int dig[maxn];
LL dp[maxn][3];

template <class numtype>
inline void read(numtype &x) {
	int f = 0; x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? 1 : 0;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	if(f) x = -x;
}

inline LL dfs(int pos, int state, bool limit) {
	if(pos == 0) return state == 2;
	if(!limit && ~dp[pos][state]) return dp[pos][state];

	int upb = limit ? dig[pos] : 9;
	LL res = 0;
	for(int i = 0; i <= upb; i++) {
		int s = state;
		if(state == 1) {
			if(i == 9) s = 2;
			else if(i != 4) s = 0;
		}
		else if(state == 0 && i == 4) s = 1;
		res += dfs(pos - 1, s, limit && i == dig[pos]);
	}

	if(!limit) dp[pos][state] = res;
	return res;
}

inline LL solve(LL x) {
	int top = 0;
	for(; x; x /= 10) dig[++top] = x % 10;
	return dfs(top, 0, 1);
}

int main() {
	int T; LL n;
	memset(dp, -1, sizeof(dp));
	for(read(T); T; T--) {
		read(n);
		printf("%lld\n", solve(n));
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值