zoukankan      html  css  js  c++  java
  • 堆排序

    make_heap, push_heap, pop_heap, sort_heap

    “堆”定义
      n个关键字序列Kl,K2,…,Kn称为(Heap),当且仅当该序列满足如下性质(简称为堆性质):
      (1)ki<=k(2i)且ki<=k(2i+1)(1≤i≤ n),当然,这是小根堆,大根堆则换成>=号。//k(i)相当于二叉树的非叶结点,K(2i)则是左孩子,k(2i+1)是右孩子
      若将此序列所存储的向量R[1..n]看做是一棵完全二叉树的存储结构,则堆实质上是满足如下性质的完全二叉树:
      树中任一非叶结点的关键字均不大于(或不小于)其左右孩子(若存在)结点的关键字。

     看如下代码:

    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <stdarg.h>
    #include <stdio.h>
    using namespace std;

    template <class _T>
    class Dump
    {
    public:
        void operator()(const _T& t){cout << t << ",";}
        //void operator()(_T& t){cout << t << ",";}
    };

    template <class _T>
    void dump_container(const _T& t)
    {
        for_each(t.begin(), t.end(), Dump<typename _T::value_type>());
        cout << endl;
    }

    int main () {
      int myints[] = {10,20,30,5,15};
      vector<int> v(myints,myints+5);
      vector<int>::iterator it;

      make_heap (v.begin(),v.end());
      cout << "initial  : " ;
      dump_container(v);

      pop_heap (v.begin(),v.end()); v.pop_back();
      cout << "max heap after pop : ";
      dump_container(v);

      v.push_back(99); push_heap (v.begin(),v.end());
      cout << "max heap after push: " ;
      dump_container(v);

      sort_heap (v.begin(),v.end());

      cout << "final sorted range :";
      dump_container(v);;

      cout << endl;

      return 0;
    }
     

    输出结果为:

    $ a.exe
    initial  : 30,20,10,5,15,
    max heap after pop : 20,15,10,5,
    max heap after push: 99,20,10,5,15,

    final sorted range :5,10,15,20,99

  • 相关阅读:
    Atcoder Regular Contest 123 题解
    Atcoder Grand Contest 015 F Kenus the Ancient Greek(找性质+乱搞)
    Solution 「CF 575G」Run for beer
    Solution 「CF 510E」Fox And Dinner
    Solution 「洛谷 P4389」付公主的背包
    Solution 「CF 555E」Case of Computer Network
    Solution 「CF 802C」Heidi and Library (hard)
    Solution 「JOISC 2020」「UOJ #509」迷路的猫
    Div弹出框
    JS对话框
  • 原文地址:https://www.cnblogs.com/hbt19860104/p/2678339.html
Copyright © 2011-2022 走看看