[Algo] 堆結構
1. 經典堆結構
// 1. 經典堆結構(大根堆)
void heapInsert(vector<int> &v, int size, int val)
{
v[size] = val;
int cur = size;
while (v[cur] > v[(cur - 1) / 2]) { swap(v[cur], v[(cur - 1) / 2]); cur = (cur - 1) / 2; }
}
void heapify(vector<int> &v, int size, int index)
{
int left = 2 * index + 1;
while (left < size)
{
int right = left + 1, maxIndex;
if (right >= size || v[left] >= v[right]) maxIndex = left;
else maxIndex = right;
if (v[index] >= v[maxIndex]) return;
swap(v[index], v[maxIndex]);
index = maxIndex;
left = 2 * index + 1;
}
}
2. 堆排序
// 2. 堆排序
void heapSort(vector<int> &v)
{
if (v.size() == 0) return;
// 從頂至底建堆 O(n*log n)
for (int i = 0; i < v.size(); i++) heapInsert(v, i, v[i]);
// 也可以從底至頂建堆 O(n)
// for (int i = v.size() - 1; i >= 0; i--) heapify(v, v.size(), i);
int size = v.size();
while (size > 1)
{
swap(v[0], v[--size]);
heapify(v, size, 0);
}
}
3. 線段重合問題
// 3. 線段重合問題
int maxSegOverlap(vector<pair<int, int>> &v)
{
sort(v.begin(), v.end(), [](pair<int, int> p1, pair<int, int> p2){ return p1.first < p2.first; });
priority_queue<int, vector<int>, greater<int>> heap;
int ans = 0;
for (int i = 0; i < v.size(); i++)
{
while (!heap.empty() && heap.top() <= v[i].first) heap.pop();
heap.push(v[i].second);
ans = heap.size() > ans ? heap.size() : ans;
}
return ans;
}