Echoing Permutation#13045

Echoing Permutation (Editorial)

Solution

Let

m=n+1.

Define

P_i=p_1p_2\dots p_i \pmod m,

and let

P_0=1.

At position , we need to choose an unused value p_i such that

P_{i-1}p_i\equiv b_i \pmod m.

Let

g=\gcd(P_{i-1},m).

The congruence

P_{i-1}x\equiv b_i \pmod m

has a solution if and only if

g\mid b_i.

If this condition does not hold, there is no valid permutation.

Otherwise, define

M=\frac{m}{g}.

After dividing the congruence by , we get

\frac{P_{i-1}}{g}p_i \equiv \frac{b_i}{g} \pmod M.

Also,

\gcd\left(\frac{P_{i-1}}{g},M\right)=1.

Therefore, \frac{P_{i-1}}{g} has a multiplicative inverse modulo .

Hence, p_i must satisfy exactly one residue condition

p_i\equiv r\pmod M,

where

r= \frac{b_i}{g} \left(\frac{P_{i-1}}{g}\right)^{-1} \pmod M.

Thus, at every step we only need to find an unused number from one residue class modulo .

Why any representative works

Suppose

x\equiv y\pmod M.

Since

P_{i-1}=gq

and

m=gM,

we have

P_{i-1}x-P_{i-1}y = gq(x-y).

Because M\mid x-y, it follows that

m\mid P_{i-1}x-P_{i-1}y.

Therefore,

P_{i-1}x\equiv P_{i-1}y\pmod m.

So every number from the required residue class produces exactly the same next prefix product.

Now define

g_i=\gcd(P_i,m)

and

M_i=\frac{m}{g_i}.

Since

P_i=P_{i-1}p_i\pmod m,

we have

g_{i-1}\mid g_i.

Therefore,

M_i\mid M_{i-1}.

Thus, every future modulus divides the current modulus.

So if two values are equal modulo the current , they also remain equal modulo every future modulus.

Therefore, all unused representatives of the current residue class are completely equivalent, and we may choose any of them.

Maintaining unused values

Every possible value of is a divisor of .

For every divisor , group the numbers 1,2,\dots,n by their residue modulo .

For every residue class, keep a pointer to the first candidate that has not yet been checked.

When a residue class is requested, move its pointer while the current value has already been used.

If there is no unused value left in this class, then no valid continuation exists.

Otherwise, choose this value as p_i and mark it as used.

Finally, update

P_i=P_{i-1}p_i\pmod m.

Correctness

At every step, the condition on p_i is equivalent to belonging to exactly one residue class modulo .

Every value from this class produces exactly the required next prefix product.

Since all future moduli divide the current modulus, all representatives of this residue class remain equivalent for all future positions.

Therefore, choosing any unused representative is always safe.

If no unused representative exists, then no unused value can satisfy the current congruence.

Hence, the algorithm constructs a valid permutation exactly when one exists.

Complexity

Let be the number of divisors of .

For every divisor, every value may be processed only a constant number of times.

Therefore, the total complexity is

O(n\tau(m))

time and

O(n\tau(m))

memory.