東京工業大学 情報理工学院 数理・計算科学系 2016年8月実施 午前 問8
Author
GPT-5
Description
A nearly complete binary tree is filled on all levels except possibly the deepest, which is filled from the left. Indexing its nodes from 0 in level order gives an array representation . It is a heap when
for every non-root node .
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| 15 | 12 | 10 | 11 | 8 | 9 | 7 | 6 | 3 | 2 |
The height of a node is the number of edges on its longest path to a leaf. The following properties may be used.
- (P1) The root of an -element heap has height .
- (P2) The number of nodes of height is at most .
The following code constructs a heap.
void heapify(int a[], int i, int n) {
int k = 2*i+1; /* node k is the left child of node i */
while (k < n) {
if (k+1 < n && a[k+1] > a[k]) k = k+1;
if (a[i] >= a[k]) return;
int tmp = a[i];
a[i] = a[k];
a[k] = tmp;
i = k; k = 2*i+1;
}
}
void build_heap(int a[], int n) {
for (int i = n-1; i >= 0; i--) {
heapify(a, i, n);
}
}
(1) Find the number of different 7-element heaps containing all integers from 1 to 7.
(2) Run build_heap(a1,10) for and give the resulting array.
(3) Explain why heapify(a,i,n) takes time for a node of height .
(4) Show using (P1), (P2), and that build_heap(a,n) takes time.
题目描述
一棵近似完全二叉树除最深层外各层均填满,最深层的结点从左向右填充。按层序从 开始给结点编号,可得到数组表示 ;若每个非根结点 都满足
则称其为堆。题面给出的树形图及对应表格展示了数组
所表示的一个堆。结点的高度定义为从该结点到叶结点的最长路径所含边数。可以使用以下性质:
- (P1) 含 个元素的堆,其根结点高度为 ;
- (P2) 高度为 的结点至多有 个。
给定题面中的 C 代码:heapify(a,i,n) 从结点 开始,反复选择两个孩子中键值较大者;若父结点已不小于它便返回,否则交换并继续向下;build_heap(a,n) 则按 的顺序对每个结点调用 heapify。回答:
-
求由整数 至 各使用一次所能构成的不同七元素堆的数量。
-
对
执行
build_heap(a1,10),写出执行结束后的数组。 -
说明为什么对高度为 的结点,
heapify(a,i,n)的运行时间为 。 -
使用 (P1)、(P2) 以及
证明
build_heap(a,n)的运行时间为 。
考点
- 二叉堆的结构与计数:利用完全二叉树形状和父结点不小于子结点的约束,计算指定键集合的合法堆数。
- 下沉式堆化过程:逐步追踪
heapify的比较与交换,求给定数组经自底向上建堆后的排列。 - 建堆复杂度分析:按结点高度汇总每次下沉的代价,并结合高度结点数上界与给定级数证明总复杂度为线性级。
Kai
(1)
根には最大値 7 を置く必要がある。残り 6 個から左の 3 頂点部分木に置く値を選ぶ方法は 通りである。各 3 頂点部分木では最大値が根に決まり、残り 2 値の左右への配置が 2 通りある。したがって
(2)
値が変化する呼び出しを追うと次のようになる。
| 処理後 | 配列 |
|---|---|
| 初期状態( の処理後も同じ) | |
よって
(3)
ループ 1 回の比較・交換は定数時間であり、交換後は注目節点が子へ 1 段下がる。高さ の節点から葉まで高々 段なので、反復回数は高々 、実行時間は である。
(4)
とし、高さ の節点数を とする。葉を含む各呼び出しの定数時間を 、下向き処理を節点当たり 以下と評価すると、(P2) より
かつ なので