P3378【模板】 堆
阿新 • • 發佈:2018-12-15
P3378【模板】 堆
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 5 int N; 6 int operate; 7 int x; 8 int heap[1000000]; 9 int heap_size; 10 void put(int x) //插入一個數 11 { 12 int now,next; 13 heap[++heap_size]=x; //在末端插入 14 now=heap_size; 15 while(now>1) //如果小於父節點就交換 16 { 17 next=now>>1; 18 if(heap[now]>=heap[next]) return; //退出 19 swap(heap[now],heap[next]); 20 now=next; 21 } 22 } 23 24 int del(int x) //刪除一個數 25 { 26 int now,next,res; 27 res=heap[1]; //heap[1]為堆頂; 28 heap[1]=heap[heap_size--];29 now=1; 30 while(now * 2<=heap_size) 31 { 32 next=now * 2; //左節點 33 if(next<heap_size && heap[next+1]<heap[next]) //如果有右節點且右節點小 34 {next++;} 35 if(heap[now]<=heap[next]) {break;} //退出 36 swap(heap[now],heap[next]);37 now=next; 38 } 39 return res; 40 } 41 42 int top() 43 { 44 return heap[1]; 45 } 46 47 int main() 48 { 49 scanf("%d",&N); 50 for(int i=1;i<=N;i++) 51 { 52 scanf("%d",&operate); 53 if(operate==1) 54 { 55 scanf("%d",&x); 56 put(x); 57 } 58 if(operate==2) 59 { 60 printf("%d\n",top()); 61 } 62 if(operate==3) 63 { 64 del(1); 65 } 66 } 67 68 return 0; 69 }
有stl為什麼不用呢?
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<queue> 5 using namespace std; 6 7 priority_queue<int,vector<int>,greater<int> >q; 8 9 int main() 10 { 11 int n; 12 scanf("%d",&n); 13 for(int i=1;i<=n;i++) 14 { 15 int x; 16 scanf("%d",&x); 17 if(x==1) 18 { 19 scanf("%d",&x);q.push(x); 20 } 21 else if(x==2) printf("%d\n",q.top()); 22 23 else q.pop(); 24 25 } 26 }