[ZJ]d732: 二分搜尋法

題目:
http://zerojudge.tw/ShowProblem?problemid=d732
---------------------------------------------------------------------------------------------------

#include<bits/stdc++.h>
using namespace std;
int binsrch(int num[], int len, int target){
int lower = 0;
int upper = len-1;
int mid=0;
while(lower <= upper){
mid = (lower + upper) / 2;
if(target > num[mid])
lower = mid + 1;
else if(target < num[mid])
upper = mid - 1;
else
return mid + 1;
}
return 0;
}
int main(){
int len,query,i;
cin>>len>>query;
int num[len];
int target[query];
int ans[query];
for(i=0;i<len;i++)
cin>>num[i];
for(i=0;i<query;i++){
cin>>target[i];
ans[i] = binsrch(num,len,target[i]);
}
for(i=0;i<query;i++)
cout<<ans[i]<<"\n";
return 0;
}

留言

這個網誌中的熱門文章

[ZJ]b513: 判斷質數-商競103

[ZJ]d212: 東東爬階梯