GESP2025年6月认证C++四级( 第三部分编程题(2)排序)
参考程序:
#include <cstdio>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;int main() {int n, ans = 0;// 读取学生人数scanf("%d", &n);// 用 vector 存储每个学生的身高和体重(h, w)vector<pair<int, int>> a(n);for (int i = 0; i < n; i++)scanf("%d%d", &a[i].first, &a[i].second); // 读入每个学生的 h 和 w// 枚举所有 i < j 的学生对for (int i = 0; i < n; i++)for (int j = i + 1; j < n; j++)// 如果 a[i] < a[j],说明 i 应该排在 j 的后面// 但现在在前面,表示出现了“逆序对”,需要一次交换if (a[i] < a[j])ans++;// 输出最少交换次数cout << ans << '\n';return 0;
}