Editorial
For two values , orient an edge if appears before in at least two of the three permutations. Exactly one direction is chosen for every pair, so this is a tournament. A good permutation exists exactly when there is a linear order consistent with every edge of this tournament, which is equivalent to the tournament being transitive.
For every value , define
Thus, is the indegree of in the tournament.
In a transitive tournament, the indegrees are exactly . Conversely, if all are distinct, then because every indegree lies between and , the set of indegrees is exactly . The vertex of indegree is before every other vertex. Removing it leaves a tournament whose indegrees are again , so induction shows that the tournament is transitive. Therefore, a good permutation exists if and only if all values are distinct.
It remains to compute the initial efficiently. Let be the position of in permutation . For two permutations , define
and let be the number of values that appear before in all three permutations. If a fixed appears before in exactly of the three permutations, it contributes to and contributes once to only when . Hence
Each can be computed in by scanning one permutation and inserting positions in the other permutation into a Fenwick tree. Computing is a three-dimensional dominance counting problem on the three positions. Sort by the position in , then use CDQ divide and conquer with a Fenwick tree to obtain all values in .
Now consider a query. Suppose the two adjacent values in the selected permutation are , with before before the swap. Swapping adjacent elements changes the relative order of only the pair in that permutation. Therefore, only the tournament edge between and can possibly change.
If the other two permutations agree on the order of , the majority result is already fixed and nothing changes. If the other two permutations disagree, then the edge is before the swap and becomes after the swap. Only in this case, update
Maintain the frequency of each possible indegree , together with the number of indegree values whose frequency is at least . This number is exactly when all are distinct. At most two indegrees change in one query, so this maintenance takes time. Also maintain the current position arrays of the three permutations, allowing the order comparison in the other two permutations to be done in .
The initialization takes time, every query takes time, and the memory usage is . Thus the total time complexity is .
Solution written by GPT5.6