版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/belous_zxy/article/details/87003113
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using Heap = struct HeapST *;
struct HeapST
{
int *array;
int HeapTop;
};
int getdigit(void)
{
int digit{0}, symbol{1};
bool isp{true};
while (1)
{
char ch = getchar();
if (ch == ' ' || ch == '\n' || ch == EOF || ch == '\t')
{
if (isp)
continue;
return digit * symbol;
}
isp = false;
if (ch == '-')
symbol = -1;
else
digit = digit * 10 + ch - '0';
}
}
void BuildHeap(Heap H, int num)
{
H->array[++H->HeapTop] = num;
int aim{H->HeapTop};
while (num < H->array[aim / 2])
{
H->array[aim] = H->array[aim / 2];
aim /= 2;
H->array[aim] = num;
}
}
void PrintHeap(Heap H, int num)
{
printf("%d", H->array[num]);
num /= 2;
while (num)
{
printf(" %d", H->array[num]);
num /= 2;
}
putchar('\n');
}
Heap CreateHeap(int N)
{
Heap H = static_cast<Heap>(malloc(sizeof(HeapST)));
H->array = static_cast<int *>(malloc(sizeof(int) * (N + 1)));
H->array[0] = 0x80000000;
H->HeapTop = 0;
return H;
}
int main(int argc, char *argv[])
{
int N{getdigit()}, M{getdigit()};
Heap H = CreateHeap(N);
for (auto i = 1; i <= N; ++i)
BuildHeap(H, getdigit());
for (auto i = 1; i <= M; ++i)
PrintHeap(H, getdigit());
return EXIT_SUCCESS;
}
建最小堆->输出指定堆路径,结束。