#include #define GET_MACRO(a, b, c, NAME, ...) NAME #define rep(...) GET_MACRO(__VA_ARGS__, rep3, rep2)(__VA_ARGS__) #define rep2(i, a) rep3 (i, 0, a) #define rep3(i, a, b) for (int i = (a); i < (b); i++) #define repr(...) GET_MACRO(__VA_ARGS__, repr3, repr2)(__VA_ARGS__) #define repr2(i, a) repr3 (i, 0, a) #define repr3(i, a, b) for (int i = (b) - 1; i >= (a); i--) #define chmin(a, b) ((b) < a && (a = (b), true)) #define chmax(a, b) (a < (b) && (a = (b), true)) using namespace std; typedef long long ll; struct MaxFlow { struct Edge { int to, cap, rev; }; vector dist, it; vector> G; MaxFlow(int n) : G(n), dist(n), it(n) {} void add(int u, int v, int c) { Edge a = {v, c, (int)G[v].size()}; Edge b = {u, 0, (int)G[u].size()}; G[u].push_back(a); G[v].push_back(b); } int calc(int s, int t) { int res = 0; while (bfs(s, t)) { fill(it.begin(), it.end(), 0); while (int f = dfs(s, t, INT_MAX)) { res += f; } } return res; } bool bfs(int s, int t) { fill(dist.begin(), dist.end(), -1); queue q; q.push(s); dist[s] = 0; while (!q.empty()) { int v = q.front(); q.pop(); for (Edge e : G[v]) { if (e.cap > 0 && dist[e.to] < 0) { dist[e.to] = dist[v] + 1; q.push(e.to); } } } return dist[t] >= 0; } int dfs(int v, int t, int f) { if (v == t) return f; for (int &i = it[v]; i < G[v].size(); i++) { Edge &e = G[v][i]; if (e.cap > 0 && dist[v] < dist[e.to]) { int d = dfs(e.to, t, min(f, e.cap)); if (d > 0) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } }; int main() { int N; cin >> N; MaxFlow f(N * 2 + 2); const int inf = 1e7; int s = N * 2; int t = N * 2 + 1; int ans = 0; rep (i, N) { int B, C; cin >> B >> C; int mx = max(B, C); ans += mx; f.add(s, i, mx - B); f.add(i, i + N, mx); f.add(i + N, t, mx - C); } int M; cin >> M; rep (i, M) { int D, E; cin >> D >> E; f.add(E + N, D, inf); } ans -= f.calc(s, t); cout << ans << endl; return 0; }