用于查找最小停靠数的贪婪算法

时间:2014-10-23 17:41:15

标签: greedy

X先生正在高速公路上开车旅行。假设有几个燃气(汽油)站 在路上:在距离0 = d0< d1< d2< ......< dn从起点d0开始。

X'scar先生,当满员时,可以行进距离D> = max {di + 1 - di}。 X先生希望尽量减少他填充气体的次数。

设计一种贪婪的算法,返回所需的最小停留次数。

1 个答案:

答案 0 :(得分:-1)

这就是它要求的东西。

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; }
相关问题