随手练——字符串按最小(大)字典序拼接

一般想到的,将所有字符串是按字典序从小到大依次排下去。

但其实是错的,比如 b , ba按这个思想排出来,是 bba,但其实最小的是bab,就要改一下比较策略了,改成拼接之后,比较谁小。

int cmp(string s1,string s2) {
    return s1 + s2 < s2 + s1;
}

 

https://www.luogu.org/problemnew/show/P1012

比如这个,给一堆数,拼出来一个最大的,比如321,32;会拼成32132,不是最大的,最大的是32321。

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;

bool cmp(string s1, string s2) {
    return s1 + s2 > s2 + s1;
}

int main() {
    int n;
    cin >> n;
    vector<string>v;
    while (n--) {
        string s;
        cin >> s;
        v.push_back(s);
    }
    sort(v.begin(), v.end(), cmp);
    for (int i = 0; i < v.size(); i++)cout << v[i];
    cout << endl;
    return 0;
}

 

posted @ 2019-02-08 11:09  czc1999  阅读(206)  评论(0编辑  收藏  举报