C : DS静态查找之顺序索引查找

Description

给出一个队列和要查找的数值,找出数值在队列中的位置,队列位置从1开始

要求使用顺序索引查找算法,其中索引表查找和块内查找都采用不带哨兵、从头开始的顺序查找方法。

Input

第一行输入n,表示主表有n个数据

第二行输入n个数据,都是正整数,用空格隔开

第三行输入k,表示主表划分为k个块,k也是索引表的长度

第四行输入k个数据,表示索引表中每个块的最大值

第五行输入t,表示有t个要查找的数值

第六行起,输入t个数值,输入t行

Output

每行输出一个要查找的数值在队列的位置和查找次数,数据之间用短划线隔开,如果查找不成功,输出字符串error

Sample

#0

Input

18
22 12 13 8 9 20 33 42 44 38 24 48 60 58 74 57 86 53
3
22 48 86
6
13
5
48
40
53
90

Output

3-4
error
12-8
error
18-9
error

解题思路

一开始忘记了n可能无法整除k,导致在构建每个块的时候出错一直卡了很久

AC代码

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 10010;
int arr[N];
int n, k;

struct indexBlock
{
   
	int start;
	int end;
	int max;
}indexBlocks[N];

int blockSearch(int key, int& cnt)
{
   
	int i = 1, j;

	while (i <= k &&++cnt&& key > indexBlocks[i].max) {
    i++;  }//确认key所在的是哪个子表
	if (i > k)return 0;//i超出了子表的个数,找不到key

	j = indexBlocks[i].start;//j为key所在子表起始下标

	while (j <= indexBlocks[i].end &&++cnt&& arr[j] != key) {
    j++;  }//在确定的块内寻找key
	if (j > indexBlocks[i].end)return 0;//j超出了所在块范围,没有找到key

	return j;
}


int main()
{
   
	while (cin >> n)
	{
   
		for (int i = 1; i <= n; i++)
		{
   
			cin >> arr[i];
		}
		int  j = 0;
		cin >> k;
		for (int i = 1; i <= k; i++)
		{
   
			int max;
			cin >> max;
			indexBlocks[i].start = j + 1;//块的起始下标
			j = j + 1;
			// 找到第一个大于max的数,此时j-1就是块的结束下标
			while (j < n)
			{
   
				j++;
				if (arr[j] > max)
				{
   
					j--;
					break;
				}
			}
			indexBlocks[i].end = j;
			indexBlocks[i].max = max;
		}
		int t;
		cin >> t;
		while (t--)
		{
   
			int key, cnt = 0;
			cin >> key;
			int index = blockSearch(key, cnt);
			if (index)cout  << index << "-" << cnt << endl;
			else cout << "error" << endl;
		}
	}
	return 0;
}

相关推荐

  1. C : DS静态查找顺序索引查找

    2023-12-13 13:06:02       58 阅读
  2. 查找——顺序查找和折半查找

    2023-12-13 13:06:02       33 阅读
  3. python实现--顺序查找

    2023-12-13 13:06:02       42 阅读
  4. 顺序表的查找

    2023-12-13 13:06:02       35 阅读
  5. oj 1.9编程基础顺序查找 09:直方图

    2023-12-13 13:06:02       61 阅读
  6. 王道c语言-顺序查找、二分查找

    2023-12-13 13:06:02       47 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-13 13:06:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-13 13:06:02       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-13 13:06:02       87 阅读
  4. Python语言-面向对象

    2023-12-13 13:06:02       96 阅读

热门阅读

  1. HTB Ouija

    2023-12-13 13:06:02       50 阅读
  2. JRT实现Cache的驱动

    2023-12-13 13:06:02       70 阅读
  3. go标记omitempty的含义

    2023-12-13 13:06:02       55 阅读
  4. c++基于流文件输入输出的综合程序设计

    2023-12-13 13:06:02       59 阅读
  5. 你在地铁上修过bug吗?

    2023-12-13 13:06:02       63 阅读
  6. reactHooks之useDeferredValue

    2023-12-13 13:06:02       69 阅读
  7. 12.12每日一题(备战蓝桥杯循环输出)

    2023-12-13 13:06:02       47 阅读
  8. 总结MySQL 的一些知识点:MySQL 运算符

    2023-12-13 13:06:02       69 阅读
  9. Windows安装卸载MySQL

    2023-12-13 13:06:02       81 阅读