Source Code
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <math.h>
#include <vector>
#include <set>
#include <map>
using namespace std;
long long p[500005], c[500005];
int main() {
	int n, x, s1, s2;
	long long ans = 0;
	cin >> n;
	vector<pair<long long, long long>> v;
	for (int i = 0; i < n; i++) {
		cin >> p[i] >> c[i];;
		v.push_back(make_pair(abs(p[i] - c[i]), i));
	}
	sort(v.begin(), v.end());
	bool flag = 0;
	x = s1 = s2 = 0;
	for (int i = 0; i < n; i++) {
		if (max(p[i], c[i]) == p[i]) {
			if (s1 == n / 2) {
				if (v[x].second == i) {
					s2++;
					ans += c[v[x].second];
				}
				else if (v[x].second != i) {
					ans -= p[v[x].second];
					ans += c[v[x].second];
					p[v[x].second] = c[v[x].second] = 0;
					s2++;
					ans += p[i];
				}
				x++;
			}
			else {
				s1++;
				ans += p[i];
			}
		}
		else {
			if (s2 == n / 2) {
				if (v[x].second == i) {
					s1++;
					ans += p[v[x].second];
				}
				else if (v[x].second != i) {
					ans -= c[v[x].second];
					ans += p[v[x].second];
					p[v[x].second] = c[v[x].second] = 0;
					s1++;
					ans += c[i];
				}
				x++;
			}
			else {
				s2++;
				ans += c[i];
			}
		}
	}
	cout << ans;
	return 0;
}


Copy
Two Teams Sarah
GNU G++17
3 ms
868 KB
Wrong Answer