#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int const N = 3e3 + 9;
int n;
int tab[N], tab2[N];
bool odw[N]; //ktore to przejscie
int poz[N];
int kon[N][N], pocz[N][N];
int rozmiark[N], rozmiarp[N];
void solve() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> tab[i];
tab2[i] = tab[i];
}
sort(tab2 + 1, tab2 + n + 1);
for (int i = 1; i <= n; i++)
poz[tab2[i]] = i;
int zle = 0;
for (int i = 1; i <= n; i++) {
if (poz[tab[i]] != i)
zle++;
}
if (zle == 0) {
cout << "0\n";
return;
}
int ile = 0;
while (zle > 0) {
for (int i = 1; i <= n; i++) {
if (poz[tab[i]] != i && odw[tab[poz[tab[i]]]] == false) {
kon[ile][rozmiark[ile]] = poz[tab[i]];
pocz[ile][rozmiarp[ile]] = i;
rozmiark[ile]++; rozmiarp[ile]++;
odw[tab[i]] = true;
odw[tab[poz[tab[i]]]] = true;
if (poz[tab[poz[tab[i]]]] == i) zle -= 2;
else zle--;
swap(tab[i], tab[poz[tab[i]]]);
}
}
for (int i = 1; i <= n; i++)
odw[tab[i]] = false;
ile++;
}
cout << ile << "\n";
for (int i = 0; i < ile; i++) {
cout << rozmiark[i] + rozmiarp[i] << "\n";
for (int j = 0; j < rozmiarp[i]; j++)
cout << pocz[i][j] << " ";
for (int j = rozmiark[i] - 1; j >= 0; j--)
cout << kon[i][j] << " ";
cout << "\n";
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
}
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 60 61 62 63 64 65 66 67 68 69 70 71 72 | #include <iostream> #include <algorithm> #include <vector> using namespace std; int const N = 3e3 + 9; int n; int tab[N], tab2[N]; bool odw[N]; //ktore to przejscie int poz[N]; int kon[N][N], pocz[N][N]; int rozmiark[N], rozmiarp[N]; void solve() { cin >> n; for (int i = 1; i <= n; i++) { cin >> tab[i]; tab2[i] = tab[i]; } sort(tab2 + 1, tab2 + n + 1); for (int i = 1; i <= n; i++) poz[tab2[i]] = i; int zle = 0; for (int i = 1; i <= n; i++) { if (poz[tab[i]] != i) zle++; } if (zle == 0) { cout << "0\n"; return; } int ile = 0; while (zle > 0) { for (int i = 1; i <= n; i++) { if (poz[tab[i]] != i && odw[tab[poz[tab[i]]]] == false) { kon[ile][rozmiark[ile]] = poz[tab[i]]; pocz[ile][rozmiarp[ile]] = i; rozmiark[ile]++; rozmiarp[ile]++; odw[tab[i]] = true; odw[tab[poz[tab[i]]]] = true; if (poz[tab[poz[tab[i]]]] == i) zle -= 2; else zle--; swap(tab[i], tab[poz[tab[i]]]); } } for (int i = 1; i <= n; i++) odw[tab[i]] = false; ile++; } cout << ile << "\n"; for (int i = 0; i < ile; i++) { cout << rozmiark[i] + rozmiarp[i] << "\n"; for (int j = 0; j < rozmiarp[i]; j++) cout << pocz[i][j] << " "; for (int j = rozmiark[i] - 1; j >= 0; j--) cout << kon[i][j] << " "; cout << "\n"; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); solve(); } |
English