https://www.luogu.com.cn/problem/P1012
刚开始并没有想到字符串排序,想用整数一位一位比较,想了半天感觉太难了,然后想到了字符串排序,写完高兴怎么这么简单,结果一提交wa了一个点,一看原来32,321的组合最大是32321,而字符串排序的话321>32这就有问题了,于是修改了排序
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
string arr[21];
int cmp(string a, string b) {
int k = min(a.length(), b.length());
for (int i = 0; i < k; i++) {
if (a[i] != b[i])
return a > b;
}
string c = max(a, b);
string d = min(a, b);
for (int i = k; i < c.length(); i++) {
if (d[i - k] > c[i]) {
return a < b;
}
else if (d[i - k] < c[i]) {
return a > b;
}
}
return a > b;
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
int n;
cin >> n;
for (int i = 0; i < n; i++)cin >> arr[i];
sort(arr, arr + n,cmp);
for (int i = 0; i < n; i++)cout << arr[i];
cout << endl;
return 0;
}
对于超出的字符一个一个比较,这个方法可以过,但是有点烦,看题解又看到了大佬的巧妙方法
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
string arr[21];
int cmp(string a, string b) {
return a + b > b + a;//妙妙妙
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
int n;
cin >> n;
for (int i = 0; i < n; i++)cin >> arr[i];
sort(arr, arr + n,cmp);
for (int i = 0; i < n; i++)cout << arr[i];
cout << endl;
return 0;
}