Files
python/TangDou/CSP-J/AcWingTraining/MaiChePai_2.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

49 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
string s, ans;
int n, k;
int mi = 0x3f3f3f3f;
int main() {
cin >> n >> k >> s;
for (int i = 0; i < 10; i++) {
int r = k, sum = 0;
string sAfter = s;
// 数字等于目标数字i
for (int t = 0; t < n; t++)
if (r && sAfter[t] - '0' == i) r--;
// 从左到右,找到比i大的数字,改小,修改为i
for (int j = 1; j < 10; j++) {
for (int t = 0; t < n; t++) {
if (r && sAfter[t] - '0' == i + j) {
r--; // 次数-1
sum += j; // 代价
sAfter[t] = i + '0'; // 修改后
}
}
// 从右往左,找到比i小的数字,改大,修改为i
for (int t = n - 1; t >= 0; t--) {
if (r && sAfter[t] - '0' == i - j) {
r--;
sum += j;
sAfter[t] = i + '0';
}
}
}
if (sum < mi) {
mi = sum;
ans = sAfter;
} else if (sum == mi)
ans = min(ans, sAfter);
}
cout << mi << endl;
cout << ans << endl;
return 0;
}