For convenience, use indices from to , with every index interpreted modulo .
Applying the operation twice at the same starting position cancels out. Therefore it is enough to let denote whether the operation starting at is used an odd number of times.
For position to become 0, we need
XORing the equations for two adjacent positions gives
Let , , and . The permutation splits the indices into exactly cycles, each of length .
For a residue class , define
The XOR of all difference equations in one cycle is . Thus the difference equations are consistent if and only if
Write one cycle in the order
Choose the canonical solution
Let be the number of ones among the values in cycle .
Considering only the difference equations, every cycle has one free variable that flips the entire cycle. The cost is for and for . Hence the minimum cost for the difference equations alone is
The difference equations used only differences of the original equations, so one original equation must still be enforced. For position , define the residual
We need .
A length- window contains exactly indices from every residue class.
If is even, flipping an entire cycle does not change . Therefore is impossible, while for the answer is .
If is odd, each toggles once, so
Let the cheaper choice for each cycle be
If , the answer is . Otherwise one cycle must take the opposite choice, at an extra cost of
Now consider a query. Flipping toggles only and , and it toggles only . Thus the condition that all are equal can be checked in by maintaining the number of classes with .
Inside a cycle, toggling with flips the suffix
of the canonical solution. When , is used only by the cycle-closing consistency equation, so the canonical values themselves do not change.
Concatenate all cycles in cycle order into one array of length . A lazy segment tree supports range flips and range-one-count queries. Every query needs at most two suffix flips and recomputation of for at most two affected cycles.
Whenever a changes, maintain the following values.
The residual can also be updated instead of recomputed. Precompute , the parity of the number of positions in the affected canonical suffix for that lie in the length- window of . For a cycle root, . A query at updates
Therefore the answer to each query is:
-1 if the values are not all equal;-1 when , otherwise ;Preprocessing each test case takes time, and each query takes time. The total complexity is with memory.
Solution written by GPT5.6