B - Permute to Minimize 解説 by en_translator
Basically, you need to rearrange the digits of the given integer in ascending order, but a modification is needed to avoid leading zeros.
The specific solution is as follows: let \(d\) be the smallest digit other than \(0\). Then it is optimal to bring \(d\) at the beginning, then rearrange the other digits in ascending order.
There are several approaches of the implementation. In the sample code, we adopt the probably most concise approach: first, sort the digits in ascending order, then scan the digits from the beginning, and once you find a non-zero digit, swap it with the first digit and finish. It may seems weird at a glance, but it is not difficult to assert why it works well, so we recommend you to think about it.
Sample code (C++):
#include <bits/stdc++.h>
using namespace std;
int main() {
string x;
cin >> x;
sort(x.begin(), x.end());
for (int i = 0; i < (int) x.size(); i++) {
if (x[i] > '0') {
swap(x[0], x[i]);
break;
}
}
cout << x << endl;
}
Sample code (Python) :
x = sorted(input())
for i in range(len(x)):
if x[i] > '0':
x[0], x[i] = x[i], x[0]
break
print(''.join(x))
投稿日時:
最終更新: