search

Home  >  Q&A  >  body text

c++ - 一道hash算法题目

题目描述:给你n个整数,请按从大到小的顺序输出其中前m大的数
输入:每组测试数据有两行,第一行有两个数n,m(0<n,m<1000000),第二行包含n个各不相同,且都处于区间[-500000,500000]的整数
输出:对每组测试数据按从大到小的顺序输出前m大的数

这是我的代码:

只要一运行就报错,一下是报错的情况:

请教大家为什么程序运行不了呢,编译是正确的,十分感谢大家。

怪我咯怪我咯2803 days ago565

reply all(4)I'll reply

  • 黄舟

    黄舟2017-04-17 14:46:13

    Everyone said that there is a problem with the open array of the topic, so I will put the code of the topic into OJ and run it

    PS: There is a pitfall in the output format of the questioner. According to the principle of allowing the questioner to understand and make minimal modifications, I have improved your code

    #include <stdio.h>
    #define N 500000
    int main() {
        int n, m;
        int t[1000001];
        while(scanf("%d%d", &n, &m) != EOF) {
            for(int i = 0; i <= 1000000; i++) {
                t[i] = 0;
            }
            while(n--) {
                int x;
                scanf("%d", &x);
                t[x+N]=1;
            }
            int num=0;
            for (int i = 1000000; i>=0; i--) {
                if (num==m) {
                    printf("\n");
                    break;
                }
                else if(t[i]==1) {
                    printf("%d", i-N); // 这里没有空格了
                    num++;
                    if (num != m){
                        printf(" "); // 这里是个坑, 因为最后一个输出是没有空格的
                    } 
                }
            }
        }
        return 0;
    }

    HDU

    Nine Degrees


    As mentioned in the title, the Hash algorithm is not a sorting problem.

    This is a basic ACM question. Take the input number and add 500000 to avoid negative numbers as keys. Value is the number of occurrences. If the value is entered, it will be sorted directly.

    Then when outputting, just output the keys whose value is not 0

    Many answers online

    http://www.cnblogs.com/acmer-...

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 14:46:13

    Open such a large array on the stack?

    You don’t need to ask this kind of postgraduate entrance examination question.

    reply
    0
  • 黄舟

    黄舟2017-04-17 14:46:13

    1. Define t to the heap
    2. Enter n and m and then judge the size relationship. Is it better?

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 14:46:13

    If your array is too large, it is very likely that the stack will explode. You can try to use new to apply for an array.

    reply
    0
  • Cancelreply