MemoryGarden's Blog

努力 -----------大能猫

C++博客 首页 新随笔 联系 聚合 管理
  118 Posts :: 11 Stories :: 20 Comments :: 0 Trackbacks
from  -> introdution to algorithms

大体和堆差不多。贴个代码

#include <stdio.h>
#include 
<string.h>
int a[100], heapsize, n;

int parent(int i){
    
return i / 2;
}

int left(int i){
    
return i * 2;
}

int right(int i){
    
return i * 2 + 1;
}

void heapfy(int i){
    
int largest = i, l = left(i), r = right(i), t;
    
if(l <= heapsize && a[l] > a[i])largest = l;
    
if(r <= heapsize && a[largest] < a[r])largest = r;
    
if(largest != i){
        t 
= a[i];
        a[i] 
= a[largest];
        a[largest] 
= t;
        heapfy(largest);
    }
}

void push(){   //插入的节点直接放到叶子上就可以,然后heapsize++, 再沿根向上,保持堆的性质。
    int i = ++heapsize, t;
    
while(i > 1 && a[parent(i)] < a[i]){
        t 
= a[i];
        a[i] 
= a[parent(i)];
        a[parent(i)] 
= t;
        i 
= parent(i);
    }
}

void pop(){
    
int t;
    t 
= a[1];
    a[
1= a[heapsize];
    a[heapsize] 
= t;
    heapsize
--;
    heapfy(
1);
}

int pqmax(){
    
return a[1];
}

int main(){
    freopen(
"pq.in""r", stdin);
    freopen(
"pq.out""w", stdout);
    
int i, j, k;
    
while(scanf("%d"&n) != -1){
        heapsize 
= 0;
        
for(i = 1; i <= n; i++){
            scanf(
"%d"&a[i]);
            push();
        }
        
while(heapsize >= 1){
            printf(
"%d ", pqmax());
            pop();
        }puts(
"");
    }
    
return 0;
}


posted on 2009-09-28 12:16 memorygarden 阅读(393) 评论(0)  编辑 收藏 引用 所属分类: 报告

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理