算法模版 动态规划

动态规划

矩阵加速

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <bits/stdc++.h>
using namespace std;

using i64 = long long;
using u64 = unsigned long long;
using u32 = unsigned;
using u128 = unsigned __int128;

constexpr int mod = 1e9 + 7;
struct Matrix {
vector<vector<i64>> a;
Matrix() { a.assign(3, vector<i64>(3)); }
Matrix operator*(const Matrix b) const {
Matrix res;
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 2; j++) {
for (int k = 1; k <= 2; k++) {
res.a[i][j] = (res.a[i][j] + a[i][k] * b.a[k][j]) % mod;
}
}
}
return res;
}
void inita() { a[1][1] = a[1][2] = 1; }
void initb() { a[1][1] = a[2][1] = a[1][2] = 1; }
};

Matrix qpow(Matrix a, i64 b) {
Matrix res;
for (int i = 1; i <= 2; i++) {
res.a[i][i] = 1;
}
while (b) {
if (b % 2 == 1) {
res = res * a;
}
a = a * a;
b /= 2;
}
return res;
}

void solve() {
i64 n;
cin >> n;
if (n <= 2) {
cout << 1 << "\n";
return;
}
Matrix a, b;
a.inita(), b.initb();
a = a * qpow(b, n - 2);
cout << a.a[1][1] << "\n";
}

signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t = 1;
// cin >> t;
while (t--) {
solve();
}
return 0;
}

数位 dp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <bits/stdc++.h>
using namespace std;
#define int long long

int dp[10][2];
int n, m, sz;
int c[10];
int dfs(int pos, bool sta, bool limit) {
int ans = 0;
if (pos == sz + 1) {
return 1;
}
if (!limit && dp[pos][sta] != -1) {
return dp[pos][sta];
}
int up = limit ? c[pos] : 9;
for (int i = 0; i <= up; i++) {
if (sta && i == 2) {
continue;
}
if (i == 4) {
continue;
}
ans += dfs(pos + 1, i == 6, limit && i == up);
}
if (!limit) {
dp[pos][sta] = ans;
}
return ans;
}

void solve() {
while (true) {
cin >> n >> m;
if (n == 0 && m == 0) {
break;
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 2; j++) {
dp[i][j] = -1;
}
}
string s = to_string(m);
sz = s.size();
s = " " + s;
for (int i = 1; i <= sz; i++) {
c[i] = s[i] - '0';
}
int ans = dfs(1, false, true);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 2; j++) {
dp[i][j] = -1;
}
}
s = to_string(n - 1);
sz = s.size();
s = " " + s;
for (int i = 1; i <= sz; i++) {
c[i] = s[i] - '0';
}
ans -= dfs(1, false, true);
cout << ans << "\n";
}
}

signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t = 1;
// cin >> t;
while (t--) {
solve();
}
return 0;
}