您的位置:首页 > 其它

1425:sort

2015-09-25 18:41 211 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1425

方法:排序+hash

思路:很明显,由于需要排序的数据已经给出了上下限,而且并不是很大,可以再内存承受的范围内,所以可以考虑使用hash排序。

难点:题目本身不难,但是需要一些注意。首先,开数组的时候要开刀100万,这个数量大小在main函数中是开不出来的。要定义全局变量。其次,数组下标代表的是数据本身,数组下标是没有负数的,因此需要设置一个偏移量,把原来的-50万-50万映射为0-100万。这样就可以正常使用hash表了。

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const long int MAX = 1000000;
const long int OFFSET = 500000;
int hashset[MAX] = {0};
int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        memset(hashset,0,sizeof(hashset));
        int num;
        while(n--)
        {
            scanf("%d",&num);
            hashset[num+OFFSET] = 1;
        }
        int counter = 1;
        for(int i = MAX;i >= 0 && counter <= m;i--)
        {
            if(hashset[i] == 1)
            {
                if(counter == m)
                    printf("%d\n",i-OFFSET);
                else
                    printf("%d ",i-OFFSET);
                counter++;
            }
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: