PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BS0000300. Hai nhóm khỉ và những quả dừa (Svada)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Hai nhóm khỉ và những quả dừa (Svada)

Svada

Source: Kattis

Version: Phuoc Hung OJ Extended

Problem Statement

An unknown positive number of coconuts is present. In the first group, monkey i picks its first coconut AiA_i seconds after entry and then one every BiB_i seconds. As soon as all coconuts are picked, the first group leaves and the second enters. In the second group, monkey j opens its first coconut after CjC_j seconds and then one every DjD_j seconds. The second group leaves immediately when all coconuts are opened. Several monkeys may finish at the same second, but stop when no coconuts remain. The total duration TT of both groups is consistent with some actual coconut count. Find the second group entry time measured from the first group entry.

Input

Line 1: TT. Line 2: NN. Next NN lines: Ai,BiA_i,B_i. Next line: MM. Last MM lines: Cj,DjC_j,D_j.

Output

Print the elapsed seconds until the second group enters.

Subtasks

  • Subtask 1 (20 points): 1≤T≤2001\le T\le200; 1≤N,M≤81\le N,M\le8; 1≤Ai,Bi,Cj,Dj≤1091\le A_i,B_i,C_j,D_j\le10^9.
  • Subtask 2 (30 points): 1≤T≤1091\le T\le10^9; N=M=1N=M=1; 1≤Ai,Bi,Cj,Dj≤1091\le A_i,B_i,C_j,D_j\le10^9.
  • Subtask 3 (50 points): 1≤T≤1091\le T\le10^9; 1≤N,M≤1001\le N,M\le100; 1≤Ai,Bi,Cj,Dj≤1091\le A_i,B_i,C_j,D_j\le10^9.

Examples

Input 1

20
2
3 2
1 3
3
3 1
4 1
5 1

Output 1

13

Explanation

Group 1 can pick 9 by second 12 and 11 by second 13. Group 2 can open 9 by second 6 and 12 by second 7. Either 10 or 11 coconuts gives transition time 13.