M–二分查找 Time Limit: 600MS Memory Limit: 65536KB Submit Statistic 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
#include <stdio.h>int a[3100000];int find(int x, int y,int k){ int m=x+(y-x)/2; if(x>y) return -1; else { if(a[m]==k) return m+1; else if(a[m]>k) return find(x,m-1,k); else return find (m+1,y,k); }}int main(){ int n; int k,q,i; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } scanf("%d",&q); while(q--) { scanf("%d",&k); printf("%d/n",find(0,n-1,k)); } return 0;}新聞熱點
疑難解答