鍍金池/ 問答/C++/ 這段C++代碼(最大堆)有什么非法操作么?

這段C++代碼(最大堆)有什么非法操作么?

OJ上的一道很經(jīng)典的題目:從大到小輸出一段數(shù)組中的前K大的數(shù)。
我的算法是建立一個大頂堆,然后刪除K次,就得到了前K大的數(shù)。
同樣的數(shù)據(jù)本地上編譯運(yùn)行都沒問題,但是提交到OJ上就Runtime Error

#include <iostream>
using namespace std;

long long N,K;
long long * maxHeap;
long long size = 0;

void insertItem(long long * maxHeap)
{
    long long item;
    cin >> item;
    long long pos = ++size;
    for  ( pos; maxHeap[pos / 2] <= item; pos /= 2 )    maxHeap[pos] = maxHeap[pos / 2];
    maxHeap[pos] = item;
}

long long deleteItem(long long * maxHeap)
{
    long long max_item = maxHeap[1];
    long long item = maxHeap[size--];
    long long parent = 1;
    long long child;
    for ( parent; parent * 2 <= size; parent = child ) {
        child = parent * 2;
        if ( child < size && maxHeap[child] < maxHeap[child + 1] )    child++;
        if ( item > maxHeap[child] )    break;
        else    maxHeap[parent] = maxHeap[child];
    }
    maxHeap[parent] = item;    
    return max_item;
}

int main()
{
//    freopen("F://input.txt","r",stdin);
    cin >> N;
    maxHeap = new long long[N];
    maxHeap[0] = 1000000000;
    for ( long long i = 0; i < N; i++ )    insertItem(maxHeap);
    cin >> K;
    for ( long long i = 0; i < K; i++ )    cout << deleteItem(maxHeap) << endl;
    delete[] maxHeap;
    return 0;
}
input:
19
11 2132 45 445 654 34 44 5645 68 455 32 56 51 63 47 453 554 655 761
10

output
5645
2132
761
655
654
554
455
453
445
68

可以看到這個輸入數(shù)據(jù)并不是邊界數(shù)據(jù),但是不知道我的代碼出了什么問題,求解。

回答
編輯回答
巷尾

知道了,數(shù)組越界了= =,主函數(shù)里面maxHeap = new long long[N]改為maxHeap = new long long[N + 1]。因?yàn)槭菑南聵?biāo)為1開始建立的。

2018年4月1日 14:51