二分查找

M–二分查找
Time Limit: 600MS Memory Limit: 65536KB
Submit Statistic Discuss
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

5
1 3 5 7 9
3
1
5
8
Example Output

1
3
-1

int  f(int l,int r,int x,int a[])
{
    int s;
    while(l<r)
    {
        s=l+(r-l)/2;

        if(x==a[s])
        {
            return s;
        }
        **if(x>a[s])
        l=s+1;
        else
            r=s-1;
    }**
    return -1;
}

int a[3000001];
int main()
{
    int n,q,i,x,s;
    scanf("%d",&n);
    for(i=1; i<=n; i++)
    scanf("%d",&a[i]);
    scanf("%d",&q);
    for(i=0;i<q;i++)
    {
        s=-1;
        scanf("%d",&x);
        s= f(1,n,x,a);
        printf("%d\n",s);
    }
    return 0;

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章