2 solutions

  • 1
    @ 2025-8-17 10:47:43
    #include<bits/stdc++.h>
    using namespace std;
    void read(int &h){
        char o;
        int x=0,y=1;
        o=getchar_unlocked();
        while(!(o<='9'&&o>='0')){
            if(o=='-'){
                y=-1;
            }
            o=getchar_unlocked();
        }
        while(o<='9'&&o>='0'){
            x*=10;
            x+=o-'0';
            o=getchar_unlocked();
        }
        h=x*y;
        return ;
    }
    int n,op,cmp;
    priority_queue<int,deque<int>,greater<int>> a;
    int main(){
        //ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
        read(n);
        for(int i=1;i<=n;i++){
            read(op);
            if(op==1){
                read(cmp);
                a.push(cmp);
            }
            if(op==2){
                cout<<a.top()<<"\n";
            }
            if(op==3){
                a.pop();
            }
        }
        return 0;
    }
    
    
    • -1
      @ 2024-11-13 19:53:02

      堆的模板题

      注意要使用小根堆

      其实STL又好用又好写

      #include<bits/stdc++.h>
      using namespace std;
      typedef long long ll;
      const int N=1e6+7;
      namespace Heap {//使用命名空间让代码更易懂
          int h[N];//小根堆
          ll tot=0;//节点数
        
          void update(ll now) {
              while(now){
                  if(h[now/2]>h[now])
                      swap(h[now/2],h[now]);
                  else 
                      break;
                  now/=2;
              }
              return ;
          }//节点向上修改
          void pushup(int x) {
              h[++tot]=x;
              update(tot);
              return ;
          }//新建节点
      
        void pop() {
              ll pos=1;
              swap(h[pos],h[tot--]);
              while(pos*2<=tot){
                  ll minn=pos*2;
                  if(minn+1<=tot&&h[minn+1]<h[minn])minn++;//判断右子节点是否更优
                  if(h[minn]>h[pos])break;
                  swap(h[minn],h[pos]);
                  pos=minn;
              }
              return ;
          }//弹出节点
      }
      int n;
      int main(){
          cin>>n;
          while(n--){
              int opt;
              cin>>opt;
              if(opt==1){
                  int add;
                  cin>>add;
                  Heap::pushup(add);
              }
              if(opt==2){
                  cout<<Heap::h[1]<<'\n';
              }
              if(opt==3){
                  Heap::pop();
              }
          }
          return 0;
      }
      
      • 1

      Information

      ID
      7408
      Time
      1000ms
      Memory
      512MiB
      Difficulty
      5
      Tags
      # Submissions
      73
      Accepted
      36
      Uploaded By