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;
    }

    挺好理解的。

  • 相关阅读:
    (一)maven基本配置,概念,常用命令
    redis 小结
    git 小结
    spring.xml
    servlet web.xml学习笔记
    springmvc小试牛刀
    maven
    springmvc学习笔记1
    springmvcpojo
    springmvc学习笔记
  • 原文地址:https://www.cnblogs.com/DukeLv/p/9251312.html
Copyright © 2011-2022 走看看