fork download
  1. // C++ program to find circular tour for a truck
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // A petrol pump has petrol and distance to next petrol pump
  6. class petrolPump {
  7. public:
  8. int petrol;
  9. int distance;
  10. };
  11.  
  12. // The function returns starting point if there is a
  13. // possible solution, otherwise returns -1
  14. int printTour(petrolPump p[], int n)
  15. {
  16. // deficit is used to store the value of the capacity as
  17. // soon as the value of capacity becomes negative so as
  18. // not to traverse the array twice in order to get the
  19. // solution
  20. int start = 0, deficit = 0;
  21. int capacity = 0;
  22. for (int i = 0; i < n; i++) {
  23. capacity += p[i].petrol - p[i].distance;
  24. if (capacity < 0) {
  25. // If this particular step is not done then the
  26. // between steps would be redundant
  27. start = i + 1;
  28. deficit += capacity;
  29. capacity = 0;
  30. }
  31. }
  32. return (capacity + deficit >= 0) ? start : -1;
  33. }
  34. // Driver code
  35. int main()
  36. {
  37. petrolPump arr[] = {{3, }, { 6, 4 }, { 3, 6 }, { 7, 3 } };
  38.  
  39. int n = sizeof(arr) / sizeof(arr[0]);
  40. int start = printTour(arr, n);
  41.  
  42. (start == -1) ? cout << "No solution"
  43. : cout << "Start = " << start;
  44.  
  45. return 0;
  46. }
  47.  
  48. // This code is contributed by aditya kumar
  49.  
Success #stdin #stdout 0.01s 5548KB
stdin
Standard input is empty
stdout
Start = 0