P1024 [NOIP2001 提高组] 一元三次方程求解
题目描述
有形如: a x 3 + b x 2 + c x + d = 0 a x^3 + b x^2 + c x + d = 0 ax3+bx2+cx+d=0 这样的一个一元三次方程。给出该方程中各项的系数( a , b , c , d a,b,c,d a,b,c,d 均为实数),并约定该方程存在三个不同实根(根的范围在 − 100 -100 −100 至 100 100 100 之间),且根与根之差的绝对值 ≥ 1 \ge 1 ≥1。要求由小到大依次在同一行输出这三个实根(根与根之间留有空格),并精确到小数点后 2 2 2 位。
提示:记方程 f(x)=0,若存在 2 个数 x1和x2 ,且x1<x2 ,f(x1)×f(x2)<0,则在 (x1,x2) 之间一定有一个根。
输入格式
一行,4 个实数a,b,c,d。
输出格式
一行,3 个实根,从小到大输出,并精确到小数点后2 位。
输入输出样例
输入
1 -5 -4 20
输出
-2.00 2.00 5.00
TLE的code:
#include<iostream>
using namespace std;
double a,b,c,d;
double f(double x){
return a*x*x*x+b*x*x+c*x+d;
}
void binary_search(double l,double r){
if(r-1<0.001){
printf("%.2f ",r);
return ;
}
while(l-0.001<r){
double mid=(l+r)/2;
if(f(mid)==0){
printf("%.2f ",mid);
return ;
}
if(f(mid)*f(l)<0) printf("%.2f ",l);
else printf("%.2f ",r);
}
}
int main(){
cin>>a>>b>>c>>d;
int m=0;
for(double i=-100;i<=100;i++){
if(m<3&&f(i)==0){
printf("%.2f ",i);
m++;
continue;
}
if(m<3&&f(i)*f(i+1)<0){
binary_search(i,i+1);
m++;
}
}
}
优化后code:
#include <iostream>
#include <iomanip> // 用于设置输出精度
using namespace std;
double a, b, c, d;
double f(double x) {
return a * x * x * x + b * x * x + c * x + d;
}
void binary_search(double l, double r) {
if (r - l < 0.001) { // 当区间足够小时,认为找到了根
cout << fixed << setprecision(2) << (l + r) / 2 << " ";
return;
}
double mid = (l + r) / 2;
if (f(mid) == 0) { // 如果mid是根
cout << fixed << setprecision(2) << mid << " ";
return;
}
if (f(mid) * f(l) < 0) { // 如果mid和l异号,则在[l, mid]之间搜索
binary_search(l, mid);
} else { // 否则在[mid, r]之间搜索
binary_search(mid, r);
}
}
int main() {
cin >> a >> b >> c >> d;
int m = 0;
for (double i = -100; i <= 100; i += 0.01) { // 改为更小的步长以捕获非整数解
if (m > 3) break; // 只输出前三个解
if (f(i) == 0) { // 直接输出整数或接近整数的解
cout << fixed << setprecision(2) << i << " ";
m++;
continue;
}
// 检查当前点和下一个点是否异号
if (i + 0.01 <= 100 && f(i) * f(i + 0.01) < 0) {
binary_search(i, i + 0.01); // 进行二分查找
m++;
if (m > 3) break; // 只输出前三个解
}
}
return 0;
}