Source Code
#include <bits/stdc++.h>
#define ll  long long
#define ss second
#define ff first
#define sz size()
#define el '\n'
#define tc ll tt; cin>>tt; while(tt--)
using namespace std;

void fastIO() {
	ios::sync_with_stdio(false);
	cout.tie(nullptr);
	cin.tie(nullptr);
}

const ll N = 2e5 + 5;
bool d[N];

int main(){
    fastIO();
    ll n,x,y,ans = 0,a,b,d1=0,d2=0,ans2=0;
    cin >> n;
    a = n - 1;
    b = n - 1;
    vector<pair<ll,pair<ll,ll>>> v1(n),v2(n);
    for (int i = 0;i < n;i++){
        cin >> x >> y;
        v1[i] = {x,{y, i}};
        v2[i] = {y,{x, i}};
        ans2 += max(x,y);
    }
    sort(v1.begin(),v1.end());
    sort(v2.begin(),v2.end());
    while (d1 + d2 < n && a >= 0 && b >= 0){
        //cout << v1[a].ss.ss << ' ' << v2[b].ss.ss << el;
        while(d[v1[a].ss.ss]) a--;
        while(d[v2[b].ss.ss]) b--;

        if (v1[a].ss.ss != v2[b].ss.ss && d1 < n / 2 && d2 < n / 2){
            d[v1[a].ss.ss] = 1;
            ans += v1[a].ff;
            a--;
            d1++;
            d[v2[b].ss.ss] = 1;
            ans += v2[b].ff;
            b--;
            d2++;
            continue;
        }

        if (d1 == n / 2 && d2 < n / 2){
            d[v2[b].ss.ss] = 1;
            ans += v2[b].ff;
            b--;
            d2++;
        }
        if (d2 == n / 2 && d1 < n / 2){
            d[v1[a].ss.ss] = 1;
            ans += v1[a].ff;
            a--;
            d1++;
        }

        //cout << ans << ' ' << a << ' ' << b << el;

        ll n1 = a,n2 = b,i = a - 1;
        while(i >= 0 && d[v1[i].ss.ss]) i--;
        n1 = i;
        i = b - 1;
        while(i >= 0 && d[v2[i].ss.ss]) i--;
        n2 = i;
        //cout << "N1 << " << n1 << "  n2 << " << n2 << el;
        if (n1 >= 0 && n2 >= 0 && v1[a].ff - v1[n1].ff > v2[b].ff - v2[n2].ff && d1 < n / 2){
            d[v1[a].ss.ss] = 1;
            ans += v1[a].ff;
            a--;
            d1++;
        }
        else if (d2 < n / 2){
            d[v2[b].ss.ss] = 1;
            ans += v2[b].ff;
            b--;
            d2++;
        }
       // cout << "ans " << ans << el;
    }

    cout << ans;
}
Copy
Two Teams heba.daraghmeh
GNU G++17
3 ms
1.0 MB
Wrong Answer