您的位置:首页 > 编程语言 > C语言/C++

SDUT_二分查找_循环

2018-03-12 17:43 204 查看

M--二分查找

Time Limit: 600 ms Memory Limit: 65536 KiB[align=center]Submit Statistic[/align]

Problem Description

给出含有n个数的升序序列,保证序列中的数两两不相等,这n个数编号从1 到n。然后给出q次询问,每次询问给出一个数x,若x存在于此序列中,则输出其编号,否则输出-1。

Input

单组输入。首先输入一个整数n(1 <= n && n <= 3000000),接下的一行包含n个数。再接下来的一行包含一个正整数q(1 <= q && q <= 10000),表示有q次询问。再接下来的q行,每行包含一个正整数x。

Output

对于每次询问,输出一个整数代表答案。

Sample Input

5
1 3 5 7 9
3
1
5
8

Sample Output

1
3
-1

Hint

#include<stdio.h>
__int64 a[3000000];
void initArr(__int64 a[],int n){
for(int i=0;i<n;i++){
scanf("%I64d",&a[i]);
}
}
int main(){
int n;
scanf("%d",&n);
initArr(a,n);
//int base=0,top=n-1,temp;  不能放在这里
int q;
scanf("%d",&q);
while(q--){
int x;
scanf("%d",&x);
int base=0,top=n-1,temp;
int k=-1;               //记录位置   默认为-1
while(top>=base){
temp=(base+top)/2;
if(a[temp]==x){
k=temp+1;
break;
}
else if(x>a[temp]){
base=temp+1;
}
else{
top=temp-1;
}
}
printf("%d\n",k);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息