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;
}