递推递归练习P - M--二分查找

    xiaoxiao2021-04-14  30

    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 思路: 这是一个二分查找问题, 很快写完了之后发现超时 , 以为 要用到 记忆化搜索? 百度 了一下 ,输入输出要用 scanf 和 printf ,scanf 和 printf 的效率 比 cin cout 要高很多 代码: #if   1            #include<bits/stdc++.h> using namespace std; int *a;  int fun(int ,int ,int );  int main() { int n,i,x,mid,lower,top;     scanf("%d",&n); a= new int[n]; for(i=0;i<n;i++)             scanf("%d",&a[i]); lower=0; top=n-1; int ni;          scanf("%d\n",&ni); for(int i=0;i<ni;i++)   { scanf("%d",& x);           int k=fun(x,lower,top);                      printf("%d\n",k); } } int fun(int x,int min,int max) { int mid; mid=(max+min)/2; if(max>=min) { if(x==a[mid]) return   mid+1; else if(x>a[mid])   fun(x,mid+1,max);   else fun(x,min,mid-1); } else return -1; } #endif
    转载请注明原文地址: https://ju.6miu.com/read-669697.html

    最新回复(0)