Empty Stalls

No attempts yetTime limit1sMemory limit128 MB

Problem

Farmer John's new barn is a ring of NN stalls (2N3×1062 \le N \le 3 \times 10^6) numbered 00 through N1N-1, and stall N1N-1 sits next to stall 00.

At the end of each day the cows come back to the barn one at a time, and every cow has one stall she wants. If that stall is already taken, she looks at the stalls in increasing order of number, starting from the one she wants, and claims the first empty stall she meets. Once she passes stall N1N-1 she keeps looking from stall 00.

Given the preferred stall of every cow, find the smallest number among the stalls that are still empty after all the cows are back. The answer does not depend on the order in which the cows return.

To keep the input from growing too large, the preferred stalls are given in compressed form on KK lines (1K1041 \le K \le 10^4). Each line has the form X Y A B.

One such line describes the stalls wanted by X×YX \times Y cows. With f(i)=(A×i+B)modNf(i) = (A \times i + B) \bmod N, there are XX cows that want each of the stalls f(1),f(2),,f(Y)f(1), f(2), \dots, f(Y). Both AA and BB are between 00 and 10910^9.

Input

  • Line 1: two space-separated integers NN and KK.
  • Lines 2 through 1+K1+K: each line contains the integers XX, YY, AA, BB described above. Together these lines describe at most N1N-1 cows. Several lines may add cows to the same stall.

Output

  • Line 1: print the smallest number of a stall that stays empty.

Hint

The barn in the sample has 10 stalls numbered 00 through 99. The line 3 2 2 4 means 3 cows want stall (2×1+4)mod10=6(2 \times 1 + 4) \bmod 10 = 6 and 3 cows want stall (2×2+4)mod10=8(2 \times 2 + 4) \bmod 10 = 8. The line 2 1 0 1 means 2 cows want stall (0×1+1)mod10=1(0 \times 1 + 1) \bmod 10 = 1, and the line 1 1 1 7 means 1 cow wants stall (1×1+7)mod10=8(1 \times 1 + 7) \bmod 10 = 8, so 4 cows want stall 8 in total. All 9 cows fit, and stall 5 is the only one left empty.