AlgoPlus v0.1.0
Loading...
Searching...
No Matches
minimum_swaps.h
1#ifndef MINIMUM_SWAPS_H
2#define MINIMUM_SWAPS_H
3
4#ifdef __cplusplus
5#include <algorithm>
6#include <cassert>
7#include <iostream>
8#include <map>
9#include <vector>
10#endif
11
19int minimum_swaps(std::vector<int>& a, std::vector<int>& b) {
20 assert(a.size() == b.size());
21 int n = int(a.size());
22 auto solve = [&](std::vector<int>& arr) -> int {
23 std::vector<std::pair<int, int>> positions;
24 for (int i = 0; i < n; i++) {
25 int pos = i, value = arr[i];
26 positions.push_back({value, pos});
27 }
28
29 std::sort(positions.begin(), positions.end());
30
31 std::vector<bool> visited(n, false);
32
33 int min_swaps = 0;
34 for (int i = 0; i < n; i++) {
35 if (visited[i] || positions[i].second == i) {
36 continue;
37 }
38
39 int cycle_size = 0, j = i;
40 while (!visited[j]) {
41 visited[j] = 1;
42 j = positions[j].second;
43 cycle_size++;
44 }
45
46 min_swaps += (cycle_size - 1);
47 }
48
49 return min_swaps;
50 };
51
52 std::map<int, int> m;
53 for (int i = 0; i < n; i++) {
54 m[b[i]] = i;
55 }
56
57 for (int i = 0; i < n; i++) {
58 b[i] = m[a[i]];
59 }
60
61 return solve(b);
62}
63
64#endif