import sys from collections import defaultdict def main(): N = int(sys.stdin.readline()) B = [] C = [] for _ in range(N): b, c = map(int, sys.stdin.readline().split()) B.append(b) C.append(c) M = int(sys.stdin.readline()) constraints = [[] for _ in range(N)] for _ in range(M): D, E = map(int, sys.stdin.readline().split()) constraints[D].append(E) # Initialize DP: dictionary where key is mask, value is max satisfaction dp = {0: 0} for i in range(N): next_dp = defaultdict(int) for mask, current_max in dp.items(): # Option 1: do not include i if mask in next_dp: if current_max > next_dp[mask]: next_dp[mask] = current_max else: next_dp[mask] = current_max # Option 2: include i if (mask >> i) & 1: # Must take the tour new_mask = mask for e in constraints[i]: new_mask |= (1 << e) new_sat = current_max + B[i] if new_mask in next_dp: if new_sat > next_dp[new_mask]: next_dp[new_mask] = new_sat else: next_dp[new_mask] = new_sat else: # Option a: take the tour new_mask_a = mask for e in constraints[i]: new_mask_a |= (1 << e) new_sat_a = current_max + B[i] if new_mask_a in next_dp: if new_sat_a > next_dp[new_mask_a]: next_dp[new_mask_a] = new_sat_a else: next_dp[new_mask_a] = new_sat_a # Option b: do not take the tour new_mask_b = mask new_sat_b = current_max + C[i] if new_mask_b in next_dp: if new_sat_b > next_dp[new_mask_b]: next_dp[new_mask_b] = new_sat_b else: next_dp[new_mask_b] = new_sat_b # Update dp to next_dp, keeping only the maximum for each mask dp = {} for mask in next_dp: if mask in dp: if next_dp[mask] > dp[mask]: dp[mask] = next_dp[mask] else: dp[mask] = next_dp[mask] if dp: print(max(dp.values())) else: print(0) if __name__ == '__main__': main()