-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathM0019.cpp
More file actions
60 lines (49 loc) · 1.02 KB
/
M0019.cpp
File metadata and controls
60 lines (49 loc) · 1.02 KB
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
/*
Problem Code: https://www.hackerrank.com/challenges/lilys-homework/problem
*/
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
int minimumSwaps(int n, vector< pair<int, int> > &brr) {
int swaps = 0;
vector<bool> visited(n);
for (int i = 0; i < n; i++) {
if (visited[i] || brr[i].second == i) {
continue;
}
int cycle_len, j;
cycle_len = 0;
j = i;
while (!visited[j]) {
visited[j] = true;
j = brr[j].second;
cycle_len++;
}
swaps += cycle_len - 1;
}
return swaps;
}
int lilysHomework(int n, vector<int> &arr) {
int swaps = 0;
vector< pair<int, int> > brr(n);
for (int i = 0; i < n; i++)
brr[i] = {arr[i], i};
// Try Ascending
sort(brr.begin(), brr.end());
swaps = minimumSwaps(n, brr);
// Try Descending
sort(brr.rbegin(), brr.rend());
swaps = min(minimumSwaps(n, brr), swaps);
return swaps;
}
int main() {
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++)
cin >> arr[i];
cout << lilysHomework(n, arr);
return 0;
}