三分求极值
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
这一次我们就简单一点了,题目在此:
在直角坐标系中有一条抛物线y=ax^2+bx+c和一个点P(x,y),求点P到抛物线的最短距离d。
输入
第1行:5个整数a,b,c,x,y。前三个数构成抛物线的参数,后两个数x,y表示P点坐标。-200≤a,b,c,x,y≤200
输出
第1行:1个实数d,保留3位小数(四舍五入)
样例输入 2 8 2 -2 6
样例输出
2.437
#include <iostream> #include <math.h> #include <float.h> #include <iomanip> using namespace std; double presult = 0.0; typedef struct funcparamter { double a; double b; double c; } funcparamter; typedef struct point { double x; double y; } point; double Calculator(funcparamter minefunc,point knownpoint,point foundpoint) { return sqrt((foundpoint.x-knownpoint.x)*(foundpoint.x-knownpoint.x)+(minefunc.a*pow(foundpoint.x,2)+minefunc.b*foundpoint.x+minefunc.c-knownpoint.y)*(minefunc.a*pow(foundpoint.x,2)+minefunc.b*foundpoint.x+minefunc.c-knownpoint.y)); } double findY(double x,funcparamter minefunc) { return minefunc.a*pow(x,2)+minefunc.b*x+minefunc.c; } double findmin(double left,double right,funcparamter minefunc,point knownpoint) { point lm,rm; lm.x = left+(right-left)/3; rm.x = left+2*(right-left)/3; lm.y = findY(lm.x,minefunc); rm.y = findY(rm.x,minefunc); if((Calculator(minefunc,knownpoint,lm)-Calculator(minefunc,knownpoint,rm))==0) { double min = Calculator(minefunc,knownpoint,lm)<Calculator(minefunc,knownpoint,rm) ? Calculator(minefunc,knownpoint,lm) : Calculator(minefunc,knownpoint,rm); cout<<setiosflags(ios::fixed)<<setprecision(3)<<min<<endl; return min; } else if(Calculator(minefunc,knownpoint,lm)<Calculator(minefunc,knownpoint,rm)) { findmin(left,rm.x,minefunc,knownpoint); } else { findmin(lm.x,right,minefunc,knownpoint); } } int main() { funcparamter minefunc; point knownpoint; //cout<<DBL_MAX<<endl; cin>>minefunc.a>>minefunc.b>>minefunc.c>>knownpoint.x>>knownpoint.y; //cout<<Calculator(minefunc,knownpoint,foundpoint)<<endl; findmin(-1000,1000,minefunc,knownpoint); return 0; }
提示
时间: 2024-10-01 00:42:51