C ++堆未知错误

时间:2018-01-30 17:23:52

标签: c++ heap

任务是从用户获取一串输入并将它们插入堆中。但是,如果输入的数字等于0,则应该从堆中提取最大数量。它不起作用,程序以“退出非零状态”结束。我想知道这个错误来自何处以及如何解决它

#include <iostream>
using namespace std;

int heapsize = 0;

int PARENT(int i){
    return i/2;
}

int LEFT(int i){
    return 2*i;
}

int RIGHT(int i){
    return 2*i+1;
}

void MAX_HEAPIFY(int A[], int i){
    int l = LEFT(i);
    int r = RIGHT(i);
    int L;
    if(l <= heapsize && A[l] > A[i]){
        L = l;
    }
    else int L = i;
    if(r <= heapsize && A[r] > A[L]){
        L = r;
    }
    if(L != i){
        int tym = A[i];
        A[i] = A[L];
        A[L] = tym;
        MAX_HEAPIFY(A,L);
    }
}
void HEAP_INCREASE_KEY(int A[],int i,int key){
  int temp;
  if (key<A[i]){
    cout<<"error"<<endl;
  }else{
    A[i]=key;
    while(i>1 && A[PARENT(i)]<A[i]){
      temp = A[i];
      A[i] = A[PARENT(i)];
      A[PARENT(i)]= temp;
      i = PARENT(i);

    }
  }
}
void MAX_HEAP_INSERT(int A[], int key){
  if(heapsize==(sizeof(A)/sizeof(A[0]))-1){
    cout<<"error"<<endl;
    }else{
      heapsize++;
      A[heapsize] = key;
      HEAP_INCREASE_KEY(A, heapsize, key);
    }

}



void BUILD_MAX_HEAP(int A[]){
    for(int i = heapsize/2; i >= 1; i--){
        MAX_HEAPIFY(A,i);
    }
}
void HEAP_EXTRACT_MAX(int A[]){
  if(heapsize==0){
      cout<<"error"<<endl;
      }else{
      int x;
      x=A[1];
      A[1]=A[heapsize];
      heapsize = heapsize-1;
      MAX_HEAPIFY(A,1);
      cout<<x<<endl;
      }
}
int main() {
    int n;
    int A[100000];
    int Z;

    cin >> n;
    for(int i=0;i<n;i++){
        cin >> Z;
        if(Z == 0){

            HEAP_EXTRACT_MAX(A);
        }else{
            MAX_HEAP_INSERT(A,Z);
        }
        n--;
    }



    return 0;
}

0 个答案:

没有答案