#6431: c++ 二分搜尋法TLE??


kikofish (fsh0524)


 這是我的程式碼
 
#include <cstdlib>
#include <iostream>

using namespace std;

int n,k,x,i,f,m,e,a[1000000];

void bs(int c)
{
     m=(f+e)/2;
     if(c==a[m]){cout<<m+1<<endl;}
     else if(c>a[m]){
          if(f==e){cout<<0<<endl;}
          else{
               f=m+1;
               bs(c);
               }
          }
     else if(c<a[m]){
          if(f==e){cout<<0<<endl;}
          else{
               e=m-1;
               bs(c);
               }
          }
}

int main()
{
    cin>>n>>k;
    for(i=0 ; i<n ; i++){cin>>a[i];}
    while(k--){
               cin>>x;
               f=0;
               e=n-1;
               if(x>a[e]||x<a[f]){cout<<0<<endl;}
               else{bs(x);}
               }
    return 0;
}
 
為什麼我都逾時TLE??
有沒有較快的解題方法 
#8916: Re:c++ 二分搜尋法TLE??


dibery (Bor)


請使用 C++ 的內建函式 lower_bound

編寫簡易又不會錯

#8917: Re:c++ 二分搜尋法TLE??


silithus (希利蘇斯)


請使用 C++ 的內建函式 lower_bound

編寫簡易又不會錯


lower_bound固然好用,但作為基礎練習,還是自己動手寫比較好吧。
#25659: Re:c++ 二分搜尋法TLE??


vic20050418@gmail.com (Wen Vic)


請IO優化:

ios_base::sync_with_stdio(false);

cin.tie(0);

並將endl替換成\n