#include using namespace std; int main() { int N; cin >> N; vector C(N); vector D(N); for (int i = 0; i < N; ++i) { cin >> C[i] >> D[i]; } vector> edges; for (int i = 0; i < N; ++i) { edges.emplace_back(C[i], N, i); } for (int i = 1; i < N; ++i) { edges.emplace_back(D[i], i - 1, i); } sort(edges.begin(), edges.end()); vector fa(N + 1); iota(fa.begin(), fa.end(), 0); function find = [&](int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }; int64_t ans = accumulate(C.begin(), C.end(), 0LL); for (auto t : edges) { int w, u, v; tie(w, u, v) = t; int fu = find(u); int fv = find(v); if (fu != fv) { fa[fu] = fv; ans += w; } } cout << ans << endl; return 0; }