#include using namespace std; vector adj2[1<<20]; int val2[1<<20]; int mate2[1<<20]; int seen2[1<<20]; int cookie = 1; void match(int a, int b) { assert(mate2[a] == -1); assert(mate2[b] == -1); mate2[a] = b; mate2[b] = a; } void unmatch(int v) { if (mate2[v] != -1) { mate2[mate2[v]] = -1; mate2[v] = -1; } } bool extend(int v, int c) { if (seen2[v] == c) return false; seen2[v] = c; for (auto x: adj2[v]) { if (mate2[x] == -1 || extend(mate2[x], c)) { unmatch(v); match(v, x); return true; } } return false; } vector adj[1<<20]; int val[1<<20], seen[1<<20]; void dfs(int u, int &bal, long long &totv, int &maxv) { if (seen[u]) return; seen[u] = true; bal += adj[u].size()-2; totv += val[u]*(adj[u].size()-1); maxv = max(maxv, val[u]); for (auto x: adj[u]) dfs(x, bal, totv, maxv); } int main(void) { int n, v = 0; scanf("%d", &n); unordered_map idx; for (int i = 0; i < n; ++i) { int s, t; scanf("%d%d", &s, &t); int &si = idx[s], &ti = idx[t]; if (!si) val[si = ++v] = s; if (!ti) val[ti = ++v] = t; adj[si].push_back(ti); adj[ti].push_back(si); adj2[i].push_back(n+si); adj2[i].push_back(n+ti); } memset(mate2, -1, sizeof(mate2)); memset(seen2, -1, sizeof(seen2)); for (int i = 0; i < n; ++i) { // greedy match if (mate2[adj2[i][0]] != -1 && mate2[adj2[i][1]] == -1) { match(i, adj2[i][1]); } else { assert(extend(i, ++cookie)); } } memset(seen, 0, sizeof(seen)); long long tot = 0; for (int i = 1; i <= v; ++i) { if (!seen[i]) { int bal = 0, maxv = 0; dfs(i, bal, tot, maxv); if (bal < 0) tot += maxv; } } printf("%lld\n", tot); }