#P3207. [HNOI2010] 物品调度

[HNOI2010] 物品调度

Description

Finding a job is not easy. Lostmonkey finally managed to get an entry-level assembly line operator position at fsk. There are nn positions on the line, numbered from 00 to n1n - 1. Initially, position 00 is empty, and each other position ii holds a box numbered ii. Lostmonkey needs to rearrange these boxes according to the following rules.

The rules are determined by five numbers, q,p,m,d,sq, p, m, d, s, where ss is the final position of the empty slot.

First, generate a sequence cc with c0=0c_0=0, and ci+1=(ci×q+p)modmc_{i+1}=(c_i\times q+p)\bmod m.

Next, starting from the first box, generate the final position posipos_i for each box in order: posi=(ci+d×xi+yi)modnpos_i=(c_i+d\times x_i+y_i)\bmod n, where xi,yix_i, y_i are non-negative integers chosen by you so that the ii-th box does not share the same position as any previous box, and posipos_i must not be ss.

If there are multiple sequences x,yx, y that satisfy the requirements, you must choose the one with the lexicographically smallest yy. If yy is the same, choose the lexicographically smallest xx. In this way, you obtain the final positions for all boxes. Each move allows you to move any box into the empty slot; after moving, the original position of that box becomes the empty slot.

Find the minimum number of moves required to move all boxes to their final positions.

Input Format

The first line contains an integer tt, the number of test cases.

Then follow tt lines. Each line contains six numbers, n,s,q,p,m,dn, s, q, p, m, d, as described above.

Output Format

For each test case, output one number on a single line, the minimum number of moves.

1
8 3 5 2 7 4
6

Hint

[Sample Explanation]

The final positions of boxes 11 through 77 are: [2,5,6,4,1,0,7][2, 5, 6, 4, 1, 0, 7].

Constraints

  • For 30%30\% of the testdata, n100n \le 100.
  • For 100%100\% of the testdata, 1t201 \le t \le 20, 1n1000001 \le n \le 100000, 0s<n0 \le s < n.
  • All other numbers are positive integers not exceeding 100000100000.

Additional Hint

The computation may exceed the integer range.

Translated by ChatGPT 5