传送门
1.关键是找dp,其他就偏模板了
2.模板:
int a[N], cnt;
int dp[N1][N2][N3];
// dp[pos][x1][x2]
int dfs(int pos, int x1, int x2, int limit) {
if (pos == -1) return xxx; // xxx为0或1,表示以某个数为个位数是否满足
if (!limit && dp[pos][x1][x2] == -1) return dp[pos][x1][x2];
int res = 0;
int up = limit ? a[pos] : 9;
for (int i = 0; i <= 9; i++) {
res += dfs(cnt - 1, x1`, x2`, limit && (i == a[pos]));
}
if (!limit) dp[pos][x1][x2] = res;
return res;
}
int solve(int x) {
cnt = 0;
while (x) {
a[cnt++] = x % 10;
x /= 10;
}
int ini; //某个未知数
return dfs(cnt - 1, ini, ini, 1);
}
3.对于这一题,也没有去细细思考,只是很快把代码写出来了罢了,等把这一专题的题目都见过之后,再来细细思考。
题意:找出1~n有多少个数既含有13又能被13整除。(1<=n<=1e9)
题解:
1.参考自:HDU - 3652 B-number(数位dp详解)
2.
代码:
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
// #define int long long
// #define ll long long
#define pb push_back
#define dbg(x) cout << #x << "===" << x << endl
using namespace std;
const int N = 20 + 10;
const int MOD = 13;
int n, cnt, a[10 + 5];
int dp[10 + 5][13 + 5][3 + 5];
// sta,2:已经有13,0:前一位不是1,1:前一位是1
int gett(int sta, int i) {
if (sta == 2)
return 2;
else if (sta == 1) {
if (i == 3)
return 2;
else if (i == 1)
return 1;
else
return 0;
} else {
if (i == 1)
return 1;
else
return 0;
}
}
int dfs(int pos, int num, int sta, bool limit) {
if (pos == -1) return (num == 0) && (sta == 2);
if (!limit && dp[pos][num][sta] != -1) return dp[pos][num][sta];
int res = 0;
int up = limit ? a[pos] : 9;
for (int i = 0; i <= up; i++) {
res += dfs(pos - 1, (num * 10 + i) % MOD, gett(sta, i),
limit & (i == a[pos]));
}
if (!limit) dp[pos][num][sta] = res;
return res;
}
int solve(int x) {
// memset(dp, -1, sizeof(dp));
cnt = 0;
while (x) {
a[cnt++] = x % 10;
x /= 10;
}
return dfs(cnt - 1, 0, 0, 1);
}
signed main() {
memset(dp, -1, sizeof(dp));
while (cin >> n) {
int ans = solve(n);
cout << ans << endl;
}
return 0;
}