1. 程式人生 > 其它 >資料結構 _ 基本練習 _ 練習4.3 堆中的路徑 (25 分)

資料結構 _ 基本練習 _ 練習4.3 堆中的路徑 (25 分)

技術標籤:資料結構_基礎

原題

點此路徑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; }