#include #include #include #include #include #define _USE_MATH_DEFINES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() const int INF = 0x3f3f3f3f; const long long LINF = 0x3f3f3f3f3f3f3f3fLL; const double EPS = 1e-8; const int MOD = 1000000007; // 998244353; const int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1}; /*-------------------------------------------------*/ struct UnionFind { UnionFind(int n) : data(n, -1) {} int root(int ver) { return data[ver] < 0 ? ver : data[ver] = root(data[ver]); } void unite(int ver1, int ver2) { ver1 = root(ver1); ver2 = root(ver2); if (ver1 != ver2) { if (data[ver1] > data[ver2]) swap(ver1, ver2); data[ver1] += data[ver2]; data[ver2] = ver1; } } bool same(int ver1, int ver2) { return root(ver1) == root(ver2); } int size(int ver) { return -data[root(ver)]; } private: vector data; }; using CostType = long long; struct Edge { int src, dst; CostType cost; Edge(int src, int dst, CostType cost = 0) : src(src), dst(dst), cost(cost) {} inline bool operator<(const Edge &rhs) const { return cost != rhs.cost ? cost < rhs.cost : dst != rhs.dst ? dst < rhs.dst : src < rhs.src; } inline bool operator<=(const Edge &rhs) const { return cost <= rhs.cost; } inline bool operator>(const Edge &rhs) const { return cost != rhs.cost ? cost > rhs.cost : dst != rhs.dst ? dst > rhs.dst : src > rhs.src; } inline bool operator>=(const Edge &rhs) const { return cost >= rhs.cost; } }; CostType kruskal(const vector > &graph) { int n = graph.size(); priority_queue, greater > que; REP(i, n) { for (Edge e : graph[i]) que.emplace(e); } vector > res(n); CostType total = 0; UnionFind uf(n); while (!que.empty()) { Edge e = que.top(); que.pop(); if (!uf.same(e.src, e.dst)) { res[e.src].emplace_back(e); res[e.dst].emplace_back(Edge(e.dst, e.src, e.cost)); total += e.cost; uf.unite(e.src, e.dst); } } return total; } int main() { cin.tie(0); ios::sync_with_stdio(false); // freopen("input.txt", "r", stdin); int n; cin >> n; vector > graph(n + 1); long long ans = 0; REP(i, n) { int c, d; cin >> c >> d; ans += c; graph[i].emplace_back(Edge(i, n, c)); graph[n].emplace_back(Edge(n, i, c)); if (i > 0) { graph[i - 1].emplace_back(Edge(i - 1, i, d)); graph[i].emplace_back(Edge(i, i - 1, d)); } } cout << ans + kruskal(graph) << '\n'; return 0; }