#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){
auto 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] -= 2;
mp2[{a->second, a->first}] -= 2;
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){
++c2;
sum+= p.second;
}
else{
sum+=p.first;
++c1;
}
}
}
}
while(c1 < n / 2){
auto 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){
auto 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