STL堆之四

#include<iostream>                    //自定义比较函数
#include<algorithm>
#include
<cstring>
#include
<stdio.h>
using namespace std;
#define maxn 100010
struct node
{
char name[11];
int mark;
}heap[
2][maxn]; //heap[0],heap[1]分别表示大顶堆和小顶堆
bool myless(const node& a,const node& b) //大顶堆比较函数
{
return a.mark<b.mark;
}
bool mygreater(const node& a,const node& b) //小顶堆比较函数
{
return a.mark>b.mark;
}
int tail[2]; //tail[0],tail[1]分别表示大顶堆和小顶堆的长度
void insert(node p,int id)
{
heap[id][tail[id]
++]=p;
if (id==1)
push_heap(heap[id],heap[id]
+tail[id],mygreater); //小顶堆
//进堆是先把要放进堆的元素放到容器的尾端(heap[id][tail[id]]),接着tail[id]++,然后再调用push_heap,把整体的堆区间作为参数传进去,调整好成新堆
else
push_heap(heap[id],heap[id]
+tail[id],myless);
}
void remove(int id)
{
if (id==1)
pop_heap(heap[id],heap[id]
+tail[id]--,mygreater); //小顶堆
//出堆的做法是先调用pop_heap,把堆顶点移到最后(这时tail[id]值还没发生改变),然后tail[id]--,相当于从容器弹出最后的元素
else
pop_heap(heap[id],heap[id]
+tail[id]--,myless);
}
int main()
{
tail[
0]=tail[1]=0;
int mark;char name[11];
for(int i=0;i<3;++i)
{
scanf(
"%s %d",name,&mark);
node p;
p.mark
=mark;
strcpy(p.name,name);
insert(p,
1); //压入小顶堆
}
for(int i=0;i<3;++i) //输入 abc 123 efd 120 wqa 125 输出120 123 125
{
cout
<<heap[1][i].mark<<" ";
}

return 0;
}

  

posted on 2011-08-24 16:15  sysu_mjc  阅读(164)  评论(0编辑  收藏  举报

导航