Advertisement
SalmaYasser

Untitled

Jan 17th, 2020
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. class Solution {
  2. public:
  3. int minSwap(vector<int>& A, vector<int>& B) {
  4.  
  5.  
  6. int sz = A.size();
  7. int swap = 1, dont_swap = 0;
  8. for (int i = 1 ; i < sz ; i++)
  9. {
  10. int al = A[i - 1], ar = A[i], bl = B[i - 1], br = B[i];
  11. bool both_increasing = al < ar && bl < br;
  12. bool if_swapped_increasing = al < br && bl < ar;
  13.  
  14. if (both_increasing && if_swapped_increasing)
  15. {
  16. int m = min (swap, dont_swap);
  17. swap = m + 1;
  18. dont_swap = m;
  19. }
  20. else if (both_increasing && !if_swapped_increasing )
  21. {
  22. swap += 1;
  23.  
  24.  
  25. }
  26. else
  27. {
  28. int temp = dont_swap;
  29. dont_swap = swap;
  30. swap = temp + 1;
  31.  
  32. }
  33.  
  34. }
  35.  
  36. return min (swap, dont_swap);
  37. }
  38. };
  39.  
  40.  
  41. /*
  42. 1 3 5 4 9
  43. 1 2 3 7 10
  44.  
  45. state
  46. whether we swap the element at index i to make A[0..i] and B[0..i] both increasing can uniquely identify a state, i.e. a node in the state graph.
  47.  
  48. state function
  49. state(i, 0) is the minimum swaps to make A[0..i] and B[0..i] both increasing if we donot swap A[i] with B[i]
  50.  
  51. state(i, 1) is the minimum swaps to make A[0..i] and B[0..i] both increasing if we do swap A[i] with B[i]
  52.  
  53. goal state
  54. min{state(n - 1, 0), state(n - 1, 1)} where n = A.length
  55.  
  56. state transition
  57. We define areBothSelfIncreasing: A[i - 1] < A[i] && B[i - 1] < B[i], areInterchangeIncreasing: A[i - 1] < B[i] && B[i - 1] < A[i].
  58. Since 'the given input always makes it possible', at least one of the two conditions above should be satisfied.
  59.  
  60.  
  61.  
  62.  
  63. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement