def main(): import sys from collections import defaultdict N = int(sys.stdin.readline()) BC = [] for _ in range(N): B, C = map(int, sys.stdin.readline().split()) BC.append((B, C)) M = int(sys.stdin.readline()) constraints = [[] for _ in range(N)] # constraints[i] contains list of j where i -> j for _ in range(M): D, E = map(int, sys.stdin.readline().split()) constraints[D].append(E) # Memoization cache for the DP from functools import lru_cache @lru_cache(maxsize=None) def dp(pos, mask): if pos >= N: return 0 # Decide whether to visit this country or not # Option 1: do not visit res = dp(pos + 1, mask) # Option 2: visit new_mask = mask must_join = (mask >> pos) & 1 # If we are forced to join, then must choose B if must_join: # Choose to join score = BC[pos][0] next_mask = new_mask # Remove the current bit next_mask &= ~(1 << pos) # Apply new constraints for j in constraints[pos]: next_mask |= (1 << j) res = max(res, score + dp(pos + 1, next_mask)) else: # Can choose to join or not, or skip visiting # Case 1: visit and not join score_not_join = BC[pos][1] new_mask_not_join = new_mask & ~(1 << pos) # Visit but not join: any future constraints not applied res_option = score_not_join + dp(pos + 1, new_mask_not_join) # Case 2: visit and join score_join = BC[pos][0] next_mask_join = new_mask next_mask_join &= ~(1 << pos) for j in constraints[pos]: next_mask_join |= (1 << j) res_option = max(res_option, score_join + dp(pos + 1, next_mask_join)) # Take the best of visiting or not res = max(res, res_option) return res max_score = dp(0, 0) print(max_score) if __name__ == "__main__": main()