递推递归练习P

来源:互联网 发布:摄像头美化软件 编辑:程序博客网 时间:2024/05/17 09:02

题目简要:

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

51 3 5 7 93158

Sample Output

13-1

 解题思路:

   对于这道题,一开始我是很单纯的,直接写了个程序提交,结果TLE···好吧,这道题的思路,其实题目已经给出了,二分查找。

附代码:

#include<bits/stdc++.h>using namespace std;int a[3000001];int demo(int m,int x,int y);int main(){    int n,i,m,N;   scanf("%d",&n);   for(i=1;i<=n;++i)   {       scanf("%d",&a[i]);   }   cin>>N;   while(N--)   {      scanf("%d",&m);     printf("%d\n",demo(m,1,n));   }}int demo(int m,int x,int y){    int b;   while(x<=y)   {       b=(x+y)/2;      if(m==a[b])return b;      else if(m<a[b]) y=b-1;      else x=b+1;   }   return -1;}
解题感受:

  这道题不仅要用二分查找,最后的输入输出还要用c的输入输出,如果用cin,cout的话,同样会超时。


0 0
原创粉丝点击