赶紧学习一发数位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;
}
本文详细介绍了数位DP的概念与记忆化搜索在解决复杂数位问题中的应用,通过实例演示如何高效地使用这些算法进行问题求解。

889

被折叠的 条评论
为什么被折叠?



