Guest User

Untitled

a guest
Feb 25th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. class Solution {
  2. public:
  3. int minSwapsCouples(vector<int>& row) {
  4. int n = row.size() / 2, res = 0;
  5. unordered_map<int, int> map;
  6. unordered_set<int> path, visited;
  7. for(int i = 0; i < 2 * n; ++i)map[row[i]] = i;
  8. for(int i = 0; i < 2 * n; ++i)
  9. if(visited.find(i / 2) == visited.end())
  10. res += findCycle(row, map, path, visited, i) - 1;
  11. return res;
  12. }
  13.  
  14. private:
  15. int findCycle(vector<int>& row, unordered_map<int, int>& map, unordered_set<int>& path, unordered_set<int>& visited, int to)
  16. {
  17. int slot = to / 2, next = map[row[to ^ 1] ^ 1];
  18. if(path.find(slot) != path.end())return path.size();
  19. if(visited.find(slot) != visited.end())return 0;
  20.  
  21. visited.insert(slot);
  22. path.insert(slot);
  23. int size = findCycle(row, map, path, visited, next);
  24. path.erase(slot);
  25. return size;
  26. }
  27. };
Add Comment
Please, Sign In to add comment