#include <iostream> #include <vector> #include <algorithm> #include <map> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); int n; std::cin >> n; std::vector<int> v(n); std::map<int, int> where; std::vector<int> v2(n); for (int i = 0; i < n; i++) { std::cin >> v[i]; where[v[i]] = i; v2[i] = v[i]; } std::sort(v2.begin(), v2.end()); std::vector<std::vector<std::pair<int ,int> >> res; while (v != v2) { std::vector<bool> visited(n, false); std::vector<std::pair<int ,int> > ans; for (int i = 0; i < n; i++) { if (!visited[i] && v[i] != v2[i] && !visited[where[v2[i]]]) { visited[i] = true; visited[where[v2[i]]] = true; ans.push_back({i, where[v2[i]]}); int help = where[v2[i]]; where[v[i]] = where[v2[i]]; where[v2[i]] = i; std::swap(v[i], v[help]); } } res.push_back(ans); } std::cout << res.size() << '\n'; for (auto i : res) { std::cout << 2 * i.size() << '\n'; for (std::pair<int,int> j : i) std::cout << j.first + 1 << " "; for (int j = i.size() - 1; j >= 0; j--) std::cout << i[j].second + 1 << " "; std::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 | #include <iostream> #include <vector> #include <algorithm> #include <map> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); int n; std::cin >> n; std::vector<int> v(n); std::map<int, int> where; std::vector<int> v2(n); for (int i = 0; i < n; i++) { std::cin >> v[i]; where[v[i]] = i; v2[i] = v[i]; } std::sort(v2.begin(), v2.end()); std::vector<std::vector<std::pair<int ,int> >> res; while (v != v2) { std::vector<bool> visited(n, false); std::vector<std::pair<int ,int> > ans; for (int i = 0; i < n; i++) { if (!visited[i] && v[i] != v2[i] && !visited[where[v2[i]]]) { visited[i] = true; visited[where[v2[i]]] = true; ans.push_back({i, where[v2[i]]}); int help = where[v2[i]]; where[v[i]] = where[v2[i]]; where[v2[i]] = i; std::swap(v[i], v[help]); } } res.push_back(ans); } std::cout << res.size() << '\n'; for (auto i : res) { std::cout << 2 * i.size() << '\n'; for (std::pair<int,int> j : i) std::cout << j.first + 1 << " "; for (int j = i.size() - 1; j >= 0; j--) std::cout << i[j].second + 1 << " "; std::cout << '\n'; } } |