:heavy_check_mark: test/yc_306_maximize.test.cpp

Back to top page

Depends on

Code

#define PROBLEM "https://yukicoder.me/problems/no/306"
#define ERROR 1e-6

#include <cstdio>
#include <cmath>

#include "algorithm/ternary_search.cpp"

int main() {
  long double xa, ya, xb, yb;
  scanf("%Lf %Lf %Lf %Lf", &xa, &ya, &xb, &yb);

  auto f = [&](auto y) { return -(std::hypot(xa, y-ya) + std::hypot(xb, yb-y)); };
  long double y = optimize_convex(f, 0.0L, 1e3L, 1e-6L).first;
  printf("%.20Lf\n", y);
}

#line 1 "test/yc_306_maximize.test.cpp"
#define PROBLEM "https://yukicoder.me/problems/no/306"
#define ERROR 1e-6

#include <cstdio>
#include <cmath>

#line 1 "algorithm/ternary_search.cpp"



/**
 * @brief 黄金比分割の三分探索
 * @author えびちゃん
 */

#line 10 "algorithm/ternary_search.cpp"
#include <utility>

template <typename Fn, typename Tp>
auto optimize_convex(Fn&& f, Tp xl, Tp xu, Tp err, bool maximize = true) {
  // Return {argmax f(x), max f(x)} if maximize, {argmin f(x), min f(x)}
  // otherwise.  If f is not convex in [xl, xu], the behavior is undefined.
  Tp const phi = (1 + std::sqrt(static_cast<Tp>(5))) / 2;
  int const iter = (std::log(xu-xl) - std::log(err)) / std::log(phi) + 1;
  Tp xml = (phi * xl + xu) / (1 + phi);
  Tp xmu = (xl + phi * xu) / (1 + phi);
  Tp yml = f(xml);
  Tp ymu = f(xmu);
  for (int i = 0; i < iter; ++i) {
    if (!maximize ^ (yml > ymu)) {
      xu = xmu;
      xmu = xml;
      ymu = yml;
      xml = (phi * xl + xu) / (1 + phi);
      yml = f(xml);
    } else {
      xl = xml;
      xml = xmu;
      yml = ymu;
      xmu = (xl + phi * xu) / (1 + phi);
      ymu = f(xmu);
    }
  }
  return std::make_pair(xml, yml);
}


#line 8 "test/yc_306_maximize.test.cpp"

int main() {
  long double xa, ya, xb, yb;
  scanf("%Lf %Lf %Lf %Lf", &xa, &ya, &xb, &yb);

  auto f = [&](auto y) { return -(std::hypot(xa, y-ya) + std::hypot(xb, yb-y)); };
  long double y = optimize_convex(f, 0.0L, 1e3L, 1e-6L).first;
  printf("%.20Lf\n", y);
}

Back to top page