顺序表应用6:有序顺序表查询
Time Limit: 1000 ms Memory Limit: 4096 KiB
Submit Statistic Discuss
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
Hint
Source
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LISTSIZE 100001
#define LISTINCREASEMENT 100
typedef struct
{
int *elem;
int listsize;
int length;
}S;
void Initlist(S&L)
{
L.elem=(int*)malloc(LISTSIZE*sizeof(int));
L.length=0;
L.listsize=LISTSIZE;
}
void Listinsert(S&L,int i,int e)
{
if(L.length>L.listsize)
{
L.elem=(int*)realloc(L.elem,(LISTINCREASEMENT+L.listsize)*sizeof(int));
L.listsize+=LISTINCREASEMENT;
}
L.elem[i]=e;
L.length++;
}
int Search(S&L,int s,int t,int e)
{
while(s<=t)
{
int mid=(s+t)/2;
if(L.elem[mid]==e)return mid+1;
else if(L.elem[mid]<e)return Search(L,mid+1,t,e);
else return Search(L,s,mid-1,e);
}
return -1;
}
int main()
{
int n;
scanf("%d",&n);
S L;
Initlist(L);
for(int i=0;i<n;i++)
{
int e;
scanf("%d",&e);
Listinsert(L,i,e);
}
int t;
scanf("%d",&t);
while(t--)
{
int e;
scanf("%d",&e);
int f=Search(L,0,L.length-1,e);
if(f==-1)printf("No Found!\n");
else printf("%d\n",f);
}
return 0;
}