-
Notifications
You must be signed in to change notification settings - Fork 0
/
C.cpp
80 lines (64 loc) · 1.79 KB
/
C.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
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll l, r, minDiff;
int dp[20][2][2]; // index, greater than left, smaller than right
ll helper(int idx, int greaterThanLeft, int smallerThanRight, int n, int maxVal, int minVal, string &curr, string &left, string &right, bool &found)
{
if (idx == n) {
found = true;
return true;
}
if (dp[idx][greaterThanLeft][smallerThanRight] != -1) {
return dp[idx][greaterThanLeft][smallerThanRight];
}
for (int i = minVal; i <= maxVal; i++) {
if ((greaterThanLeft || i >= left[idx] - '0') && (smallerThanRight || i <= right[idx] - '0')) {
curr.push_back(char('0' + i));
helper(idx + 1, greaterThanLeft || i > left[idx] - '0', smallerThanRight || i < right[idx] - '0', n, maxVal, minVal, curr, left, right, found);
if (found) return true;
curr.pop_back();
}
}
return dp[idx][greaterThanLeft][smallerThanRight] = false;
}
void solve()
{
cin >> l >> r;
string left = to_string(l), right = to_string(r);
if ((int)left.size() != (int)right.size()) {
string ans((int)left.size(), '9');
cout << ans << '\n';
return;
}
string ans = left;
minDiff = 100;
for (int maxVal = 1; maxVal <= 9; maxVal++) {
for (int minVal = 0; minVal <= maxVal; minVal++) {
if (maxVal - minVal > minDiff) continue;
memset(dp, -1, sizeof(dp));
string curr;
bool found = false;
helper(0, 0, 0, (int)left.size(), maxVal, minVal, curr, left, right, found);
if (found) {
ans = curr;
minDiff = maxVal - minVal;
}
}
}
cout << ans << '\n';
}
int main()
{
#ifndef ONLINE_JUDGE
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
//freopen("Error.txt", "w", stderr);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL), cout.tie(NULL);
int t = 1;
cin >> t;
while (t--) solve();
return 0;
}