#include <bits/stdc++.h> using namespace std; int x,licznik,counter; bool odw[3007]; vector <pair<int, int> > v; stack <int> koniec[3007]; queue <int> poczatek[3007]; void find_path(int x, int y){ if(x==y) return; if(odw[v[x].second] == 0 && odw[v[y].second] == 0){ int temp, temp2; for(int i=0; i<v.size();i++) { if(v[i].second==x) temp = i; } for(int i=0;i<v.size();i++) { if(v[y].second==i) temp2 = i; } poczatek[counter].push(v[x].second); koniec[counter].push(v[y].second); swap(v[x].second, v[y].second); odw[v[x].second] = 1; odw[v[y].second] = 1; find_path(temp, temp2); } } int main() { int n; cin>>n; for(int i=0;i<n;i++){ cin>>x; v.push_back({x,i}); } sort(v.begin(), v.end()); while(licznik!=n){ licznik = 0; ++counter; for(int i=0;i<v.size();++i){ if(v[i].second == i){ ++licznik; } if(v[i].second != i){ if(odw[v[i].second] == 0){ find_path(i, v[i].second); } } } for(int i=0;i<=3001;++i){ odw[i] = 0; } } cout<<counter-1<<endl; for(int i=1;i<=counter-1;++i){ cout<<koniec[i].size() * 2<<endl; while(!poczatek[i].empty()){ cout<<poczatek[i].front()+1<<" "; poczatek[i].pop(); } while(!koniec[i].empty()){ cout<<koniec[i].top()+1<<" "; koniec[i].pop(); } cout<<endl; } }
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 73 | #include <bits/stdc++.h> using namespace std; int x,licznik,counter; bool odw[3007]; vector <pair<int, int> > v; stack <int> koniec[3007]; queue <int> poczatek[3007]; void find_path(int x, int y){ if(x==y) return; if(odw[v[x].second] == 0 && odw[v[y].second] == 0){ int temp, temp2; for(int i=0; i<v.size();i++) { if(v[i].second==x) temp = i; } for(int i=0;i<v.size();i++) { if(v[y].second==i) temp2 = i; } poczatek[counter].push(v[x].second); koniec[counter].push(v[y].second); swap(v[x].second, v[y].second); odw[v[x].second] = 1; odw[v[y].second] = 1; find_path(temp, temp2); } } int main() { int n; cin>>n; for(int i=0;i<n;i++){ cin>>x; v.push_back({x,i}); } sort(v.begin(), v.end()); while(licznik!=n){ licznik = 0; ++counter; for(int i=0;i<v.size();++i){ if(v[i].second == i){ ++licznik; } if(v[i].second != i){ if(odw[v[i].second] == 0){ find_path(i, v[i].second); } } } for(int i=0;i<=3001;++i){ odw[i] = 0; } } cout<<counter-1<<endl; for(int i=1;i<=counter-1;++i){ cout<<koniec[i].size() * 2<<endl; while(!poczatek[i].empty()){ cout<<poczatek[i].front()+1<<" "; poczatek[i].pop(); } while(!koniec[i].empty()){ cout<<koniec[i].top()+1<<" "; koniec[i].pop(); } cout<<endl; } } |