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], f[500005] = { 0 };
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) {
				for (int j = 0; j < n; j++) {
					if (f[v[j].second] == 1) {
						x = v[j].second;
						f[v[j].second] = 2;
						break;
					}
				}
				ans -= p[x];
				ans += c[x];
				s2++;
				ans += p[i];
				f[i] = 1;
			}
			else {
				s1++;
				ans += p[i];
				f[i] = 1;
			}
		}
		else {
			if (s2 == n / 2) {
				for (int j = 0; j < n; j++) {
					if (f[v[j].second] == 2) {
						x = v[j].second;
						f[v[j].second] = 1;
						break;
					}
				}
				ans -= c[x];
				ans += p[x];
				s1++;
				ans += c[i];
				f[i] = 2;
			}
			else {
				s2++;
				ans += c[i];
				f[i] = 2;
			}
		}

	}
	cout << ans;
	return 0;
}


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