#include <bits/stdc++.h>
using namespace std;
string bc, bj;
long long d = LLONG_MAX;
void b(int pos, string& C, string& J, bool cr, bool jr) {
if (pos == C.size()) {
long long numC = stoll(C);
long long numJ = stoll(J);
long long diff = abs(numC - numJ);
if (diff < d || (diff == d && numC < stoll(bc)) ||(diff == d && numC == stoll(bc) && numJ < stoll(bj))) {
d = diff;
bc = C;
bj = J;
}
return;
}
char& c = C[pos];
char& j = J[pos];
char oc = c, oj = j;
if (c != '?' && j != '?') {
bool ncr = cr || (c > j && !jr);
bool njr = jr || (j > c && !cr);
b(pos+1, C, J, ncr, njr);
}
else if (c == '?' && j == '?') {
if (cr) {
c = '0'; j = '9';
b(pos+1, C, J, true, jr);
}
else if (jr) {
c = '9'; j = '0';
b(pos+1, C, J, cr, true);
}
else {
c = j = '0';
b(pos+1, C, J, false, false);
c = '0'; j = '1';
b(pos+1, C, J, false, true);
c = '1'; j = '0';
b(pos+1, C, J, true, false);
}
}
else if (c == '?') {
if (cr) {
c = '0';
b(pos+1, C, J, true, jr);
}
else if (jr) {
c = '9';
b(pos+1, C, J, cr, true);
}
else {
c = j;
b(pos+1, C, J, false, false);
if (j > '0') {
c = j - 1;
b(pos+1, C, J, false, true);
}
if (j < '9') {
c = j + 1;
b(pos+1, C, J, true, false);
}
}
}
else {
if (cr) {
j = '0';
b(pos+1, C, J, true, false);
}
else if (jr) {
j = '9';
b(pos+1, C, J, cr, true);
}
else {
j = c;
b(pos+1, C, J, false, false);
if (c > '0') {
j = c - 1;
b(pos+1, C, J, true, false);
}
if (c < '9') {
j = c + 1;
b(pos+1, C, J, false, true);
}
}
}
c = oc;
j = oj;
}
int main() {
int T;
cin >> T;
for (int t = 1; t <= T; ++t) {
string C, J;
cin >> C >> J;
bc = C;
bj = J;
d = LLONG_MAX;
b(0, C, J, false, false);
cout << "Case #" << t << ": " << bc << " " << bj << endl;
}
return 0;
}
我用的是贪心,全排列过了一个点,到 O(n) 的算法就全错了,dalao求调