-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.h
41 lines (38 loc) · 1 KB
/
solution.h
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
/*
Code generated by https://github.com/goodstudyqaq/leetcode-local-tester
*/
#if __has_include("../utils/cpp/help.hpp")
#include "../utils/cpp/help.hpp"
#elif __has_include("../../utils/cpp/help.hpp")
#include "../../utils/cpp/help.hpp"
#else
#define debug(...) 42
#endif
class Solution {
public:
int minSwapsCouples(vector<int>& row) {
int n = row.size();
vector<int> to(n);
for (int i = 0; i < n; i += 2) {
int u = row[i], v = row[i + 1];
to[u] = v;
to[v] = u;
}
vector<int> vis(n);
int res = 0;
for (int i = 0; i < n; i++) {
if (vis[i] || vis[i + (i % 2 ? -1 : 1)]) continue;
int now = i;
int cir = 0;
do {
vis[now] = 1;
cir++;
int love = now % 2 ? now - 1 : now + 1;
int go = to[love];
now = go;
} while (now != i);
res += cir - 1;
}
return res;
}
};