#include<iostream> #include<vector> #include<utility> #include<algorithm> using namespace std; int main(){ //ios::sync_with_stdio(false); //cin.tie(NULL); cout.tie(NULL); int n; cin>>n; vector<pair<int,int>>tab(n); int x; for(int i = 0;i<n;++i){ cin>>x; tab[i]={x,i}; } sort(tab.begin(),tab.end()); vector<bool>good; int left = n; for(int i = 0;i<n;++i){ if(tab[i].second==i){ --left; } } vector<vector<int>>odp; while(left>0){ //cout<<left<<endl; good.clear(); good.resize(n,false); odp.push_back({}); for(int i = 0;i<n;++i){ if(tab[i].second!=i && !good[i] && !good[tab[i].second]){ good[i]=true; good[tab[i].second]=true; --left; if(tab[tab[i].second].second==i) --left; odp[odp.size()-1].push_back(i); odp[odp.size()-1].push_back(tab[i].second); swap(tab[i],tab[tab[i].second]); } } } cout<<odp.size()<<endl; for(int i = odp.size()-1;i>=0;--i){ cout<<odp[i].size()<<endl; for(int j = 0;j<odp[i].size();j+=2){ cout<<odp[i][j]+1<<" "; } for(int j = odp[i].size()-1;j>=1;j-=2){ cout<<odp[i][j]+1<<" "; } 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 | #include<iostream> #include<vector> #include<utility> #include<algorithm> using namespace std; int main(){ //ios::sync_with_stdio(false); //cin.tie(NULL); cout.tie(NULL); int n; cin>>n; vector<pair<int,int>>tab(n); int x; for(int i = 0;i<n;++i){ cin>>x; tab[i]={x,i}; } sort(tab.begin(),tab.end()); vector<bool>good; int left = n; for(int i = 0;i<n;++i){ if(tab[i].second==i){ --left; } } vector<vector<int>>odp; while(left>0){ //cout<<left<<endl; good.clear(); good.resize(n,false); odp.push_back({}); for(int i = 0;i<n;++i){ if(tab[i].second!=i && !good[i] && !good[tab[i].second]){ good[i]=true; good[tab[i].second]=true; --left; if(tab[tab[i].second].second==i) --left; odp[odp.size()-1].push_back(i); odp[odp.size()-1].push_back(tab[i].second); swap(tab[i],tab[tab[i].second]); } } } cout<<odp.size()<<endl; for(int i = odp.size()-1;i>=0;--i){ cout<<odp[i].size()<<endl; for(int j = 0;j<odp[i].size();j+=2){ cout<<odp[i][j]+1<<" "; } for(int j = odp[i].size()-1;j>=1;j-=2){ cout<<odp[i][j]+1<<" "; } cout<<endl; } } |