#include <iostream>
#include <vector>
#include <algorithm>
#include <deque>
using namespace std;
const int N = 3000 + 5;
int t[N], sorted[N], n;
bool unsorted() {
for (int i = 1; i <= n; i++) {
if (t[i] < t[i-1]) {
return true;
}
}
return false;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n;
vector<int> tmp{0};
for (int i = 1; i <= n; i++) {
cin >> t[i];
tmp.push_back(t[i]);
}
sort(tmp.begin(), tmp.end());
for (int i = 1; i <= n; i++) {
sorted[tmp[i]] = i;
}
vector<deque<int>> rounds;
while (unsorted()) {
vector<bool> visited(N, false);
deque<int> round;
for (int i = 1; i <= n; i++) {
if (!visited[i] && !visited[sorted[t[i]]] && sorted[t[i]] != i) {
visited[i] = true;
visited[sorted[t[i]]] = true;
round.push_front(i);
round.push_back(sorted[t[i]]);
}
}
int p = round.size();
for (int i = 0; 2*i < p; i++) {
swap(t[round[i]], t[round[p-i-1]]);
}
rounds.push_back(round);
}
int r = rounds.size();
cout << r << '\n';
for (deque<int> Q : rounds) {
int p = Q.size();
cout << p << '\n';
for (int i : Q) {
cout << i << ' ';
}
cout << '\n';
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | #include <iostream> #include <vector> #include <algorithm> #include <deque> using namespace std; const int N = 3000 + 5; int t[N], sorted[N], n; bool unsorted() { for (int i = 1; i <= n; i++) { if (t[i] < t[i-1]) { return true; } } return false; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n; vector<int> tmp{0}; for (int i = 1; i <= n; i++) { cin >> t[i]; tmp.push_back(t[i]); } sort(tmp.begin(), tmp.end()); for (int i = 1; i <= n; i++) { sorted[tmp[i]] = i; } vector<deque<int>> rounds; while (unsorted()) { vector<bool> visited(N, false); deque<int> round; for (int i = 1; i <= n; i++) { if (!visited[i] && !visited[sorted[t[i]]] && sorted[t[i]] != i) { visited[i] = true; visited[sorted[t[i]]] = true; round.push_front(i); round.push_back(sorted[t[i]]); } } int p = round.size(); for (int i = 0; 2*i < p; i++) { swap(t[round[i]], t[round[p-i-1]]); } rounds.push_back(round); } int r = rounds.size(); cout << r << '\n'; for (deque<int> Q : rounds) { int p = Q.size(); cout << p << '\n'; for (int i : Q) { cout << i << ' '; } cout << '\n'; } } |
English