1.首次接触数位DP,可以先了解一下它的形式,然后变刷题边思考其原理,最后刷完这个专题之后再总结提炼一下它的思想
2.(建议今后总结写在一个博客的最前面)
题意:
给一个数n(1<=n<=2^63-1),然后求出1~n中含有子数49的数的个数
题解:
1.参考的带佬博客hdu3555 Bomb (秒懂的数位dp)
2.
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#define int long long
#define pb push_back
#define dbg(x) cout << #x << "===" << x << endl
using namespace std;
const int N = 20 + 10; //数的位数
int n, dp[N][10];
int a[N], cnt;
void solve(int x) {
cnt = 0;
while (x) {
a[cnt++] = x % 10;
x /= 10;
}
}
int dfs(int pos, int pre, bool limit) {
if (pos == -1) return 1; //最后个位的数
if (!limit && dp[pos][pre] != -1) {
return dp[pos][pre];
}
int res = 0;
int up = limit ? a[pos] : 9;
for (int i = 0; i <= up; i++) {
if (pre == 4 && i == 9)
continue;
else
res += dfs(pos - 1, i, limit & (i == a[pos]));
}
if (!limit) dp[pos][pre] = res;
return res;
}
signed main() {
int T;
cin >> T;
while (T--) {
memset(dp, -1, sizeof(dp));
cin >> n;
int i, j;
solve(n);
int ans = n - dfs(cnt - 1, 0, 1) + 1;
cout << ans << endl;
}
return 0;
}