zoukankan      html  css  js  c++  java
  • 数据结构————手写堆

    之前堆都是直接用stl中的priority_queue,一直不会手写堆,所以今天搞一下这个手写堆。

    洛谷P3378堆的板子

    #include<cstdio>
    #include<iostream>
    using namespace std;
    int tree[2000003],t,n;
    void change(int a,int b)
    {
        int temp = tree[a];
        tree[a] = tree[b];
        tree[b] = temp;
    }
    void del(int x)
    {
        int d = x,f = 0;
        while(x * 2 <= t && f == 0)
        {
            if(tree[x] > tree[x * 2] && x * 2 <= t)
            {
                d = x * 2;
            }
            if(tree[x] > tree[x * 2 + 1] && tree[x * 2 + 1] < tree[x * 2] && x * 2 + 1 <= t)
            {
                d = x * 2 + 1;
            }
            if(x != d)
            {
                change(x,d);
                x = d;
            }
            else
            f = 1;
        }
    }
    void insert(int x)
    {
        int d,f = 0;
        while(x != 1 && f == 0)
        {
            if(tree[x / 2] > tree[x])
            {
                d = x / 2;
                change(x,d);
            }
            else
            f = 1;
            x = x / 2;
        }
    }
    int main()
    {
        scanf("%d",&n);
        int m,k;
        for(int i = 1;i <= n;i++)
        {
            scanf("%d",&m);
            if(m == 1)
            {
                scanf("%d",&k);
                t++;
                tree[t] = k;
                insert(t);
            }
            if(m == 2)
            {
                printf("%d
    ",tree[1]);
            }
            if(m == 3)
            {
                tree[1] = tree[t];
                t--;
                del(1);
            }
        }
        return 0;
    }

    挺好理解的。

  • 相关阅读:
    java操作Redis
    Redis安装和基本操作
    IDEA使用教程+JRebel破解
    java环境配置
    qtp10安装步骤(比较完整)
    c++第一章1.6
    软件测试第二章作业
    c++作业22题
    c++第二周阶段小测2
    oracle12c数据库第一周小测验
  • 原文地址:https://www.cnblogs.com/DukeLv/p/9251312.html
Copyright © 2011-2022 走看看