-3

Mr X is traveling by car on an expressway. Suppose there are several gas (petrol) stations on the way: at distances 0 = d0 < d1 < d2 < ... < dn from the starting point d0.

Mr X’scar, when full, can travel a distance D >= max{di+1 - di} . Mr X wants to minimize the number of stops he makes to fill gas.

Devise an greedy algorithm that return min numbers of stops needed.

Jun Hao
  • 209
  • 4
  • 9

1 Answers1

0

This is the sort of thing it is asking for.

GCC 4.8.3: g++ -Wall -Wextra -std=c++0x -g main.cpp

#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <vector>

int count_stops(int D, const std::vector<int>& d) {
  if (d.size() < 2) { throw std::logic_error("Vector too small."); }

  auto p = std::begin(d);
  auto count = 0;

  while (p != --std::end(d)) {
    // Greedy: go as far as I can on this tank of gas.
    auto n = --std::find_if(p, std::end(d), [=](int x) {
      return *p + D < x; });
    // The specification says we do not need to worry about this...
    if (p == n) { throw std::logic_error("D too small."); }
    p = n;
    ++count; }

  return count; }


int main(int, char* []) {
  auto D = 16;
  auto d = std::vector<int> { 0, 5, 15, 30, 32, 33, 37, 49, 53, 59, 61 };

  std::cout << "stops: " << count_stops(D, d) << "\n";
  return 0; }
Adam Burry
  • 1,904
  • 13
  • 20
  • This problem is problem 17.2-4 from Cormen, Leiserson, and Rivest, "Introduction to Algorithms", 1990. There is a detailed solution here: http://people.cis.ksu.edu/~subbu/Papers/Minimum%20Stops.pdf – Adam Burry Oct 27 '14 at 12:46