-
Notifications
You must be signed in to change notification settings - Fork 14
/
05-树8 堆中的路径.cpp
60 lines (52 loc) · 954 Bytes
/
05-树8 堆中的路径.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
using namespace std;
#define Min -10001;
struct Heap
{
int *data;
int size;
};
Heap *Create(int N); //建小顶堆;
void Insert(Heap *H, int t); //插入元素;
void Print(Heap *H, int d); //打印路径;
int main()
{
int N, M, i, t;
cin >> N >> M;
Heap *H = Create(N);
for (i = 0; i < N; i++)
{
cin >> t;
Insert(H, t);
}
for (i = 0; i < M; i++)
{
cin >> t;
Print(H, t);
}
return 0;
}
Heap *Create(int N)
{
Heap *H = new Heap;
H->data = new int[N + 1]; //堆都是从下标1的位置开始存储;
H->size = 0;
H->data[0] = Min;
return H;
}
void Insert(Heap *H, int t)
{
int i = ++H->size; //先插入最后一个位置, 然后依次往上过滤;
for (i = H->size; t < H->data[i / 2]; i /= 2)
H->data[i] = H->data[i / 2];
H->data[i] = t;
}
void Print(Heap *H, int d)
{
int i;
cout << H->data[d];
for (i = d / 2; i > 0; i /= 2)
cout << ' ' << H->data[i];
cout << endl;
return;
}