#3310. [USACO2013 Nov] Empty Stalls

[USACO2013 Nov] Empty Stalls

Description

Farmer John's new barn consists of a huge circle of NN stalls, numbered 0N10\sim N-1, with stall N1N-1 being adjacent to stall 00.

At the end of each day, FJ's cows arrive back at the barn one by one, each with a preferred stall they would like to occupy. However, if a cow's preferred stall is already occupied by another cow, she scans forward sequentially from this stall until she finds the first unoccupied stall, which she then claims. If she scans past stall N1N-1, she continues scanning from stall 00.

Given the preferred stall of each cow, please determine the smallest index of a stall that remains unoccupied after all the cows have returned to the barn. Notice that the answer to this question does not depend on the order in which the cows return to the barn.

In order to avoid issues with reading huge amounts of input, the input to this problem is specified in a concise format using KK lines each of the form: X Y A BX\ Y\ A\ B.

One of these lines specifies the preferred stall for X×YX\times Y total cows: X cows prefer each of the stalls f(1)f(Y)f(1)\sim f(Y), where f(i)=(A×i+B)modNf(i)=(A\times i+B)\bmod N. Do not forget the standard memory limit of 64MB64\text{MB} for all problems.

Input

Line 1: Two space-separated integers: N,KN,K.

Lines 21+K2\sim 1+K: Each line contains integers X,Y,A,BX,Y,A,B, interpreted as above. The total number of cows specified by all these lines will be at most N1N-1. Cows can be added to the same stall by several of these lines.

Output

Line 11: The minimum index of an unoccupied stall.

10 3
3 2 2 4
2 1 0 1
1 1 1 7 
5 

Sample Explain 1

There are 1010 stalls in the barn, numbered 090\sim 9. The second line of input states that 33 cows prefer stall (2×1+4)mod10=6(2\times 1+4)\bmod 10=6, and 33 cows prefer stall (2×2+4)mod10=8(2\times 2+4)\bmod 10=8. The third line states that 22 cows prefer stall (0×1+1)mod10=1(0\times 1+1)\bmod 10=1. Line four specifies that 11 cow prefers stall (1×1+7)mod10=8(1\times 1+7)\bmod 10=8 (so a total of 44 cows prefer this stall).

All stalls will end up occupied except stall 55.

Data scale and Agreement

For 100%100\% data, 2N3×1062\leq N\leq 3\times 10^6, 1K1041\leq K\leq 10^4, 0A,B1090\leq A,B\leq 10^9.

Source

Gold