Drill

ProblemsC++ › logistics

Cost of a planned route

easylogisticsArraysMathC++

A route is a list of legs; each leg has a distance and a per-kilometre rate. Sum the cost of the whole route.

routeCost(legs: list<Leg>) → int

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

int routeCost(std::vector<Leg> legs) {
    
}

Worked examples

CallResult
routeCost(std::vector<Leg>{Leg{10, 5}, Leg{4, 8}})82
routeCost(std::vector<Leg>{Leg{1, 1000}})1000
routeCost(std::vector<Leg>{})0
routeCost(std::vector<Leg>{Leg{0, 500}})0

Hint

Multiply per leg and add.

Reference solution in C++
int routeCost(std::vector<Leg> legs) {
    int total = 0;
    for (const auto& leg : legs) total += leg.distance * leg.rate;
    return total;
}

The same problem in another language

More logistics problems in C++