#P1912A. Accumulator Apex

    ID: 8889 Type: RemoteJudge 3000ms 1024MiB Tried: 0 Accepted: 0 Difficulty: 6 Uploaded By: Tags>implementationsortings*1800

Accumulator Apex

No submission language available for this problem.

Description

Allyn is playing a new strategy game called "Accumulator Apex". In this game, Allyn is given the initial value of an integer xx, referred to as the accumulator, and kk lists of integers. Allyn can make multiple turns. On each turn, Allyn can withdraw the leftmost element from any non-empty list and add it to the accumulator xx if the resulting xx is non-negative. Allyn can end the game at any moment. The goal of the game is to get the largest possible value of the accumulator xx. Please help Allyn find the largest possible value of the accumulator xx they can get in this game.

The first line of the input contains two integers xx and kk (0x109,1k1050 \leq x \leq 10^9, 1 \leq k \leq 10^5) — the initial value of the accumulator xx and the number of lists. The next kk lines contain the description of lists: an integer lil_i (li1l_i \ge 1) followed on the same line by lil_i elements of the list in the order from left to right. Each element of lists does not exceed 10910^9 by the absolute value, and the total size of all lists does not exceed 10510^5.

The sole line of the output should contain the largest value of the accumulator xx Allyn can get.

Input

The first line of the input contains two integers xx and kk (0x109,1k1050 \leq x \leq 10^9, 1 \leq k \leq 10^5) — the initial value of the accumulator xx and the number of lists. The next kk lines contain the description of lists: an integer lil_i (li1l_i \ge 1) followed on the same line by lil_i elements of the list in the order from left to right. Each element of lists does not exceed 10910^9 by the absolute value, and the total size of all lists does not exceed 10510^5.

Output

The sole line of the output should contain the largest value of the accumulator xx Allyn can get.

Sample Input 1

1 3
2 -1 2
2 -2 3
2 -3 4

Sample Output 1

4

Sample Input 2

1 2
3 -1 -1 4
4 1 -3 -4 8

Sample Output 2

4

Note

In the first input, we start with x=1x = 1. Then, we can take the first integer from the first list and get x=0x = 0 — adding the next integer 22 from the first list we get x=2x = 2. After that, we can add the integers from the second list and obtain x=3x = 3. Finally, we can add the integers from the third list and obtain x=4x = 4.

In the second input, we can add the first integer from the second list and get x=2x = 2. Then, by adding the elements from the first list, we get x=4x = 4. We cannot add more integers to increase xx.