数据结构与算法题目集(中文)7-5 堆中的路径 (25分) (make_heap函数的使用)

1.题目

将一系列给定数字插入一个初始为空的小顶堆H[]。随后对任意给定的下标i,打印从H[i]到根结点的路径。

输入格式:

每组测试第1行包含2个正整数N和M(≤1000),分别是插入元素的个数、以及需要打印的路径条数。下一行给出区间[-10000, 10000]内的N个要被插入一个初始为空的小顶堆的整数。最后一行给出M个下标。

输出格式:

对输入中给出的每个下标i,在一行中输出从H[i]到根结点的路径上的数据。数字间以1个空格分隔,行末不得有多余空格。

输入样例:

5 3
46 23 26 24 10
5 4 3

输出样例:

24 23 10
46 23 10
26 10

2.题目分析

题目中是给出相应的数据,从而建立小根堆之后输出相应要求的下标的数据

1.小根堆:父节点的值小于或等于子节点的值

大根堆:父节点的值大于或等于子节点的值

2.make_heap()函数:是生成一个堆,大顶堆或小顶堆

push_heap()函数:是向堆中插入一个元素,并且使堆的规则依然成立

pop_heap()函数:是在堆的基础上,弹出堆顶元素。

3.代码

#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
int main()
{
	int n, m;
	while (cin >> n >> m)
	{
		vector<int>list;
		for (int i = 1; i <= n; i++)
		{
			int temp;
			cin >> temp;
			list.push_back(temp);

			make_heap(list.begin(), list.end(), greater<int>());//注意一定要写在for循环中!!!!!!
		}
		int b[1001];
		for (int i = 0; i < n; i++)
		{
			b[i + 1] = list[i];
		}

		int key;
		int count = 0;
		for(int i=1;i<=m;i++)
		{
			cin >> key;
			count = 0;
		while(key)
			{
				if (count == 0)
				{
					cout << b[key];
					count++;
				}
				else
				{
					cout << " " << b[key];
				}
				key /= 2;
			}
			cout << endl;
		}

	}

}

原文地址:https://www.cnblogs.com/Jason66661010/p/12789030.html