洛谷 P1012拼数(sort对string的用法)

mac2024-10-07  54

这个题有点太水了,先来看一下题解,主要是学到了cmp函数中对于string排序的一种写法

#include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <algorithm> //ios::sync_with_stdio(false); typedef long long LL; using namespace std; vector <string> vec; bool cmp(string a, string b) { return a+b > b+a; // 假设 a=321, b=32, 默认 a > b 排序后 32132 // 而 a+b > b+a 排序后 32321 // 明显第二个方法排序后值更大 } int main() { int n; string s; cin >> n; for(int i = 0; i < n; i++) { cin >> s; vec.push_back(s); } sort(vec.begin(), vec.end(), cmp); for(int i = 0; i < n; i++) { cout << vec[i]; } return 0; }

测试了一下输出 排序后的字符串最小值:

6 321 32 407 135 13 217 13 135 217 321 32 407 13 135 217 32 321 407 32132 (return a+b < b+a) 32321 (return a < b)

二者组合起来,明显第一个更小一点。

最新回复(0)