4721: 【GESP2506四级】排序

内存限制:128 MB 时间限制:1.000 S
评测方式:文本比较 命题人:
提交:11 解决:7

题目描述

样例输入 复制

5
1 60
3 70
2 80
4 55
4 50

样例输出 复制

8

提示

#include <bits/stdc++.h>
using namespace std;
struct Student {
    int h, w, id;
};
bool cmp(const Student& a, const Student& b) {
    if (a.h != b.h) return a.h > b.h;
    return a.w > b.w;	
}
int main() {
    int n;
    cin >> n;
    vector<Student> stu(n);
    for (int i = 0; i < n; i++) {
        cin >> stu[i].h >> stu[i].w;
        stu[i].id = i;  
    }
    sort(stu.begin(), stu.end(), cmp);
    vector<int> pos(n); // 提取原始位置
    for (int i = 0; i < n; i++) {
        pos[i] = stu[i].id;
    }
    long long ans = 0; // 用冒泡排序统计逆序对
    for (int i = 0; i < n - 1; i++) {
    	bool f=true; //是否已排好序
        for (int j = 0; j < n - 1 - i; j++) {
            if (pos[j] > pos[j + 1]) {
                swap(pos[j], pos[j + 1]);
                ans++;
                f=false;
            }
        }
        if(f) break;
    }
    cout << ans << endl;
    return 0;
}