#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; #define sz size() #define pb push_back #define mp make_pair #define fi first #define se second #define all(c) (c).begin(), (c).end() #define rep(i,a,b) for(ll i=(a);i<(b);++i) #define per(i,a,b) for(ll i=(b-1);i>=(a);--i) #define clr(a, b) memset((a), (b) ,sizeof(a)) #define ctos(c) string(1,c) #define print(x) cout<<#x<<" = "< uf, usz; int nc; void init(int n){ vector uf_(n); vector usz_(n, 1); uf = uf_; usz = usz_; nc = n; for(int i = 0; i < uf.size(); i++){ uf[i] = i; } } int find(int a){ return (uf[a] == a) ? a : uf[a] = find(uf[a]); } void union_(int a, int b){ a = find(a); b = find(b); if(a != b){ if(usz[a] >= usz[b]){ swap(a, b); } uf[a] = b; usz[b] += usz[a]; nc--; } } int check(int a, int b){ return (find(a) == find(b)) ? 1 : 0; } int get_size(int a){ return usz[find(a)]; } long long minST(vector > > &v, long long V){ init(V); long long ret = 0; sort(v.begin(),v.end()); for(long long i = 0; i < v.sz; i++){ long long from = v[i].se.fi; long long to = v[i].se.se; long long cost = v[i].fi; if(check(from,to)==0){ union_(from,to); ret += cost; } } return ret; } int main() { ll n; cin>>n; vector vc,vd; ll ans = 0; rep(i,0,n){ ll a,b; cin>>a>>b; ans += a; vc.pb(a); vd.pb(b); } vector > > v; rep(i,0,vc.sz){ v.pb(mp(vc[i],mp(0,i+1))); } rep(i,1,vd.sz){ v.pb(mp(vd[i],mp(i,i+1))); } printf("%lld\n", ans+minST(v,n+1)); return 0; }