from collections import deque import sys sys.setrecursionlimit(10 ** 6) class Dinic: def __init__(self, n, flow_limit): self.vertices = n self.flow_limit = flow_limit self.links = [[] for _ in range(n)] self.level = None self.progress = None def add_link(self, f, t, cap): from_id = len(self.links[f]) to_id = len(self.links[t]) if f == t: to_id += 1 self.links[f].append([cap, t, to_id]) self.links[t].append([0, f, from_id]) def bfs(self, src, dst): level = [-1 for _ in range(self.vertices)] level[src] = 0 dq = deque([src]) while len(dq) > 0: cur = dq.popleft() for cap, nxt, _ in self.links[cur]: if cap > 0 and level[nxt] < 0: level[nxt] = level[cur] + 1 dq.append(nxt) self.level = level return level[dst] != -1 def dfs(self, cur, src, up): if cur == src: return up ans = 0 lv_cur = self.level[cur] for i in range(self.progress[cur], len(self.links[cur])): self.progress[cur] += 1 cap, nxt, rev = self.links[cur][i] if self.level[nxt] >= lv_cur or self.links[nxt][rev][0] == 0: continue d = self.dfs(nxt, src, min(up - ans, self.links[nxt][rev][0])) if d <= 0: continue self.links[cur][i][0] += d self.links[nxt][rev][0] -= d ans += d if ans == up: break return ans def max_flow(self, src, dst): ans = 0 while ans < self.flow_limit: if not self.bfs(src, dst): break self.progress = [-1 for _ in range(self.vertices)] while ans < self.flow_limit: f = self.dfs(dst, src, self.flow_limit - ans) if f <= 0: break ans += f return ans INF = 10 ** 13 n = int(input()) src = 2 * n dst = src + 1 mf = Dinic(2 * n + 2, INF) ans = 0 for u in range(n): b, c = map(int, input().split()) ans += b + c ans += b + c # 何もしないの辺が余分にカットされるのであらかじめもらっておく mf.add_link(src, u, b + c) mf.add_link(u, dst, c) mf.add_link(src, u + n, b) mf.add_link(u + n, dst, b + c) mf.add_link(u, u + n, INF) m = int(input()) for _ in range(m): d, e = map(int, input().split()) mf.add_link(d, e + n, INF) ans -= mf.max_flow(src, dst) print(ans)