Skip to content

Commit 19432d1

Browse files
committed
Added greedy algorithm programs
1 parent 35f3610 commit 19432d1

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Greedy Algorithms/Autonomous Car.cpp

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// Autonomous Car
2+
3+
// A futuristic company is building an autonomous car. The scientists at the company are training the car to perform Reverse parking. To park, the car needs to be able to move in backward as well as forward direction. The car is programmed to move backwards B meters and forwards again, say F meters, in a straight line. The car does this repeatedly until it is able to park or collides with other objects. The car covers 1 meter in T units of time. There is a wall after distance D from car's initial position in the backward direction.
4+
5+
// The car is currently not without defects and hence often hits the wall. The scientists are devising a strategy to prevent this from happening. Your task is to help the scientists by providing them with exact information on amount of time available before the car hits the wall.
6+
7+
// Input Format:
8+
9+
// First line contains total number of test cases, denoted by N Next N lines, contain a tuple containing 4 values delimited by space F B T D, where 1. F denotes forward displacement in meters 2. B denotes backward displacement in meters 3. T denotes time taken to cover 1 meter 4. D denotes distance from Car's starting position and the wall in backward direction
10+
11+
// Output Format:
12+
13+
// For each test case print time taken by the Car to hit the wall
14+
15+
// Constraints:
16+
// First move will always be in backward direction
17+
// 1 <= N <= 100
18+
// backward displacement > forward displacement i.e. (B > F)
19+
// forward displacement (F) > 0
20+
// backward displacement (B) > 0
21+
// time (T) > 0
22+
// distance (D) > 0
23+
// All input values must be positive integers only
24+
25+
// Sample Input 0
26+
27+
// 2
28+
// 6 9 3 18
29+
// 3 7 5 20
30+
// Sample Output 0
31+
32+
// 162
33+
// 220
34+
35+
#include <iostream>
36+
using namespace std;
37+
38+
int main()
39+
{
40+
int n;
41+
cin>>n;
42+
while(n--)
43+
{
44+
45+
int f,b,t,d;
46+
cin>>f>>b>>t>>d;
47+
long long ans=0;
48+
int count=0,dist=0;
49+
while(true)
50+
{
51+
if(dist+b<d)
52+
dist+=b;
53+
54+
else
55+
{
56+
ans+=(d-dist)*t;
57+
break;
58+
}
59+
60+
dist-=f;
61+
62+
count++;
63+
64+
}
65+
ans+=(count*t)*(f+b);
66+
67+
cout<<ans<<endl;
68+
69+
}
70+
71+
return 0;
72+
}

0 commit comments

Comments
 (0)