Strange fuction 解題報告
阿新 • • 發佈:2018-12-24
Strange fuction
Description
Now, here is a fuction: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.
Input
The first line of the input contains an integer T(1<=T<=100) which means the number of test cases. Then T lines follow, each line has only one real numbers Y.(0 < Y <1e10)Output
Just the minimum value (accurate up to 4 decimal places),when x is between 0 and 100.Sample Input
2
100
200
Sample Output
-74.4291
-178.8534
題意:給定Y,求當0<=x<=100時f(x)的最小值。
解題思路:首先看這個函式並沒有單調性可言,但是我們對其求導之後發現
f'(x)=42x^6+48x^5+21x^2+10^x-y.
容易發現 f'(x) 在[0,100]上是一個單調遞增的函式,那麼問題就簡單了,如果f'(x)在[0,100]上存在零點x0,那麼f(x0)必然就是所求的最小值,怎麼求零點?二分查詢啊~
如果不存在零點,也就是f'(100)<0或者f'(0)>0的情況,意味著f(x)單調遞減或者單調遞增,那麼直接輸出f(100)或f(0)就可以了。
#include <iostream> #include <math.h> #include <stdlib.h> #include <cstdio> using namespace std; const double EPS=1e-5; double y; double f(double x) { return 6*pow(x,7)+8*pow(x,6)+7*pow(x,3)+5*pow(x,2)-y*x; } double f2(double x) //f(x)求導 { return 42*pow(x,6)+48*pow(x,5)+21*pow(x,2)+10*x; } double bs() { double lo=0,hi=100; double mi; while(1) { mi=(lo+hi)/2.0;//浮點數問題就別移位運算了 if(fabs(f2(mi)-y)<EPS) return mi; else if(f2(mi)>y) hi=mi; else lo=mi; } return -1; } int main() { int T; cin>>T; while(T--) { cin>>y; if(f2(100)-y<0) printf("%.4f\n",f(100)); else if(f2(0)-y>0) printf("%.4f\n",f(0)); else printf("%.4f\n",f(bs())); } return 0; }
</pre><p></p><p><span style="font-family:SimHei;font-size:18px;">以上說的是使用二分查詢的方法,但是這道題也可以使用三分。</span></p><p><span style="font-family:SimHei;font-size:18px;">可以用二分的方法AC之後再試一下用三分解這道題,可以作為練習三分的入門題。</span></p><p><span style="font-family:SimHei;font-size:18px;">用三分查詢可以直接求得單峰函式的極值</span></p><p><span style="font-family:SimHei;font-size:18px;"></span><pre name="code" class="cpp">#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
const double EPS=1e-6;
double y;
double f(double x)
{
return 6*pow(x,7)+8*pow(x,6)+7*pow(x,3)+5*pow(x,2)-y*x;
}
double ts()
{
double l=0,r=100,mid,mmid;
mid=(l+r)/2.0;
mmid=(mid+r)/2.0;
while(fabs(mid-mmid)>EPS)
{
mid=(l+r)/2.0;
mmid=(mid+r)/2.0;
if(f(mid)<f(mmid))
r=mmid;
else
l=mid;
}
return f(mid);
}
int main()
{
int repeat;
cin>>repeat;
while(repeat--)
{
cin>>y;
printf("%.4lf\n",ts());
}
return 0;
}