Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int minSwapsCouples(vector<int>& row) {
- int n = row.size() / 2, res = 0;
- unordered_map<int, int> map;
- unordered_set<int> path, visited;
- for(int i = 0; i < 2 * n; ++i)map[row[i]] = i;
- for(int i = 0; i < 2 * n; ++i)
- if(visited.find(i / 2) == visited.end())
- res += findCycle(row, map, path, visited, i) - 1;
- return res;
- }
- private:
- int findCycle(vector<int>& row, unordered_map<int, int>& map, unordered_set<int>& path, unordered_set<int>& visited, int to)
- {
- int slot = to / 2, next = map[row[to ^ 1] ^ 1];
- if(path.find(slot) != path.end())return path.size();
- if(visited.find(slot) != visited.end())return 0;
- visited.insert(slot);
- path.insert(slot);
- int size = findCycle(row, map, path, visited, next);
- path.erase(slot);
- return size;
- }
- };
Add Comment
Please, Sign In to add comment