Official

C - IPFL Editorial by en_translator


If you process the queries just as what the problem statement says, the complexity can be \(\Theta(QN)\) (if, for example, they are all \(T_i = 2\)), which does not finish in time limit.
Therefore, we have to process the cases where \(T_i = 2\) fast.
Here, let us hold a variable \(t\) that indicates whether the first \(N\) characters and the last \(N\) characters are swapped or not (initialized with false).
For a query of \(T_i = 2\), we can just flip the parity of \(t\).
For a query of \(T_i = 1\), if \(t\) is false, we can directly swap the \(A_i\)-th and the \(B_i\)-th characters.
If \(t\) is true, the stored \(S\) is the actual \(S\) with the first and the last \(N\) characters swapped. The \(x\)-th character in the actual \(S\) correspond to, the \(x+N\)-th character of the stored \(S\) if \(x \le N\), or the \(x-N\)-th character of the stored \(S\) if \(x \gt N\).
Therefore, we can swap the stored \(S\) after translating \(A_i\) and \(B_i\) in the way described above.

After processing all the queries, we can reverse the first and the last \(N\) characters of \(S\) before outputting if \(t\) is true at last, or output as it is if \(t\) is false.
The complexity of this solution is \(O(N + Q)\), so it easily fit to the execution time limit.

posted:
last update: