#include #include #include template struct MinCostFlow { struct Edge { int src, dst; Cap cap; Cost cost; Edge(int src, int dst, Cap cap, Cost cost) : src(src), dst(dst), cap(cap), cost(cost){}; }; using Edges = std::vector; using Graph = std::vector>; Edges edges; Graph graph; std::vector dist; std::vector rev; const Cost INF = std::numeric_limits::max() / 2; explicit MinCostFlow(int n) : graph(n), dist(n), rev(n) {} void span(int u, int v, Cap cap, Cost cost) { graph[u].push_back(edges.size()); edges.emplace_back(u, v, cap, cost); graph[v].push_back(edges.size()); edges.emplace_back(v, u, 0, -cost); } void bellman_ford(int s) { std::fill(dist.begin(), dist.end(), INF); dist[s] = 0; for (int i = 0; i < (int)graph.size(); ++i) { for (int eidx = 0; eidx < (int)edges.size(); ++eidx) { const auto& edge = edges[eidx]; int u = edge.src, v = edge.dst; if (edge.cap > 0 && dist[u] < INF && dist[v] > dist[u] + edge.cost) { dist[v] = dist[u] + edge.cost; rev[v] = eidx; } } } } Cost exec(int s, int g, Cap flow) { Cost ret = 0; while (flow > 0) { bellman_ford(s); if (dist[g] == INF) break; Cap f = flow; int v = g; while (v != s) { const auto& edge = edges[rev[v]]; f = std::min(f, edge.cap); v = edge.src; } flow -= f; ret += f * dist[g]; v = g; while (v != s) { auto& edge = edges[rev[v]]; auto& redge = edges[rev[v] ^ 1]; edge.cap -= f; redge.cap += f; v = edge.src; } } return (flow > 0 ? -1 : ret); } }; using lint = long long; constexpr lint INF = 1LL << 30; void solve() { int n; std::cin >> n; lint amax = 0, absum = 0; int s = n * 2 + 0, g = n * 2 + 1; MinCostFlow mcf(n * 2 + 2); for (int v = 0; v < n; ++v) { if (v == 0) { mcf.span(s, v, INF, 1); mcf.span(v + n, g, INF, 0); } else { lint a, b; std::cin >> a >> b; mcf.span(s, v, a, -INF); mcf.span(v + n, g, b, -INF); amax += b; absum += a + b; } } for (int u = 0; u < n; ++u) { for (int v = 0; v < n; ++v) { if (u != v) mcf.span(u, v + n, INF, 0); } } mcf.span(s, g, INF, 0); lint c = mcf.exec(s, g, INF); lint amin = c + INF * absum; std::cout << amax - amin + 1 << std::endl; } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); solve(); return 0; }