#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; class MaxFlow { public: MaxFlow(int V) : G(V), level(V), iter(V) {} void add(int u, int v, int cap) { G[u].push_back((edge){v, cap, (int)G[v].size()}); G[v].push_back((edge){u, 0, (int)G[u].size() - 1}); } int calc(int s, int t) { int res = 0; for (;;) { bfs(s); if (level[t] < 0) return res; fill(iter.begin(), iter.end(), 0); int f; while ((f = dfs(s, t, (int)1e9)) > 0) { res += f; } } } private: struct edge { int to, cap, rev; }; vector level, iter; vector > G; void bfs(int s) { fill(level.begin(), level.end(), -1); queue q; q.push(s); level[s] = 0; while (!q.empty()) { int v = q.front(); q.pop(); for (edge e : G[v]) { if (e.cap > 0 && level[e.to] < 0) { level[e.to] = level[v] + 1; q.push(e.to); } } } } int dfs(int v, int t, int f) { if (v == t) return f; for (int &i = iter[v]; i < G[v].size(); i++) { edge &e = G[v][i]; if (e.cap > 0 && level[v] < level[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; }