Source Code
#include <iostream>
#include <set>
#include <map>
using namespace std;

int main() {
	
	int n;
	set<pair<int, int> > s1, s2;
	map<pair<int, int>, int> mp1, mp2;
	cin >> n;
	int c1 = 0, c2 = 0;
	for(int i = 0, a, b; i < n;++i){
		cin >> a >> b;
		s1.insert({a, b});
		s2.insert({b, a});
		++mp1[{a, b}];
		++mp2[{b, a}];
	}
	long long sum = 0;
	while(c1 < n / 2 && c2 < n / 2){
		pair<int,int> a = *s1.rbegin(), b = *s2.rbegin();
		if(a.first + b.second > b.first + a.second && (a.first != b.second || b.first != a.second)){
			--mp2[{a.second, a.first}];
			--mp1[a];
			sum += a.first;
			if(mp1[a] == 0){
				s2.erase({a.second, a.first});
				s1.erase(a);
			}
			++c1;
		}
		else if(a.first != b.second || b.first != a.second){
			--mp2[b];
			--mp1[{b.second, b.first}];
			sum += b.first;
			if(mp2[b] == 0){
				s1.erase({b.second, b.first});
				s2.erase(b);
			}
			++c2;
		}
		else{
			if(mp1[a] > 1){
				mp1[a]--;
				mp2[{a.second, a.first}]--;
				
				sum += a.first;
				if(mp1[a] == 0){
					s2.erase({a.second, a.first});
					s1.erase(a);
				}
				++c1;
			}
			else{
				--mp2[b];
				--mp1[{b.second, b.first}];
				pair<int,int>p = a;
				if(mp2[b] == 0){
					s1.erase({b.second, b.first});
					s2.erase(b);
				}
				a = *s1.rbegin(), b = *s2.rbegin();
				if(a.first + p.second> b.first + p.first){
					++c1;
					sum+= p.second;
				}
				else{
					sum+=p.first;
					++c2;
				}
			}
		}
	}
	while(c1 < n / 2){
		pair<int,int> a = *s1.begin();
		--mp1[a];
		--mp2[{a.second, a.first}];
		sum += a.first;
		if(mp1[a] == 0){
			s2.erase({a.second, a.first});
			s1.erase(a);
		}
		++c1;
	}
	
	while(c2 < n / 2){
		
		pair<int,int> b = *s2.begin();
		--mp2[b];
		--mp1[{b.second, b.first}];
		sum += b.first;
		if(mp2[b] == 0){
			s1.erase({b.second, b.first});
			s2.erase(b);
		}
		++c2;
	}
	cout << sum;
	return 0;
}
Copy
Two Teams azoz
GNU G++17
3 ms
308 KB
Wrong Answer