前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >顺序表应用6:有序顺序表查询(SDUT 3330)

顺序表应用6:有序顺序表查询(SDUT 3330)

作者头像
Lokinli
发布2023-03-09 16:23:12
3490
发布2023-03-09 16:23:12
举报
文章被收录于专栏:以终为始以终为始

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

题解:二分+顺序表

代码语言:javascript
复制
#include <bits/stdc++.h>

using namespace std;
const int maxn = 1000005;

struct node
{
    int *elem;
    int len;
    int listsize;
};
void Creatlist(struct node &list, int n)
{
    list.elem=new int[maxn];
    if(!list.elem)
        exit(OVERFLOW);
    for(int i=0; i<n; i++)
    {
        cin>>list.elem[i];
        list.len++;
    }
}
int BSearch(struct node &list, int l,int r,int x)
{
    while(l<=r)
    {
        int m=(l+r)/2;
        if(list.elem[m]<x)
            l=m+1;
        else if (list.elem[m]>x)
            r=m-1;
        else
            return m+1;
    }
    return 0;
}
int main()
{
    int n,m,x;
    struct node list;
    cin>>n;
    Creatlist(list,n);
    cin>>m;
    for(int i=0; i<m; i++)
    {
        cin>>x;
        int ans =BSearch(list,0,n,x);
        if(ans)
            cout<<ans<<endl;
        else
            cout<<"No Found!"<<endl;
    }
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-09-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档