This C++ solution uses permutation exponentiation for USACO 1014 Swapity Swapity Swap. Read the reasoning, inspect the code, or try your own test case below.
1#include <bits/stdc++.h>2usingnamespace std;3intmain(){4 ios::sync_with_stdio(0); cin.tie(0);5intN, M; longlongK;6 cin >>N>>M>>K;7vector<pair<int,int>>seg(M);8for(int i =0; i <M; i++){9intL, R; cin >>L>>R;10 seg[i] = {L, R};11 }12// Build pos after one routine, position newPos holds oldPos13vector<int>pos(N+1);14iota(pos.begin(), pos.end(), 0); // pos[i] = i15for(auto [L, R] : seg){16for(int i =0; i < (R-L+1) /2; i++){17swap(pos[L+ i], pos[R- i]);18 }19 }20// Q's perpose is mapping oldPos to newPos after one routine21vector<int>Q(N+1);22for(int newPos =1; newPos <=N; newPos++){23int oldPos = pos[newPos];24Q[oldPos] = newPos;25 }2627// Binary lifting up[i][v] = Q^(2^i)(v)28constintLOG=60;29vector<vector<int>>up(LOG, vector<int>(N+1));30for(int v =1; v <=N; v++) up[0][v] =Q[v];31for(int i =1; i <LOG; i++){32for(int v =1; v <=N; v++){33 up[i][v] = up[i -1][up[i -1][v]];34 }35 }36// For each label s (initially at position s), jump K times along Q37vector<int>res(N+1, 0);38for(int s =1; s <=N; s++){39int cur = s;40longlong x =K;41for(int i =0; x; i++, x >>=1){42if(x &1) cur = up[i][cur];43 }44 res[cur] = s; // label s ends at position cur45 }46for(int i =1; i <=N; i++) cout << res[i] <<'\n';47return0;48}49
☕
Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.
Python records executed lines and locals automatically. For selected values in any language, add // @trace i, total on its own valid line; Python uses # @trace i, total.
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.
Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.