1
+ /*
2
+
3
+ Implementation of Truck tour problem from Hackerrank
4
+
5
+ Suppose there is a circle. There are N petrol pumps on that circle.
6
+ Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces
7
+ of information corresponding to each of the petrol pump:
8
+ (1) the amount of petrol that particular petrol pump will give, and
9
+ (2) the distance from that petrol pump to the next petrol pump.
10
+
11
+ Initially, you have a tank of infinite capacity carrying no petrol.
12
+ You can start the tour at any of the petrol pumps. Calculate the first
13
+ point from where the truck will be able to complete the circle. Consider
14
+ that the truck will stop at each of the petrol pumps. The truck will
15
+ move one kilometer for each litre of the petrol.
16
+
17
+ Link to the problem: https://www.hackerrank.com/challenges/truck-tour/problem
18
+ */
19
+
20
+ #include < iostream>
21
+ using namespace std ;
22
+
23
+ int main ()
24
+ {
25
+ int n;
26
+ cin >> n;
27
+ int petrol[n], distance[n];
28
+ for (int i = 0 ; i < n; i++)
29
+ {
30
+ cin >> petrol[i];
31
+ cin >> distance[i];
32
+ }
33
+ // the amount of petrol left in the truck
34
+ int amountofpetrol = 0 ;
35
+
36
+ // the total amount of petrol we were short of in each petrol pump
37
+ int previous = 0 ;
38
+
39
+ // stores the index of the starting point
40
+ int startindex = 0 ;
41
+
42
+ for (int i = 0 ; i < n; i++)
43
+ {
44
+ // calculating amount of petrol left
45
+ amountofpetrol += (petrol[i] - distance[i]);
46
+
47
+ // true means that route does not exists from the current starting point
48
+ if (amountofpetrol < 0 )
49
+ {
50
+ previous = previous + amountofpetrol;
51
+ amountofpetrol = 0 ;
52
+
53
+ // start agaain from starting point
54
+ startindex = i + 1 ;
55
+ }
56
+ }
57
+ // returns starting point
58
+ cout << startindex <<endl;
59
+ return 0 ;
60
+ }
61
+
62
+ /* Time complexity: O(n)
63
+
64
+ Example 1:
65
+
66
+ Sample Input
67
+
68
+ 3
69
+ 1 5
70
+ 10 3
71
+ 3 4
72
+
73
+ Sample Output
74
+
75
+ 1
76
+
77
+ Example 2:
78
+
79
+ Sample Input
80
+
81
+ 3
82
+ 6 4
83
+ 3 6
84
+ 7 3
85
+
86
+ Sample Output
87
+
88
+ 2*/
0 commit comments