#include <bits/stdc++.h> using namespace std; #define pii pair<int, int> const int N = 3e3+1; int n, h[N], x[N]; bool vis[N], us[N]; vector<pii> mv[3]; void solve(vector<int> c) { if (c.size() <= 1) return; if (c.size() == 2) { mv[1].push_back({c[0], c[1]}); swap(h[c[0]], h[c[1]]); return; } int sz=c.size(); for (int i=0; i<sz/2; ++i) { if (h[c[i]] == c[i]) continue; mv[1].push_back({c[i], c[sz-i-1]}); swap(h[c[i]], h[c[sz-i-1]]); } for (int i=0; i<sz; ++i) { if (h[c[i]] == c[i]) continue; mv[2].push_back({c[i], h[c[i]]}); swap(h[c[i]], h[h[c[i]]]); } } vector<int> cyc; void dfs(int v) { vis[v]=true; cyc.push_back(v); if (!vis[h[v]]) dfs(h[v]); } int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); cin>>n; set<int> s; for (int i=1; i<=n; ++i) { cin>>h[i]; s.insert(h[i]); } int i=1; for (auto u : s) x[u]=i++; for (int i=1; i<=n; ++i) h[i]=x[h[i]]; for (int i=1; i<=n; ++i) { if (vis[i]) continue; dfs(i); solve(cyc); cyc.clear(); } if (mv[1].empty()) { assert(mv[2].empty()); cout<<0<<"\n"; return 0; } if (mv[2].empty()) cout<<1<<"\n"; else cout<<2<<"\n"; for (int i=1; i<=2; ++i) { vector<int> res; for (auto u : mv[i]) res.push_back(u.first); reverse(mv[i].begin(), mv[i].end()); for (auto u : mv[i]) res.push_back(u.second); if (res.empty()) break; cout<<res.size()<<"\n"; for (auto u : res) cout<<u<<" "; 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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | #include <bits/stdc++.h> using namespace std; #define pii pair<int, int> const int N = 3e3+1; int n, h[N], x[N]; bool vis[N], us[N]; vector<pii> mv[3]; void solve(vector<int> c) { if (c.size() <= 1) return; if (c.size() == 2) { mv[1].push_back({c[0], c[1]}); swap(h[c[0]], h[c[1]]); return; } int sz=c.size(); for (int i=0; i<sz/2; ++i) { if (h[c[i]] == c[i]) continue; mv[1].push_back({c[i], c[sz-i-1]}); swap(h[c[i]], h[c[sz-i-1]]); } for (int i=0; i<sz; ++i) { if (h[c[i]] == c[i]) continue; mv[2].push_back({c[i], h[c[i]]}); swap(h[c[i]], h[h[c[i]]]); } } vector<int> cyc; void dfs(int v) { vis[v]=true; cyc.push_back(v); if (!vis[h[v]]) dfs(h[v]); } int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); cin>>n; set<int> s; for (int i=1; i<=n; ++i) { cin>>h[i]; s.insert(h[i]); } int i=1; for (auto u : s) x[u]=i++; for (int i=1; i<=n; ++i) h[i]=x[h[i]]; for (int i=1; i<=n; ++i) { if (vis[i]) continue; dfs(i); solve(cyc); cyc.clear(); } if (mv[1].empty()) { assert(mv[2].empty()); cout<<0<<"\n"; return 0; } if (mv[2].empty()) cout<<1<<"\n"; else cout<<2<<"\n"; for (int i=1; i<=2; ++i) { vector<int> res; for (auto u : mv[i]) res.push_back(u.first); reverse(mv[i].begin(), mv[i].end()); for (auto u : mv[i]) res.push_back(u.second); if (res.empty()) break; cout<<res.size()<<"\n"; for (auto u : res) cout<<u<<" "; cout<<"\n"; } } |