HDU 2199 Can you solve this equation?(簡單二分)

題目連接HDU 2199ios

VJ連接寒假第一練--二分搜索專題
c++


第一次給大一的寫題解,好激動有木有!
數組

B題,首先來看題目描述,
url


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.spa


給你這麼一個等式,讓你找到有個0 ~ 100 之間的解。乍一看個人天,最高階是4的方程這可怎麼解?.net

彆着急咱們接着看輸入INPUTcode


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);blog


題目給了咱們Y。
ip

那麼問題就變成了求一元四次方程的解了,我剛查了一下還真有4次方乘的求根公式的!這裏再也不贅述感興趣的移步百度百科
其實咱們能夠經過計算機的超高運算速度去解決這個問題。直接枚舉?這裏的解是實數顯然不行,而acm中與實數相關的問題都涉及到精度,ci

咱們能夠經過基礎的二分搜索來不斷縮小解的範圍來提升答案的精度直到知足條件。


常見的二分

常見的二分通常是查找數組中的元素的位置或者存不存在。

基礎比較弱的同窗能夠本身多寫幾遍,最好去實現一下文章底部給出的lower_bound,upper_bound。

int binSearch(int List[] ,int x,int head,int tail){ //循環版本
	while(head<=tail){
		int mid=(head+tail)/2;
		if(List[mid]==x)
			return mid;
		else if(List[mid]>x){ //注意別寫反
			tail=mid-1;
		}
		else{
			head=mid+1;
		}
	}
	return -1;
}


這裏是實數,稍稍改變一下。


#include<iostream>
#include<cstdio>
using namespace std;
const double eps = 1e-10; //c++中推薦寫法,等價於c的 #define eps 1e-10
double ans(double x){
    return 8*x*x*x*x + 7*x*x*x + 2*x*x + 3*x + 6;
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        double Y;
        scanf("%lf",&Y);
        if(Y > ans(100) || Y<ans(0))  //找不到的狀況
            printf("No solution!\n");
        else{
            double l = 0,r = 100; //解在 0 ~ 100
            while(r - l >eps){ //注意這裏,若是咱們的解的範圍大於 eps,那麼咱們繼續二分 (這裏我用1e-5結果與樣例差0.001,索性直接用了1e-10)
                double mid = (l + r)/2;
                if(ans(mid) < Y)
                    l = mid;
                else
                    r = mid ;
            }
            printf("%.4f\n",l);
        }
    }
    return 0;
}


二分搜索,就這麼簡單,剩下的題目,除了C題應該都能抽象出二分搜索的模型來,加油去AC吧!

安利一發STL中的二分 lower_bound upper_bound的簡單實現(STL)

相關文章
相關標籤/搜索