sort()函数

sort函数的特点是非常好用、易用,比赛中,利用这个特点设置坑,让你跳。比如,不管时间复杂度,或者不会看时间复杂度,上来就是sort,然后就肯定超时。就是用sort,也会导致,对数组和下标的理解不完备,导致没有手搓代码的能力。

image.png

  1. // ϱê´Ó0¿ªÊ¼ sort(a, a + n);
  2. // ϱê´Ó1¿ªÊ¼ sort(a + 1, a + 1 + n);
  3. // ĬÈÏ´ÓСµ½´óÅÅÐò
  4. // Òª´Ó´óµ½Ð¡ÅÅÐò
  5. // ¶¨Òåcmpº¯Êý
  6. // reverse(a, a + n);
  7. // sort(a, a + n, greater<int>());
  1. // 先看一下sort的自定义
  2. // 自定义一个cmp函数
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5. int a[110];
  6. bool cmp(int a, int b){
  7. return a > b;
  8. }
  9. int main()
  10. {
  11. int n;
  12. cin >> n;
  13. for (int i = 0; i < n; i++) cin >> a[i];
  14. sort(a, a + n, cmp);
  15. for (int i = 0; i < n; i++) cout << a[i] << ' ';
  16. puts("");
  17. return 0;
  18. }
  1. // 如果只是从大到小,还可以使用greater<int>()
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. int a[110];
  5. int main()
  6. {
  7. int n;
  8. cin >> n;
  9. for (int i = 0; i < n; i++) cin >> a[i];
  10. sort(a, a + n, greater<int>());
  11. for (int i = 0; i < n; i++) cout << a[i] << ' ';
  12. puts("");
  13. return 0;
  14. }
  1. // 除了自定义函数,可以结构体的小于符号重载
  2. // 以下两个代码,实战意义很大,务必熟练操作
  3. // 下面这段代码,看起来很奇怪,可是一定要很熟悉的啊
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6. const int N = 110;
  7. struct node{
  8. int x, y;
  9. node(int _x = 0, int _y = 0): x(_x), y(_y){}
  10. bool operator< (const node& W)const{
  11. if (x == W.x) return y < W.y;
  12. return x < W.x;
  13. }
  14. }a[N];
  15. int n;
  16. int main(){
  17. cin >> n;
  18. for (int i = 0; i < n; i++) cin >> a[i].x >> a[i].y;
  19. sort(a, a + n);
  20. for (int i = 0; i < n; i++) cout << a[i].x << ' ' << a[i].y << '\n';
  21. return 0;
  22. }
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int N = 110;
  4. struct node{
  5. int x, y;
  6. node(int _x = 0, int _y = 0): x(_x), y(_y){}
  7. }a[N];
  8. int n;
  9. bool cmp(node a, node b){
  10. if (a.x == b.x) return a.y < b.y;
  11. return a.x < b.x;
  12. }
  13. int main(){
  14. cin >> n;
  15. for (int i = 0; i < n; i++) cin >> a[i].x >> a[i].y;
  16. sort(a, a + n, cmp);
  17. for (int i = 0; i < n; i++) cout << a[i].x << ' ' << a[i].y << '\n';
  18. return 0;
  19. }

image.png

例题 病人排队

例题【07NOIP普及组】奖学金

例题【09NOIP普及组】分数线划定