数据结构实验之查找六:顺序查找

来源:互联网 发布:asmr德叔是哪国人 知乎 编辑:程序博客网 时间:2024/06/08 10:33

数据结构实验之查找六:顺序查找
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
Problem Description
在一个给定的无序序列里,查找与给定关键字相同的元素,若存在则输出找到的元素在序列中的位序和需要进行的比较次数,不存在则输出”No”,序列位序从1到n,要求查找从最后一个元素开始,序列中无重复元素。

Input
连续多组数据输入,每组输入数据第一行首先输入两个整数 n (n <= 10^6) 和 k (1 <= k <= 10^7),n是数组长度,k是待查找的关键字,然后连续输入n个整数 ai (1 <= ai <= 10^7),数据间以空格间隔。

Output
若存在则输出元素在序列中的位序和比较次数,不存在则输出No。

Example Input
5 9
4 6 8 9 13
7 4
-1 3 2 5 4 6 9
20 90
4 6 8 9 13 17 51 52 54 59 62 66 76 78 80 85 88 17 20 21
Example Output
4 2
5 3
No
Hint
本题数据量较大,如果你使用 C++ 的 cin 读入,建议在 main 函数开头加入一行 ios::sync_with_stdio(false); 以防止读入超时。

Author
xam

#include <iostream>#include <stdio.h>#include <string.h>using namespace std;const int MAX = 1000005;int a[MAX];int main(){    ios::sync_with_stdio(false);    int n, k;    while (cin >> n >> k)    {        int i;        for (i = 1; i <= n; i++)            cin >> a[i];        int sum = 0;        int flag = 1;        int pos;        for (i = n; i > 0; i--)        {   sum++;            if (a[i] == k)            {                pos = i;                flag = 0;                break;            }        }        if (flag)            cout << "No" << endl;        else cout << pos << " " << sum << endl;    }    return 0;}
原创粉丝点击