码迷,mamicode.com
首页 > 编程语言 > 详细

HDU 1425 sort(堆排序/快排)

时间:2016-09-26 12:24:57      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

传送门

Description

给你n个整数,请按从大到小的顺序输出其中前m大的数。

Input

每组测试数据有两行,第一行有两个数n,m(0<n,m<1000000),第二行包含n个各不相同,且都处于区间[-500000,500000]的整数。

Output

对每组测试数据按从大到小的顺序输出前m大的数。

Sample Input

5 3 
3 -35 92 213 -644

Sample Output

213 92 3

1、使用内建sort函数

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int ans[1000001];
int main()
{
    int n,m;
    while (scanf("%d%d",&n,&m) != EOF)
    {
        for (int i = 0;i < n;i++)
        {
            scanf("%d",&ans[i]);
        }
        sort(ans,ans + n);
        printf("%d",ans[n - 1]);
        for(int i = n - 2;m > 1;m--,i--)
        {
            printf(" %d",ans[i]);
        } 
        printf("\n");
    }
    return 0;
} 

2、使用内建优先队列

#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;

int main()
{
    int N,M;
    while (~scanf("%d%d",&N,&M))
    {
        priority_queue<int>que;
        bool first = true;
        int tmp;
        while (N--)
        {
            scanf("%d",&tmp);
            que.push(tmp);
        } 
        while (M--)
        {
            first?printf("%d",que.top()):printf(" %d",que.top());
            que.pop();
            first = false;
        }
        printf("\n");
    }
    return 0;
}

3、使用内部堆函数

#include <cstdio>
#include <algorithm>
using namespace std;

static int a[1000000];

int main()
{
    int i,n,m;
    while(EOF != scanf("%d %d",&n,&m))
    {
        for(i=0;i<n;i++)
            scanf("%d",&a[i]);
        make_heap(a,a+n);
        printf("%d",a[0]);
        for(i=1;i<m;i++)
        {
            pop_heap(a,a+n-i+1);
            printf(" %d",a[0]);
        }
        printf("\n");
    }
    return 0;
}

4、手写堆排序

#include<stdio.h>
#include<string.h>
const int maxn = 1000005;
int heap[maxn],sz = 0;

void push(int x)
{
    int i = sz++;
    while (i > 0)
    {
        int p = (i - 1)/2;
        if (heap[p] >= x)    break;
        heap[i] = heap[p];
        i = p;
    }
    heap[i] = x;
}

int pop()
{
    int ret = heap[0];
    int x = heap[--sz];
    int i = 0;
    while (i*2+1<sz)
    {
        int a = i*2+1,b = i*2+2;
        if (b < sz && heap[b]>heap[a])    a = b;
        if (heap[a] <= x)    break;
        heap[i] = heap[a];
        i = a;
    }
    heap[i] = x;
    return ret;
}

int main()
{
    int n,m,tmp;
    while (~scanf("%d%d",&n,&m))
    {
        sz = 0;
        memset(heap,0,sizeof(heap));
        for (int i = 0;i < n;i++)    scanf("%d",&tmp),push(tmp);
        for (int i = 1;i < m;i++)    printf("%d ",pop());
        printf("%d\n",pop());
    }
    return 0;
}

  

HDU 1425 sort(堆排序/快排)

标签:

原文地址:http://www.cnblogs.com/zzy19961112/p/5908321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!