zoukankan      html  css  js  c++  java
  • P3378 【模板】堆 小根堆

    题目描述

    如题,初始小根堆为空,我们需要支持以下3种操作:

    操作1: 1 x 表示将x插入到堆中

    操作2: 2 输出该小根堆内的最小数

    操作3: 3 删除该小根堆内的最小数

    输入输出格式

    输入格式:

    第一行包含一个整数N,表示操作的个数

    接下来N行,每行包含1个或2个正整数,表示三种操作,格式如下:

    操作1: 1 x

    操作2: 2

    操作3: 3

    输出格式:

    包含若干行正整数,每行依次对应一个操作2的结果。

    输入输出样例

    输入样例#1: 复制
    5
    1 2
    1 5
    2
    3
    2
    输出样例#1: 复制
    2
    5



    模拟小根堆
    的插入和查询

    #include<bits/stdc++.h>
    using namespace std;
    //input by bxd
    #define rep(i,a,b) for(int i=(a);i<=(b);i++)
    #define repp(i,a,b) for(int i=(a);i>=(b);--i)
    #define RI(n) scanf("%d",&(n))
    #define RII(n,m) scanf("%d%d",&n,&m)
    #define RIII(n,m,k) scanf("%d%d%d",&n,&m,&k)
    #define RS(s) scanf("%s",s);
    #define ll long long
    #define pb push_back
    #define REP(i,N)  for(int i=0;i<(N);i++)
    #define CLR(A,v)  memset(A,v,sizeof A)
    //////////////////////////////////
    #define inf 0x3f3f3f3f
    const int N=100000000+5;
    int heap[N];
    int pos=0;
    
    void push(int x)
    {
        heap[++pos]=x;
        int now=pos;
        while(now)
        {
            int nex=now>>1;
            if(heap[nex]>heap[now])swap(heap[nex],heap[now]);
            else break;
            now=nex;
        }
    }
    void pop()
    {
        swap(heap[1],heap[pos]);
        pos--;
        int now=1;
        while((now<<1)<=pos)
        {
            int nex=now<<1;
            if(nex+1<=pos&&heap[nex+1]<heap[nex])nex++;
            if(heap[now]>heap[nex])swap(heap[now],heap[nex]);
            else break;
            now=nex;
        }
    }
    int main()
    {
        int n;
        RI(n);
        rep(i,1,n)
        {
            int a;RI(a);
            if(a==1)
            {
                int b;RI(b);
                push(b);
            }
            else if(a==2)
            {
                cout<<heap[1]<<endl;
            }
            else if(a==3)
                pop();
        }
        return 0;
    }
    View Code





  • 相关阅读:
    spring 事务配置方式以及事务的传播性、隔离级别
    springmvc 事务控制与数据库隔离级别
    mybatis
    mapper 传多个参数
    ubuntu vim编辑文件保存是出现权限不足
    配置phpmyadmin连接远程 MySQL数据库
    spring mvc Response header content type
    Spring 异常处理三种方式 @ExceptionHandler
    SpringMvc @ResponseBody
    Redhat6.8安装Oracle11g下遇到两个问题记录
  • 原文地址:https://www.cnblogs.com/bxd123/p/10803534.html
Copyright © 2011-2022 走看看