原题
点此路径1
题目分析
本题主要考察的是堆算法的理解,可以按照课本(高等教育出版社-陈越-《数据结构》)P146中的堆插入算法构件。
值得一提的是课本提出了两种堆建立算法,P146的插入算法,P150中更快的构件算法。上述两种算法得到的结果不相同,并且后者的速度更快。按照样例输出应该是使用前者。
代码
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <string>
#include <array>
using namespace std;
class Heap;
typedef Heap *PHeap;
class Heap
{
public:
int Size()
{
//return static_cast<int>(data.size()) - 1;
return size;
}
int Data(int index)
{
return data[index];
}
void Swap(int left, int right)
{
std::swap(data[left], data[right]);
}
int Top()
{
return data[1];
}
int Bottom()
{
//return data.back();
return data[Size()];
}
bool IsEmpty()
{
return !Size();
}
void Print(int index)
{
while (index <= Size())
{
if (index == Size())
cout << data[index] << endl;
else
cout << data[index] << " ";
index++;
}
}
void push_back(int value)
{
data[++size] = value;
}
void pop_back()
{
--size;
}
void Print2Root(int index)
{
while (index != -1)
{
auto father = FatherIndex(index);
if (father == -1)
cout << data[index] << endl;
else
cout << data[index] << " ";
index = father;
}
}
int LeftIndex(int index)
{
auto tmp = index * 2;
if (tmp > Size())
return -1;
else
return tmp;
}
int RightIndex(int index)
{
auto tmp = index * 2 + 1;
if (tmp > Size())
return -1;
else
return tmp;
}
int FatherIndex(int index)
{
if (index == 1)
return -1;
return index / 2;
}
Heap()
{
//data.push_back(0);
data[0] = 0;
}
// vector<int> data;
int data[1001];
size_t size=0;
};
void Insert(PHeap heap, int v)
{
heap->push_back(v);
auto now = heap->Size();
for (auto father = heap->FatherIndex(now); father != -1; now = father, father = heap->FatherIndex(now))
{
if (heap->Data(father) > heap->Data(now))
heap->Swap(father, now);
else
break;
}
}
void CheckHeap(PHeap heap, int index)
{
auto parent = index;
for (auto kid = heap->LeftIndex(parent); kid != -1; parent = kid, kid = heap->LeftIndex(parent))
{
auto right = heap->RightIndex(parent);
if (right != -1 && heap->Data(kid) > heap->Data(right))
kid = right;
if (heap->Data(parent) > heap->Data(kid))
heap->Swap(kid, parent);
else
break;
}
}
int DeleteMin(PHeap heap)
{
if (heap->IsEmpty())
return -1;
auto top = heap->Top();
heap->data[1] = heap->Bottom();
heap->pop_back();
CheckHeap(heap, 1);
return top;
}
void ConstructHeap(PHeap heap)
{
if (heap->IsEmpty() || heap->Size() == 1)
return;
for (auto i = heap->Size() / 2; i > 0; i--)
CheckHeap(heap, i);
}
int main()
{
int n, outSum;
cin >> n >> outSum;
Heap heap;
for (auto i = 0; i < n; i++)
{
int tmp;
cin >> tmp;
//heap.data.push_back(tmp);
Insert(&heap, tmp);
}
//ConstructHeap(&heap);
vector<int> outIndex;
for (auto i = 0; i < outSum; i++)
{
int tmp;
cin >> tmp;
heap.Print2Root(tmp);
}
system("pause");
return 0;
}