Source Code
#include "bits/stdc++.h"

using namespace std;
typedef long long ll;

struct Box {
    int adv, idx, to;
    bool operator < (const Box &rhs) {
        return adv > rhs.adv;
    } 
};


void solve() {
    int n;
    cin >> n;
    vector<pair<int, int>> p(n);
    vector<Box> box(n); 
    for (int i = 0; i < n; i++) {
        cin >> p[i].first >> p[i].second;
        box[i].idx = i;
        box[i].adv = abs(p[i].second - p[i].first);
        box[i].to = (p[i].first < p[i].second);
    }
    
    sort(box.begin(), box.end());

    int t1 = 0, t2 = 0;
    ll ans = 0;
    for (int i = 0; i < n; i++) {
        if (box[i].to == 0) {
            if (t1 < n / 2) {
                ans += p[box[i].idx].first; 
                t1++;
            }
            else {
                ans += p[box[i].idx].second;
                t2++;
            }
        }
        else {
            if (t2 < n / 2) {
                ans += p[box[i].idx].second;
                t2++;
            }
            else {
                ans += p[box[i].idx].first; 
                t1++;               
            }
        }
    }

    cout << ans << '\n';
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t = 1;
    // cin >> t;
    while (t--) {
        solve();
    }
}
Copy
Two Teams OsamaX01
GNU G++17
54 ms
4.9 MB
Accepted