SDUT-M--二分查找

来源:互联网 发布:微积分中d含义,知乎 编辑:程序博客网 时间:2024/05/21 08:06

M--二分查找

Time Limit: 600MS Memory Limit: 65536KB  

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

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

Example Input

51 3 5 7 93158

Example Output

13-1

Hint

 

Author

#include <bits/stdc++.h>using namespace std;int a[3300000];int fin(int*a,int x,int s,int t){    int low=s,high=t,mid;//注意用替换变量    if(s<=t)//必须是小于等于    {        mid=(low+high)/2;        if(a[mid]>x)        {            return fin(a,x,low,mid-1);//仍然用替换变量        }        else if(a[mid]<x)        {            return fin(a,x,mid+1,high);        }        else            return mid+1;    }    return -1;}int main(){    int n,x,i,m;    scanf("%d",&n);    {        for(i=0;i<n;i++)            {scanf("%d",&a[i]);}            scanf("%d",&m);            while(m--)            {scanf("%d",&x);            int k=fin(a,x,0,n-1);            if(k!=-1)                printf("%d\n",k);            else                printf("-1\n");}    }    return 0;}

原创粉丝点击