#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> a(n); map<int, int> scale; for (int i = 0; i < n; i++) { cin >> a[i]; scale[a[i]]; } int last_value = 0; for (auto& [key, value] : scale) { value = last_value++; } for (int i = 0; i < n; i++) { a[i] = scale[a[i]]; } vector<vector<pair<int, int>>> result; vector<bool> visited(n); for (int i = 0; i < n; i++) { if (!visited[i]) { vector<int> cycle; int curr = i; do { visited[curr] = true; cycle.emplace_back(curr); curr = a[curr]; } while (curr != i); if ((int) cycle.size() == 2) { if ((int) result.size() < 1) { result.resize(1); } result[0].emplace_back(cycle[0], cycle[1]); } else if ((int) cycle.size() > 2) { if ((int) result.size() < 2) { result.resize(2); } for (int j = 0; j < (int) cycle.size() / 2; j++) { result[0].emplace_back(cycle[j], cycle[cycle.size() - 1 - j]); } for (int j = 1; j < (int) (cycle.size() + 1) / 2; j++) { result[1].emplace_back(cycle[j], cycle[cycle.size() - j]); } } } } cout << result.size() << '\n'; for (auto vec : result) { cout << vec.size() * 2 << '\n'; for (int i = 0; i < (int) vec.size(); i++) { cout << vec[i].first + 1 << ' '; } for (int i = vec.size() - 1; i >= 0; i--) { cout << vec[i].second + 1 << (i == 0 ? '\n' : ' '); } } return 0; }
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 main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> a(n); map<int, int> scale; for (int i = 0; i < n; i++) { cin >> a[i]; scale[a[i]]; } int last_value = 0; for (auto& [key, value] : scale) { value = last_value++; } for (int i = 0; i < n; i++) { a[i] = scale[a[i]]; } vector<vector<pair<int, int>>> result; vector<bool> visited(n); for (int i = 0; i < n; i++) { if (!visited[i]) { vector<int> cycle; int curr = i; do { visited[curr] = true; cycle.emplace_back(curr); curr = a[curr]; } while (curr != i); if ((int) cycle.size() == 2) { if ((int) result.size() < 1) { result.resize(1); } result[0].emplace_back(cycle[0], cycle[1]); } else if ((int) cycle.size() > 2) { if ((int) result.size() < 2) { result.resize(2); } for (int j = 0; j < (int) cycle.size() / 2; j++) { result[0].emplace_back(cycle[j], cycle[cycle.size() - 1 - j]); } for (int j = 1; j < (int) (cycle.size() + 1) / 2; j++) { result[1].emplace_back(cycle[j], cycle[cycle.size() - j]); } } } } cout << result.size() << '\n'; for (auto vec : result) { cout << vec.size() * 2 << '\n'; for (int i = 0; i < (int) vec.size(); i++) { cout << vec[i].first + 1 << ' '; } for (int i = vec.size() - 1; i >= 0; i--) { cout << vec[i].second + 1 << (i == 0 ? '\n' : ' '); } } return 0; } |