【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;
}


你可能感兴趣的:(【HDU3555】Bomb【数位DP】【记忆化搜索】)