C++实现优先队列(大根堆)
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int a[maxn];
bool vis[maxn];
int parent(int i)
{
return i / 2;
}
int left(int i)
{
return 2 * i;
}
int right(int i)
{
return 2 * i + 1;
}
void Insert(int id) // id代表第几个元素(输入顺序)
{
cin >> a[id];
vis[id] = true; // 标记这个元素已被插入
while (id != 1) // 当元素不是根时
{
int par_id = parent(id);
if (vis[id] && vis[par_id] && a[id] > a[par_id])
swap(a[id], a[par_id]);
id = par_id;
continue;
}
}
void init(int n)
{
for (int i = 1; i <= n; i++)
Insert(i);
}
void show(int n)
{
for (int i = 1; i <= n; i++)
cout << a[i] << " ";
cout << endl;
}
int main()
{
int n;
cin >> n;
init(n);
show(n);
return 0;
}