1142 : 三分·三分求极值
题目传送:hihoCoder - 1142 - 三分·三分求极值
二分适用于单调函数,对于需要逼近的区间做二等分,来求解某点的值等。
三分适用于凸形函数,对于需要逼近的区间做三等分。
AC代码:
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <utility>
#include <iostream>
#include <algorithm>
#include <functional>
#define LL long long
#define INF 0x7fffffff
using namespace std;
double a, b, c, x, y;
double get_dist(double xx) {
double yy = a * xx * xx + b * xx + c;
return sqrt((xx - x) * (xx - x) + (yy - y) * (yy - y));
}
int main() {
double l = -500, r = 500;
scanf("%lf %lf %lf %lf %lf", &a, &b, &c, &x, &y);
while(r - l > 0.000001) {//这里为了保证精度,尽量开小点,因为是分治,即使再小也能够承受
double d = (r - l) / 3;
double rm = r - d;
double lm = l + d;
if(get_dist(lm) < get_dist(rm)) {
r = rm;
}
else l = lm;
}
printf("%.3lf\n", get_dist(l));
return 0;
}