1#include <bits/stdc++.h>2usingnamespace std;34int n;5vector<int> arr;67// put the right numbers after 18vector<int>solve1(vector<int> a) {9 a.insert(a.end(), a.begin(), a.end());10int idx1 =find(a.begin(), a.end(), 1) - a.begin();11vector<int>b(a.begin() + idx1, a.end());12for (int i =0; i < n; i++) {13if (b[i] != i +1) {14int miss =find(b.begin(), b.end(), i +1) - b.begin();15swap(b[i], b[miss]);16break;17 }18 }19 b.resize(n);20return b;21}2223// move the 1 in front of the 224vector<int>solve2(vector<int> a) {25int pos2 =find(a.begin(), a.end(), 2) - a.begin();26int pos1 =find(a.begin(), a.end(), 1) - a.begin();27// swap 1 into the slot just before 228swap(a[(pos2 -1+ n) % n], a[pos1]);29// rotate so that 1 is at front30int start =find(a.begin(), a.end(), 1) - a.begin();31vector<int> b;32 b.reserve(n);33for (int i =0; i < n; i++)34 b.push_back(a[(start + i) % n]);35return b;36}37// if 1 is already right after 2, just swap them38vector<int>solve3(vector<int> a) {39int pos2 =find(a.begin(), a.end(), 2) - a.begin();40vector<int>b(n);41for (int i =0; i < n; i++)42 b[i] = a[(pos2 + i) % n];43if (b[1] ==1)44swap(b[0], b[1]);45return b;46}4748intmain() {49 ios::sync_with_stdio(0);50 cin.tie(0);51 cin >> n;52 arr.resize(n);53for (int i =0; i < n; i++)54 cin >> arr[i];55if (n ==1) {56 cout <<"1"<<"\n";57return0;58 }59auto a1 =solve1(arr);60auto a2 =solve2(arr);61auto a3 =solve3(arr);62// pick lexicographically smallest63vector<int> ans =min(min(a1, a2), a3);64for (int i =0; i < n; i++)65 cout << ans[i] << (i +1== n ?'\n':' ');66return0;67}68
☕
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.