【1038 30 字符串和排序】 Recover the Smallest Number
传送门
题意
给定 \(n\) 个字符串数字片段 \(seg_{i}\),求出这些数字组合起来的最小数字
数据范围
\(n\leq 10^{4}\)
\(|seg_{i}|\leq 6\)
题解
- 只有作为数字开头的需要去除前导 \(0\),其余的不需要
- 单纯按照字典序排列后得到的不一定是数值最小的,合并以后长度相同,例如
32, 321和321, 32 - 字符串和进行排序,即 \(a+b<b+a\) ,最后第一个表示其它的任意数字串结合都是最小的,满足最小
Code
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; cin >> n;
vector<string> numbers(n);
for (auto& it : numbers) cin >> it;
sort(numbers.begin(), numbers.end(),
[](const string& a, const string& b) {
return a + b < b + a;
});
string s = "";
for (auto it : numbers) s += it;
while(s[0] == '0') s.erase(0, 1);
if (s.size() == 0) cout << '0';
else cout << s;
}

浙公网安备 33010602011771号