ann8497

car fueling/ Samsung

Aug 21st, 2019
1,137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.19 KB | None | 0 0
  1. /*
  2. IN COLLABORATION WITH MY FRIEND MOHIT PRESENTS  -> car fueling
  3. script to generate test cases -> https://ideone.com/9e2nu0
  4.  
  5. TEST CASES
  6.  
  7. inputs
  8. 7
  9. 4
  10. 1 1 1 1
  11. 5
  12. 1 2 1 2 1
  13. 6
  14. 1 1 1 2 2 2
  15. 7
  16. 1 1 2 1 2 1 1
  17. 4
  18. 1 1 1 1
  19. 3
  20. 1 2 1
  21. 8
  22. 1 2 2 2 1 2 1 1
  23. outputs
  24. 8
  25. 12
  26. 14
  27. 22
  28. 8
  29. 6
  30. 32
  31. */
  32.  
  33. #include<iostream>
  34. using namespace std;
  35.  
  36. int n;
  37. int ans;
  38. int a[100];
  39.  
  40. void solve(int cars, int cost, int index, int type, int fuel){
  41.  
  42.    if(cost>ans)return; /* this condition is used to stop the unnecessary recursion */
  43.    
  44.     if(cars == n){
  45.          ans = min(ans,cost); /* base case when all cars are filled */
  46.          return;
  47.     }
  48.    
  49.     if(cost > 50)return;  /* this is done to stop the recursion */
  50.    
  51.     int temp;
  52.     temp = (type == 1) ? 1 : -1; /* to check the  direction of robot */
  53.     int cost2;
  54.     cost2 = (type == 1) ? index : n-index + 1;
  55.     int decide;
  56.     decide = (type == 1) ? 0 : n+1;
  57.  
  58.     if(index == 0)
  59.         solve(cars, cost+1,1, 1,2);
  60.     else if(index == n+1)
  61.         solve(cars, cost+1,n, 2,2);
  62.    
  63.  
  64.     else{
  65.         if(type != a[index]){
  66.             solve(cars, cost+1, index + temp, type, fuel);
  67.         }
  68.         else{
  69.             if(fuel>0){
  70.             int x  = a[index];
  71.             a[index] = 0;
  72.            
  73.             /* fill the car and move in same direction */
  74.             solve(cars + 1, cost + 1, index + temp, type, fuel-1);  
  75.              /* move the car back to same station after filling the car */
  76.             solve(cars + 1, cost+cost2, decide, 0, 0);
  77.             a[index] = x;
  78.             }
  79.             /* else cant be used here this is the heart of recursion
  80.                if we have fuel and the type is same then also we can
  81.                chose to move ahead. we can fill the the present cars
  82.                later. in some test cases it will leads to less
  83.                final distance covered
  84.             */
  85.             solve(cars, cost + 1, index + temp, type, fuel);
  86.         }
  87.     }
  88.    
  89. }
  90.  
  91. int main(){
  92.    
  93.    int t; cin>>t;
  94.    while(t--){
  95.      
  96.     cin>>n;
  97.     for(int i = 1; i<=n; i++)cin>>a[i];
  98.    
  99.     ans = 100000;
  100.    
  101.     solve(0,0,0,1,2);
  102.     cout<<ans-1<<endl;
  103.    }
  104.     return 0;
  105. }
Add Comment
Please, Sign In to add comment