-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
refueling_schedule.cc
50 lines (44 loc) · 1.71 KB
/
refueling_schedule.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <vector>
#include "test_framework/fmt_print.h"
#include "test_framework/generic_test.h"
#include "test_framework/test_failure.h"
#include "test_framework/timed_executor.h"
using std::vector;
const int kMPG = 20;
// gallons[i] is the amount of gas in city i, and distances[i] is the distance
// city i to the next city.
int FindAmpleCity(const vector<int>& gallons, const vector<int>& distances) {
int remaining_gallons = 0;
struct CityAndRemainingGas {
int city = 0, remaining_gallons = 0;
};
CityAndRemainingGas city_remaining_gallons;
const int num_cities = size(gallons);
for (int i = 1; i < num_cities; ++i) {
remaining_gallons += gallons[i - 1] - distances[i - 1] / kMPG;
if (remaining_gallons < city_remaining_gallons.remaining_gallons) {
city_remaining_gallons = {i, remaining_gallons};
}
}
return city_remaining_gallons.city;
}
void FindAmpleCityWrapper(TimedExecutor& executor, const vector<int>& gallons,
const vector<int>& distances) {
int result = executor.Run([&] { return FindAmpleCity(gallons, distances); });
const int num_cities = gallons.size();
int tank = 0;
for (int i = 0; i < num_cities; ++i) {
int city = (result + i) % num_cities;
tank += gallons[city] * kMPG - distances[city];
if (tank < 0) {
throw TestFailure(FmtStr("Out of gas on city {}", i));
}
}
}
int main(int argc, char* argv[]) {
std::vector<std::string> args{argv + 1, argv + argc};
std::vector<std::string> param_names{"executor", "gallons", "distances"};
return GenericTestMain(args, "refueling_schedule.cc",
"refueling_schedule.tsv", &FindAmpleCityWrapper,
DefaultComparator{}, param_names);
}