把数字当字符串,按 a+b > b+a 降序排序后拼接,即得最大整数。
OJ: roj
题目 ID: 20003
难度:普及-
标签:贪心排序字符串python
创建: 2026-10-02 19:16
更新: 2026-10-06 02:11
题目描述
给定
输入:第一行
样例:
思路
对任意两数
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-10-02 19:18
# update_at: 2026-10-04 10:36
import sys
from functools import cmp_to_key
def bigger_first(a: str, b: str) -> int:
"""拼接比较器:a 放在 b 前拼出的数更大时返回负数,让 sort 产出最大拼接。"""
ab, ba = a + b, b + a
if ab > ba:
return -1
return 1 if ab < ba else 0
def solve() -> None:
data = iter(sys.stdin.read().split())
n = int(next(data)) # 数字个数,n < 20
nums = [next(data) for _ in range(n)] # 保留字符串:拼接按位比较,转 int 反而丢掉顺序信息
nums.sort(key=cmp_to_key(bigger_first)) # 比较器等价于键 x/(10^len-1) 降序,全序保证贪心最优
print(''.join(nums))
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-06 02:11
* update_at: 2026-10-06 02:11
*/
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAXN = 25;
string a[MAXN]; // 每个数字保留为字符串,方便拼接比较
// 比较器:a 放在 b 前面拼出的数更大时返回 true,用于按最大拼接排序
bool cmp(const string &a, const string &b) {
return a + b > b + a;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
sort(a, a + n, cmp); // 按拼接后的字典序降序排列
for (int i = 0; i < n; ++i) {
cout << a[i];
}
cout << '\n';
return 0;
}