HDU 2899 Strange fuction
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8055 Accepted Submission(s): 5535
F(x) = 6 * x^7+8*x^6+7*x^3+5*x^2-y*x (0 <= x <=100)
Can you find the minimum value when x is between 0 and 100.
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; double a[5] = {6,8,7,5,0},b[5] = {7,6,3,2,1}; double cal(double x) { double ans = 0; for(int i = 0;i < 5; ++i) { ans += a[i] * pow(x,b[i]); } return ans; } int main() { int t; scanf("%d",&t); while(t--) { scanf("%lf",&a[4]); a[4] *= -1; double lmid,rmid,l = 0,r = 100; while(r - l > 0.000001) { lmid = l + (r - l) / 3; rmid = r - (r - l) / 3; if(cal(lmid) > cal(rmid)) l = lmid; else r = rmid; } printf("%.4f\n",cal(lmid)); } return 0; }
hihoCoder 1142 三分·三分求極值
描述
這一次我們就簡單一點了,題目在此:
在直角座標系中有一條拋物線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<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
double a,b,c,xx,yy;
double cal(double x)
{
double ans = 0;
return pow((x - xx),2) + pow((a * x * x + b * x + c - yy),2);
}
double solve()
{
scanf("%lf %lf %lf %lf %lf",&a,&b,&c,&xx,&yy);
double l = -200,r = 200,lmid,rmid;
while(r - l > 0.00001)
{
lmid = l + (r - l) / 3;
rmid = r - (r - l) / 3;
if(cal(lmid) > cal(rmid)) l = lmid;
else r = rmid;
}
printf("%.3f\n",sqrt(cal(rmid)));
}
int main()
{
solve();
return 0;
}