HDU 2199 Can you solve this equation? HDU 2899 Strange fuction
Can you solve this equation?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 25430 Accepted Submission(s): 10944
Problem Description
Now,given the equation 8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 == Y,can you find its solution between 0 and 100; Now please try your lucky.
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 a real number Y (fabs(Y) <= 1e10);
Output
For each test case, you should just output one real number(accurate up to 4 decimal places),which is the solution of the equation,or “No solution!”,if there is no solution for the equation between 0 and 100.
Sample Input
2 100 -4
Sample Output
1.6152 No solution!
題意是:
輸入一個Y,你找出一個x,滿足8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 == Y,的區間為【0,100】
思路:二分搜尋,通過求導,可知該函式在【0,100】間是遞增的,首先先判斷Y是否能求出x
#include<stdio.h> #include<math.h> const double eps = 1e-6; double f(double x) { return 8*pow(x,4) + 7*pow(x,3) + 2*pow(x,2) + 3*x + 6 ; } int main() { int t; double l,r,mid,n; double ans=0.0; scanf("%d",&t); while(t--) { scanf("%lf",&n); if(f(0)<=n&&n<=f(100)) //判斷n是否在此區間中 { l=0,r=100; while(r-l>1e-6) { mid=(l+r)/2; ans = f(mid); if(fabs(ans-n)<=eps) break; else if(ans > n) r=mid-1e-7; else l=mid+1e-7; } printf("%.4lf\n",mid); } else printf("No solution!\n"); } return 0; }
下面考慮一道在區間中非單調函式
Strange fuction
Problem 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,求 F(x) = 6 * x^7+8*x^6+7*x^3+5*x^2-y*x (0 <= x <=100)的最小值,精度保留4位
思路:二分搜尋,這裡需注意的是函式在區間中並非單調,不能直接二分,需要我們來求其單調區間
F(x) = 6*x7 + 8*x6 + 7*x3 + 5*x2 - y*x 一階導 F’(x) = 42*x6 + 48*x5 + 21*x2 + 10*x – y
所以我們只需求出其F’(x) == 0的點就可得到最小值
#include <stdio.h>
#include <math.h>
const double eps = 1e-8;
double y;
double cal(double x){
return 42.0*pow(x,6.0)+48.0*pow(x,5.0)+21.0*pow(x,2.0)+10.0*x;
}
double ans(double x){
return 6.0*pow(x,7.0)+8.0*pow(x,6.0)+7.0*pow(x,3.0)+5.0*pow(x,2.0)-y*x;
}
int main(){
int T;
double f,l,mid;
scanf("%d",&T);
while(T--){
scanf("%lf",&y);
if(cal(100.0)-y<=0.0){ //表明在【0,100】內為遞減,可直接輸出
printf("%.4lf\n",ans(100.0));
continue;
}
f=0.0,l=100.0;
while(l-f>eps){
mid=(f+l)/2.0;
if(cal(mid)-y<0.0){
f=mid;
}else{
l=mid;
}
}
printf("%.4lf\n",ans(mid));
}
return 0;
}