#include<iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
vector<int> tab, st;
set<int> us;
vector<pair<int,vector<pair<int, int>>>> wypis;
int main() {
bool left;
int n, el, zamian, ind;
cin >> n;
for (int i=0; i < n; i++) {
cin >> el;
tab.push_back(el);
st.push_back(el);
}
sort(st.begin(),st.end());
left = true;
zamian = 0;
while (left) {
left = false;
vector<pair<int, int>> wyn;
us.clear();
for (int i=0; i<n; i++) {
if (tab[i]!=st[i]) {
ind = find(st.begin(), st.end(), tab[i]) - st.begin();
if ((us.count(ind)) || (us.count(i))) {
left = true;
} else {
wyn.push_back(make_pair(i+1, ind+1));
us.insert(ind);
us.insert(i);
swap(tab[i], tab[ind]);
}
}
}
if (wyn.size()) {
wypis.push_back(make_pair(wyn.size()*2, wyn));
zamian+=1;
}
}
cout << zamian << "\n";
for (auto s: wypis) {
cout << s.first << "\n";
for (auto v:s.second)
cout << v.first << " ";
for (int i=s.second.size()-1; i >=0; i--)
cout << s.second[i].second << " ";
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 | #include<iostream> #include <vector> #include <set> #include <algorithm> using namespace std; vector<int> tab, st; set<int> us; vector<pair<int,vector<pair<int, int>>>> wypis; int main() { bool left; int n, el, zamian, ind; cin >> n; for (int i=0; i < n; i++) { cin >> el; tab.push_back(el); st.push_back(el); } sort(st.begin(),st.end()); left = true; zamian = 0; while (left) { left = false; vector<pair<int, int>> wyn; us.clear(); for (int i=0; i<n; i++) { if (tab[i]!=st[i]) { ind = find(st.begin(), st.end(), tab[i]) - st.begin(); if ((us.count(ind)) || (us.count(i))) { left = true; } else { wyn.push_back(make_pair(i+1, ind+1)); us.insert(ind); us.insert(i); swap(tab[i], tab[ind]); } } } if (wyn.size()) { wypis.push_back(make_pair(wyn.size()*2, wyn)); zamian+=1; } } cout << zamian << "\n"; for (auto s: wypis) { cout << s.first << "\n"; for (auto v:s.second) cout << v.first << " "; for (int i=s.second.size()-1; i >=0; i--) cout << s.second[i].second << " "; cout << "\n"; } } |
English