/* -*- coding: utf-8 -*- * * 860.cc: No.860 買い物 - yukicoder */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; /* constant */ const int MAX_N = 100000 + 1; const int MAX_M = MAX_N * 2; /* typedef */ typedef long long ll; struct UFT { int links[MAX_N], ranks[MAX_N], sizes[MAX_N]; UFT() {} void init(int n) { for (int i = 0; i < n; i++) links[i] = i, ranks[i] = sizes[i] = 1; } int root(int i) { int i0 = i; while (links[i0] != i0) i0 = links[i0]; return (links[i] = i0); } int rank(int i) { return ranks[root(i)]; } int size(int i) { return sizes[root(i)]; } bool same(int i, int j) { return root(i) == root(j); } int merge(int i0, int i1) { int r0 = root(i0), r1 = root(i1), mr; if (r0 == r1) return r0; if (ranks[r0] == ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; ranks[r0]++; mr = r0; } else if (ranks[r0] > ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; mr = r0; } else { links[r0] = r1; sizes[r1] += sizes[r0]; mr = r1; } return mr; } }; struct Edge { int d, i, j; Edge() {} Edge(int _d, int _i, int _j): d(_d), i(_i), j(_j) {} bool operator<(const Edge &e) const { return d < e.d; } }; /* global variables */ int cs[MAX_N], ds[MAX_N]; Edge es[MAX_M]; UFT uft; /* subroutines */ /* main */ int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d%d", cs + i, ds + i); int m = 0; for (int i = 0; i < n; i++) es[m++] = Edge(cs[i], i, n); for (int i = 1; i < n; i++) es[m++] = Edge(ds[i], i - 1, i); sort(es, es + m); uft.init(n + 1); ll sum = 0; for (int i = 0; i < m; i++) { Edge &ei = es[i]; if (! uft.same(ei.i, ei.j)) { uft.merge(ei.i, ei.j); sum += ei.d; } } for (int i = 0; i < n; i++) sum += cs[i]; printf("%lld\n", sum); return 0; }