-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnbn.cpp
110 lines (89 loc) · 2.56 KB
/
nbn.cpp
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
const int INF = 0x3f3f3f3f;
void solve() {
string n;
int k;
int n_i;
cin >> n;
cin >> k;
n_i = stoi(n);
if (k == 1) {
int lo = n[0];
string ans;
ans = "";
for (char c : n) {
ans += lo;
}
if(stoi(ans) < n_i) {
ans = "";
for (char c : n) {
ans += lo + 1;
}
}
cout << ans << "\n";
return;
}
bool vis[10];
memset(vis, false, sizeof(vis));
for (char c : n) {
vis[c - '0'] = true;
}
int cnt = 0;
for (int i = 0; i <= 9; i++) {
cnt += vis[i];
}
if (cnt <= 2) {
cout << n << "\n";
return;
}
// x, y, digit, goneUp?
int dp[10][10][10][2];
memset(dp, INF, sizeof(dp));
for (int i = 0; i <= 9; i++) {
for (int j = 0; j <= 9; j++) {
dp[i][j][0][false] = n_i;
}
}
for (int i = 0; i <= 9; i++) {
for (int j = 0; j <= 9; j++) {
for (int d = 0; d < n.length(); d++) {
for (int up = 0; up < 2; up++) {
if (dp[i][j][d][up] == INF) continue;
int a = n[d] - '0';
//cout << (i - a) * (int)pow(10, n.length() - d - 1) << endl;
if (up) {
dp[i][j][d + 1][up] = min(dp[i][j][d + 1][up], dp[i][j][d][up] + (i - a) * (int)pow(10, n.length() - d - 1));
dp[i][j][d + 1][up] = min(dp[i][j][d + 1][up], dp[i][j][d][up] + (j - a) * (int)pow(10, n.length() - d - 1));
} else {
if (i >= a) dp[i][j][d + 1][true ? i > a : false] = min(dp[i][j][d + 1][true ? i > a : false], dp[i][j][d][up] + (i - a) * (int)pow(10, n.length() - d - 1));
if (j >= a) dp[i][j][d + 1][true ? j > a : false] = min(dp[i][j][d + 1][true ? j > a : false], dp[i][j][d][up] + (j - a) * (int)pow(10, n.length() - d - 1));
}
}
}
}
}
int best = INF;
for (int i = 0; i <= 9; i++) {
for (int j = 0; j <= 9; j++) {
//cout << i << " " << j << endl;
//cout << endl;
best = min(best, dp[i][j][n.length()][true]);
}
}
cout << best << "\n";
return;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}