堆 C++實現
阿新 • • 發佈:2019-01-27
以 codevs1076 排序為例;
手打堆:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 100000 + 10;
int n, cnt = 0;
int heap[MAXN];
void push(int x)
{
heap[++cnt] = x;
int now = cnt;
while(now >= 1)
{
int fa = now/2;
if(heap[fa] > heap[now])
{
swap(heap[fa], heap[now]);
now /= 2;
}
else break;
}
}
void pop()
{
heap[1] = heap[cnt];
cnt --;
int now = 1;
while(now*2 <= cnt)
{
int l = now*2, r = now*2+1;
if (heap[l] < heap[now])
{
if(heap[r] < heap[now] && heap[r] < heap[l])
swap(l,r);
swap(heap[l], heap[now]);
now = l;
}
else if(heap[r] < heap[now])
{
swap(heap[r], heap[now]);
now = r;
}
else break;
}
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i ++)
{
int t;
scanf("%d", &t);
push(t);
}
while(n --)
{
printf("%d ", heap[1]);
pop();
}
return 0;
}
priority_queue 加過載。
記得 priority 是預設大根堆並且內部用 < 排序, 所以需要過載 < 為 > 而不是 過載 > 為 <;
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
using namespace std;
struct T{
int a;
};
priority_queue <T> q;
bool operator < (T a, T b)
{
return a.a > b.a;
}
int main()
{
int n;
cin >> n;
for(int i = 1; i <= n; i++)
{
int t;
scanf("%d",&t);
q.push((T){t});
}
while(q.size())
{
printf("%d ", q.top().a);
q.pop();
}
return 0;
}