hdu 1425 sort用堆排序做的

http://acm.hdu.edu.cn/showproblem.php?pid=1425

View Code
#include <iostream>
#include <stdio.h>
using namespace std;
long heap[1000005];//觉得那个数有点大所以开了长整型
void adjust(long start,long n)
{
    long i;
    long temp;//用来记录当前要交换的值
    temp = heap[start];
    for(i = start*2;i <= n;i *= 2)
    {
        if(i < n&& heap[i] > heap[i+1])//既然是往下推,那么肯定是要找一个孩子中比较小的一个来与temp比较
        i = i+1;
        if(temp < heap[i])//如果heap的值大于temp的值,说明heap的子树中没有比temp的值更小的了
        break;
        heap[start] = heap[i];//此处Start记录的只是上一个交换的坐标,不是只一开始的那一个,在进行第1次交换的时候,Start的位置上补充了新的数,空缺的是当时的i也就是第二次交换时的start
        start = i;//为标记空缺的位置
    }
    heap[start] = temp;//为最后空缺的位置填数,也就是temp应该在的位置。
}
void sort(long n)
{
    long temp,i;
    for(i = n/2;i > 0;i--)
    {
        adjust(i,n);
    }//初建堆
    for(i = n;i > 1;i--)
    {
        temp = heap[1];
        heap[1] = heap[i];//交换堆顶和堆低的值
        heap[i] = temp;
        adjust(1,i-1);//调整为堆
    }
}
int main()
{
    long i,n,j,m;
    while(scanf("%ld %ld",&n,&m) != EOF)
    {
        for(i = 1;i <= n;i++)
        {
            scanf("%ld",heap+i);
        }
        sort(n);
        printf("%ld",heap[1]);
        for(i = 2;i <= m;i++)
        {
            printf(" %ld",heap[i]);
        }
        puts("");
    }

    return 0;
}

 

posted @ 2012-07-21 14:37  某某。  阅读(140)  评论(0编辑  收藏  举报