顺序表应用6:有序顺序表查询
Time Limit: 1000 ms Memory Limit: 4096 KiB
Submit Statistic
Problem Description
顺序表内按照由小到大的次序存放着n个互不相同的整数,任意输入一个整数,判断该整数在顺序表中是否存在。如果在顺序表中存在该整数,输出其在表中的序号;否则输出“No Found!"。
Input
第一行输入整数n (1 <= n <= 100000),表示顺序表的元素个数;
第二行依次输入n个各不相同的有序非负整数,代表表里的元素;
第三行输入整数t (1 <= t <= 100000),代表要查询的次数;
第四行依次输入t个非负整数,代表每次要查询的数值。
保证所有输入的数都在 int 范围内。
Output
输出t行,代表t次查询的结果,如果找到在本行输出该元素在表中的位置,否则本行输出No Found!
Sample Input
10
1 22 33 55 63 70 74 79 80 87
4
55 10 2 87
Sample Output
4
No Found!
No Found!
10
在这里插入代码片#include <iostream>
#include<bits/stdc++.h>
#define max 100001
typedef int element;
using namespace std;
typedef struct
{
element *elem ;
int length;
int size;
}sq;
void initlist(sq &L)
{
L.elem=(element*)malloc(max*sizeof(element));
L.length=0;
L.size=max;
}
void cr(sq &L,int n)
{
int i;
for(i=0;i<n;i++)
{
scanf("%d",&L.elem[i]);
}
}
int cha(sq L,int left,int right,int num) //由于时间限制,必须用到二分查找。
{
while(left<=right)
{
int mid=(left+right)/2;
if(L.elem[mid]<num)
left=mid+1;
else if (L.elem[mid]>num)
right=mid-1;
else
return mid+1;
}
return 0;
}
int main()
{int n,m,i,a[100001],t;
scanf("%d",&n);
sq L;
initlist(L);
cr(L,n);
scanf("%d",&t);
for(i=0;i<t;i++)
scanf("%d",&a[i]);
for(i=0;i<t;i++)
{
int cn=cha(L,0,n,a[i]);
if(cn)
printf("%d\n",cn);
else printf("No Found!\n");
}
return 0;
}
/***************************************************
User name: dj族修仙者121
Result: Accepted
Take time: 80ms
Take Memory: 924KB
Submit time: 2018-09-24 11:45:00
****************************************************/