HDU 2899 Strange fuction [二分]

#Description
给一个多项式函数f(x),带一个参数y,每次输入y,求函数最小值
#Algorithm
首先对函数求导,然后f’(x) = 0,f(x)就是函数的最小值。然后就是二分法求函数最小值的问题了。高中都学过。
#Code

#include <cstdio>
#include <cmath>
#include <iostream>
using namespace std;
const double eps = 1e-10;
double y;
double f(const double &x)
{
  return 6 * pow(x, 7) + 8 * pow(x, 6) + 7 * pow(x, 3) +
         5 * pow(x, 2) - y * x;
}
double f1(const double &x)
{
  return 6 * 7 * pow(x, 6) + 8 * 6 * pow(x, 5) +
         7 * 3 * pow(x, 2) + 5 * 2 * x - y;
}
void solve()
{
  cin >> y;
  double l = 0, r = 100;
  while (r > l)
  {
    double mid = (l + r) / 2;
    if (abs(f1(mid)) < eps)
    {
      printf("%.4lf\n", f(mid));
      break;
    }
    if (f1(l) * f1(mid) < 0) r = mid; else l = mid;
  }
}
int main()
{
  int t;
  cin >> t;
  for (int i = 0; i < t; i++)
    solve();
}

猜你喜欢

转载自blog.csdn.net/YYecust/article/details/50813151
今日推荐