(Analysis by Benjamin Qi)

For full credit, we need to do better than just simulating the $K$ processes individually.

For each $i$ compute the minimum positive integer $X$ such that after $X$ repetitions of the process, the cow with label $i$ is again the cow that is $i$-th from the left. Then, for that cow, we can consider the remainder when $K$ is divided by $X$ rather than $K$ itself. As the remainder is always less than $N$, this runs in $O(N^2)$. See the silver analysis for how to do it in $O(N)$.

#include "bits/stdc++.h"
using namespace std;
void setIO(string s) {
	ios_base::sync_with_stdio(0); cin.tie(0); 
int N,K,A1,A2,B1,B2,res[101];
int nex(int x) {
	if (A1 <= x && x <= A2) x = A1+A2-x;
	if (B1 <= x && x <= B2) x = B1+B2-x;
	return x;
int main() {
	cin >> N >> K >> A1 >> A2 >> B1 >> B2;
	for (int i = 1; i <= N; ++i) {
		int p = 1, cur = nex(i);
		while (cur != i) {
			p ++;
			cur = nex(cur);
		int k = K%p;
		for (int j = 0; j < k; ++j) cur = nex(cur);
		res[cur] = i; // position of cow i after k steps is cur
	for (int i = 1; i <= N; ++i) cout << res[i] << "\n";

Alternatively, we can just hope that the permutation returns to its original state quickly. If it repeats after $S$ steps, then it suffices to simulate only $K\pmod{S}$ steps. It can be verified (by exhaustive search) that the maximum possible value of $S$ for $N\le 100$ is $29640$ for $A=(1,94)$ and $B=(2,98)$. Thus, the bounds were small enough to allow a solution that runs in $O(NS)$ time to run in time.

Nick Wu's code:

import java.io.*;
import java.util.*;
public class Solution {
  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader("swap.in"));
    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("swap.out")));
    StringTokenizer st = new StringTokenizer(br.readLine());
    int n = Integer.parseInt(st.nextToken());
    int k = Integer.parseInt(st.nextToken());
    st = new StringTokenizer(br.readLine());
    int a1 = Integer.parseInt(st.nextToken())-1;
    int a2 = Integer.parseInt(st.nextToken())-1;
    st = new StringTokenizer(br.readLine());
    int b1 = Integer.parseInt(st.nextToken())-1;
    int b2 = Integer.parseInt(st.nextToken())-1;
    int cycleSize = 0;
    int[] l = new int[n];
    for(int i = 0; i < n; i++) l[i] = i;
    boolean sorted = true;
    do {
      reverse(l, a1, a2);
      reverse(l, b1, b2);
      sorted = true;
      for(int i = 0; sorted && i < n; i++) sorted = l[i] == i;
    k %= cycleSize;
    for(int i = 0; i < n; i++) l[i] = i+1;
    for(int i = 0; i < k; i++) {
      reverse(l, a1, a2);
      reverse(l, b1, b2);
    for(int val: l) pw.println(val);
  private static void reverse(int[] l, int a, int b) {
    while(a < b) {
      int t = l[a];
      l[a] = l[b];
      l[b] = t;