求助 P1177 堆排RE20
  • 板块学术版
  • 楼主zxm_
  • 当前回复1
  • 已保存回复1
  • 发布时间2023/2/13 20:20
  • 上次更新2023/10/24 00:52:13
查看原帖
求助 P1177 堆排RE20
731974
zxm_楼主2023/2/13 20:20

rt

Runtime Error. Received signal 11: Segmentation fault with invalid memory reference.



#include<bits/stdc++.h>
#include<algorithm>
using namespace std;
long long heap[50000]={};
long long heapPointer=1;

void up(int operPointer){
    //cout<<"upping "<<operPointer<<" which has a value "<<heap[operPointer]<<"......\n";
    if(heapPointer>=1 and heap[operPointer]<heap[operPointer/2]){
        int k;
        k=heap[operPointer];
        heap[operPointer]=heap[operPointer/2];
        heap[operPointer/2]=k;
        operPointer=operPointer/2;
        //cout<<"upped to"<<operPointer<<" which has a value "<<heap[operPointer]<<"\n";
        //cout<<"now the heap looks like:";
        for(int i=1;i<=10;i++){
            //cout<<heap[i];
        }//cout<<endl;
        up(operPointer);
    }else{
    //  cout<<"now the heap looks like:";
        for(int i=1;i<=10;i++){
            //cout<<heap[i];
        }//cout<<endl;
        return;
    }
}
void down(int p=1){
    if( (heap[p]>heap[p*2] or heap[p]>heap[p*2+1] ) and p>=1){
        if(heap[p*2]>heap[p*2+1]){
            swap(heap[p],heap[p*2+1]);
            p=p*2+1; 
        }
        if(heap[p*2]<heap[p*2+1]){
            swap(heap[p],heap[p*2]);
            p=p*2;
        }
        down(p);
    }
    else{
        return; 
    } 
}
void insrt(int val){
    //cout<<"inserting "<<heapPointer<<" which has a value "<<val<<"......\n";
    heap[heapPointer]=val;
    up(heapPointer);
    heapPointer++;

}
void eject(){
    swap(heap[1],heap[heapPointer--]);
    int cur=1;
    while(cur*2<=heapPointer){
        int son=cur*2;
        if(son+1<=heapPointer && heap[son+1]<heap[son])son++;
        if(heap[cur]<heap[son])break;
        swap(heap[cur],heap[son]);
        cur=son;
    }
    return ;
}
int main(){
    int n,e;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>e;
        insrt(e);
    }/*
    for(int i=1;i<=20;i++){
            cout<<heap[i];
    }cout<<endl;*/
    while(heapPointer){ 
        if(heap[1]!=0)cout<<heap[1]<<" ";
        eject();
    }
}
2023/2/13 20:20
加载中...