最小堆插入元素和刪除堆頂(無哨兵元素) 20分

2021-10-05 05:34:10 字數 1539 閱讀 1349

6-1 最小堆插入元素和刪除堆頂(無哨兵元素) (20分)

對於給定的最小堆(優先佇列),分別實現插入元素和刪除堆頂的函式。

函式介面定義:

int insertintoheap(struct heap* h, int x); // 向堆中插入元素x

int deletemin(struct heap* h, int* pelement); //將堆頂元素拷貝到pelement所指變數並刪除堆頂元素

其中,h、x和pelement為引數,h是堆結構體指標,x是待插入元素的值,pelement指向的變數用於存放刪除的堆頂元素。

堆結構體定義如下:

struct heap

;

裁判測試程式樣例:

#include

#include

struct heap

;struct heap*

initheap

(int capacity)

h->capacity = capacity;

h->size =0;

return h;};

void

printheap

(struct heap* h)

intinsertintoheap

(struct heap* h,

int x)

;int

deletemin

(struct heap* h,

int* pelement)

;int

main()

else

scanf

("%d"

,&op);}

return0;

}

/*你提交的**將被嵌在這裡 */

輸入樣例:

對於樣例測試程式規定的輸入格式:

3110

12015

140-1

-1-1

-10

輸出樣例:

樣例測試程式的輸出:

insertion succeeded. 10,

insertion succeeded. 10, 20,

insertion succeeded. 5, 20, 10,

insertion failed. 5, 20, 10,

5 deleted. 10, 20,

10 deleted. 20,

20 deleted.

deletion failed.

int

insertintoheap

(struct heap* h,

int x)

h->data[i]

=x;return1;

}int

deletemin

(struct heap* h,

int* pelement)

h->data[parent]

=temp;

return1;

}

最小堆操作(元素的新增和刪除)

先引用我一直很膜拜的牛人 morewindows 在堆排序中的一段內容,該內容詳細講述了最小堆,以及在最小堆中新增 刪除元素的原理。二叉堆的定義 二叉堆是完全二叉樹或者是近似完全二叉樹。二叉堆滿足二個特性 1 父結點的鍵值總是大於或等於 小於或等於 任何乙個子節點的鍵值。2 每個結點的左子樹和右子樹...

查詢最小的k個元素(堆處理和非堆處理)

查詢最小的k個元素 題目 輸入n個整數,輸出其中最小的k個。例如輸入1,2,3,4,5,6,7和8這8個數字,則最小的4個數字為1,2,3和4。非堆處理 include include using namespace std int main void for int i 0 i k i cout ...

從無序陣列中獲取最小的M個元素(小頂堆實現)

我同學大龍給我出了一道演算法題 給定乙個長度為n無序的陣列,怎麼從中挑選出最小的m個數 m n 我的第一想法就是用快速排序將整個陣列進行排序,然後遍歷排序後的陣列,從中選處m個最小的數。雖然這個方法可行,但是不是最好的。用堆排序的思想就可以很好的解決這個問題。建立小頂堆,然後每次將堆頂最小元素丟擲,...