fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. int findPos(int* a,int val,int n){
  6. cout << " ";
  7. for(int i=0;i<n;i++)
  8. if(a[i]==val) return i;
  9. return -1;
  10. }
  11.  
  12. void print(int* a, int n){
  13. for (int i = 0; i < n ; i++) cout << a[i] << " " ;
  14. cout << endl;
  15. }
  16.  
  17. void parkinglot(int* a, int *b, int n){
  18.  
  19. cout << "Init: " ;
  20. print(a,n);
  21.  
  22. int count = 0;
  23. int currIdx = 0;
  24. for (int i = 0; i < n; i++) {
  25. if (a[i] != 0 && b[i] != a[i]) {
  26. int zIdx = findPos(a, 0, n);
  27. swap(a[i], a[zIdx]);
  28. count++;
  29. print(a,n);
  30. if(b[i]!=0){
  31. currIdx = findPos(a, b[i], n);
  32. swap(a[i], a[currIdx]);
  33. print(a,n);
  34. count++;
  35. }
  36. }
  37.  
  38. else if(a[i]==0 && b[i] != a[i]){
  39. currIdx = findPos(a, b[i], n);
  40. swap(a[i], a[currIdx]);
  41. print(a,n);
  42. count++;
  43. }
  44. }
  45.  
  46. cout << "Finl: " ;
  47. print(a,n);
  48. cout << "Min swaps: " << count << endl;
  49.  
  50. }
  51.  
  52. int main()
  53. {
  54. int src[] = {1,2,3,0,4};
  55. int tgt[] = {0,3,2,1,4};
  56. cout << "Rearrange parking lot in Min swaps!" << endl;
  57. int n = sizeof(src)/sizeof(src[0]);
  58. parkinglot(src,tgt,n);
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Rearrange parking lot in Min swaps!
Init: 1 2 3 0 4 
      0 2 3 1 4 
      2 0 3 1 4 
      2 3 0 1 4 
      0 3 2 1 4 
Finl: 0 3 2 1 4 
Min swaps: 4