解法一:字符串比较

最优解不是纯粹的字典序,要将两个字符串的前后两种连接方式进行比较来决定谁排在前面。
注意全部为0的情况。

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. vector<string> nums;
  4. bool flag = false;
  5. bool cmp(string o1, string o2) {
  6. return o1 + o2 < o2 + o1;
  7. }
  8. void print(string &str) {
  9. int i;
  10. for (i = 0; i < str.size(); ++i) {
  11. if (str[i] != '0') {
  12. break;
  13. }
  14. }
  15. for (; i < str.size(); ++i) {
  16. cout << str[i];
  17. flag = true;
  18. }
  19. }
  20. int main() {
  21. int N;
  22. cin >> N;
  23. string num;
  24. for (int i = 0; i < N; ++i) {
  25. cin >> num;
  26. nums.emplace_back(num);
  27. }
  28. sort(nums.begin(), nums.end(), cmp);
  29. for (auto &it:nums) {
  30. if (!flag) {
  31. print(it);
  32. } else {
  33. cout << it;
  34. }
  35. }
  36. if (!flag) {
  37. cout << "0\n";
  38. } else {
  39. cout << '\n';
  40. }
  41. }