Farmer John's new barn is a ring of N stalls (2≤N≤3×106) numbered 0 through N−1, and stall N−1 sits next to stall 0.
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 N−1 she keeps looking from stall 0.
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 K lines (1≤K≤104). Each line has the form X Y A B.
One such line describes the stalls wanted by X×Y cows. With f(i)=(A×i+B)modN, there are X cows that want each of the stalls f(1),f(2),…,f(Y). Both A and B are between 0 and 109.
The barn in the sample has 10 stalls numbered 0 through 9. The line 3 2 2 4 means 3 cows want stall (2×1+4)mod10=6 and 3 cows want stall (2×2+4)mod10=8. The line 2 1 0 1 means 2 cows want stall (0×1+1)mod10=1, and the line 1 1 1 7 means 1 cow wants stall (1×1+7)mod10=8, so 4 cows want stall 8 in total. All 9 cows fit, and stall 5 is the only one left empty.