sort
算法竞赛中的每一毫秒都是珍贵的
而 sort 的不恰当使用会浪费很多额外的时间,尤其是在数据量较大的时候。
平时阅读题解的时候发现很多大佬都会这样子写 sort :
sort(a + 1, a + 1 + n, [](const int& x, const int& y) { return x > y; });
或者是这样
sort(a + 1, a + 1 + n, []greater());
的确这样子写都能加快程序运行的时间,相比于通过传递的 sort 写法:
...
bool cmp(int x, int y) {
    return x > y;
}
...
sort(a + 1, a + 1 + n, cmp);
...
这样子写每一次在调用的时候都会定义两个变量 x、 y 造成程序的效率降低,在使用结构体的时候尤其明显。
例子
UVA11729 Commando War
分别使用以下两份 C++ 代码
/*
Commando War
https://vjudge.csgrandeur.cn/contest/584210#problem/A
*/
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1005;
struct Work {
    int pre, spd;
}work[maxn];
bool cmp(Work x, Work y) {
    return x.spd > y.spd;
}
int n;
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int it = 0;
    while(true) {
        cin >> n;
        it++;
        if (n == 0) break;
        for(int i = 1; i <= n; i++)
            cin >> work[i].pre >> work[i].spd;
        sort(work + 1, work + 1 + n, cmp);
        int ans1 = 0, ans2 = 0;
        for(int i = 1; i <= n; i++) {
            ans1 += work[i].pre;
            ans2 = max(ans2, ans1 + work[i].spd);
        }
        cout << "Case " << it << ": " << ans2 << endl;
    }
    return 0;
}
/*
编程语言
C++14 (GCC 9)
代码长度
843B
用时
10ms
内存
0B
*/
/*
Commando War
*/
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1005;
struct Work {
    int pre, spd;
}work[maxn];
/*
bool cmp(Work x, Work y) {
    return x.spd > y.spd;
}
*/
int n;
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int it = 0;
    while(true) {
        cin >> n;
        it++;
        if (n == 0) break;
        for(int i = 1; i <= n; i++)
            cin >> work[i].pre >> work[i].spd;
        sort(work + 1, work + 1 + n,
         [](const Work& x, const Work& y) { return x.spd > y.spd; });
        int ans1 = 0, ans2 = 0;
        for(int i = 1; i <= n; i++) {
            ans1 += work[i].pre;
            ans2 = max(ans2, ans1 + work[i].spd);
        }
        cout << "Case " << it << ": " << ans2 << "\n";
    }
    return 0;
}
/*
编程语言
C++14 (GCC 9)
代码长度
916B
用时
0ms
内存
0B
*/
**UVA 的测评机十分感人,可能与实际数据相比可能有偏差*
在 $n \le 1000$ 的情况下,足足慢了 10ms (可能还不止,),由此可见二者的效率差距