4.1a 堆的插入和删除
// P3378【模板】堆 - 洛谷 // 小根堆模板 #include<stdio.h> #include<stdlib.h> #define N 1000005 int H[N],len; //堆数组,堆大小 // 交换元素 void swap(int *a,int *b){ int t=*a; *a=*b; *b=t; } // 堆的插入 void HeapInsert(int H[],int e){ H[++len]=e; //堆底插入新元素 int p=len; //p指向堆底 while(p>1){ //新元素上浮过程 int fa=p/2; if(H[fa]<=H[p]) break; swap(&H[fa],&H[p]); p=fa; } } // 堆的删除 void HeapDelete(int H[]){ H[1]=H[len--]; //堆底替代堆顶 int p=1; //p指向堆顶 while(p*2<=len){ //元素下沉过程 int son=p*2; //左儿子 if(son<len&&H[son+1]<H[son]) son++; //右儿子 if(H[p]<=H[son]) break; swap(&H[p],&H[son]); p=son; } } int main(){ int n,op,e; scanf("%d",&n); while(n--){ scanf("%d",&op); if(op==1) scanf("%d",&e),HeapInsert(H,e); else if(op==2) printf("%d\n",H[1]); else HeapDelete(H); } return 0; }
// P3378【模板】堆 - 洛谷 // 小根堆模板 C++ #include<bits/stdc++.h> using namespace std; int n,op,x; priority_queue<int,vector<int>,greater<int> > q; //小根堆 int main(){ scanf("%d",&n); while(n--){ scanf("%d",&op); if(op==1) scanf("%d",&x), q.push(x); else if(op==2) printf("%d\n",q.top()); else q.pop(); } return 0; }
练习:
class Solution { // C++编译 public: vector<int> topKFrequent(vector<int>& nums, int k){ unordered_map<int, int> mp; //哈希表 for(auto& v : nums){ mp[v]++; //v出现次数 } priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>> > q; //小根堆 for(auto& [num,count] : mp){ if(q.size() == k){ if(q.top().first < count){ q.pop(); q.emplace(count,num); } } else{ q.emplace(count,num); } } vector<int> ret; while(!q.empty()){ ret.emplace_back(q.top().second); q.pop(); } return ret; } };
.
浙公网安备 33010602011771号