博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

模拟堆

Posted on 2019-10-22 10:29  淼哥学习园地  阅读(226)  评论(0编辑  收藏  举报

1.堆的基本操作:

    (1)插入

    (2)输出最小值

    (3)删除最小值

    (4)删除第k个插入的数

    (5)修改第k个插入的数

 

堆的核心算法:down() ,up();

问题:

 

  代码:

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int N=100010;

int h[N],hp[N],ph[N],size;
int n,m;


void heap_swap(int a,int b)
{
    swap(h[a],h[b]);
    swap(ph[hp[a]],ph[hp[b]]);
    swap(hp[a],hp[b]);
    
}

向下排序 void down(int u) { int t=u; if(2*u<=size && h[t]>h[2*u]) t=2*u; if(2*u+1<=size && h[t]>h[2*u+1]) t=2*u+1; if(t!=u) { heap_swap(t,u); down(t); } } //向上排序 void up(int u) { int t=u; if(u/2 && h[t] <h[u/2]) t=u/2; if(u!=t) { heap_swap(t,u); up(t); } } int main() { cin>>n; while(n--) { char op[10]; cin>>op; int k,x; if(!strcmp(op,"I")) { cin>>x; size++; m++; ph[m]=size; //第M个插入的数是size hp[size]=m;// size对应第M个插入的数 h[size]=x; up(size); } else if(!strcmp(op,"PM")) cout<<h[1]<<endl; else if(!strcmp(op,"DM")) { heap_swap(1,size); size--; down(1); } else if(!strcmp(op,"D")) { cin>>k; k=ph[k]; //找到第k个插入的数 heap_swap(k,size); size--; up(k); down(k); } } return 0; }