zoukankan      html  css  js  c++  java
  • Priority_Queue C++

    优先队列:

    计算机科学中的一类抽象数据类型。优先队列中的每个元素都有各自的优先级,优先级最高的元素最先得到服务;优先级相同的元素按照其在优先队列中的顺序得到服务。优先队列往往用来实现。

     1 #pragma once
     2 #include<vector>
     3 #include<stdexcept>//runtime_error
     4 #include<iostream>
     5 #include"HEAPSORT.h"
     6 
     7 int Heap_Maximum(std::vector<int>& A)
     8 {
     9     return A[0];
    10 }
    11 
    12 
    13 //取最大值并删除
    14 int Heap_Extract_Max(std::vector<int>& A)
    15 {
    16     heap_size = A.size() - 1;
    17     Build_Max_Heap(A);
    18     /*
    19     try
    20     {
    21         if (heap_size < 0)
    22             throw std::runtime_error("heap underflow");
    23     }
    24     catch (std::runtime_error err)
    25     {
    26         std::cout << err.what()
    27             << "
     Try Again? Enter y or n" << std::endl;
    28         char c;
    29         std::cin >> c;
    30         if (!std::cin || c == 'n')
    31             return -1;
    32     }
    33     */
    34     if (heap_size < 0)
    35         throw std::runtime_error("heap underflow");
    36     int max = A[0];
    37     A[0] = A[heap_size];
    38     --heap_size;
    39     Max_Heapify(A, 0);
    40     return max;
    41 }
    42 //改变(变大)节点里面的值
    43 void Heap_Increase_Key(std::vector<int>& A, int& i, const int& key)
    44 {
    45     if (key < A[i])
    46         throw std::runtime_error("new key is small than current key");
    47     A[i] = key;
    48     //保持最大堆
    49     while (i > 0 && A[parent(i)] < A[i])
    50     {
    51         std::swap(A[i], A[parent(i)]);
    52         i = parent(i);
    53     }
    54 }
    55 //在末尾处插入键值
    56 void Max_Heap_Insert(std::vector<int>& A, const int& key)
    57 {
    58     ++heap_size;
    59     A[heap_size] = INT_MIN;
    60     Heap_Increase_Key(A, heap_size, key);
    61 }

    main.cpp

     1 #include<iostream>
     2 #include<iterator> //ostream_iterator
     3 #include"PRIORITY_QUEUE.h"
     4 using namespace std;
     5 void print(vector<int>& v)
     6 {
     7     ostream_iterator<int> out_iter(cout, " ");
     8     copy(v.begin(), v.end(), out_iter);
     9 }
    10 void Priority_Queue()
    11 {
    12     vector<int> v = { 4,1,3,2,16,9,10,14,8,7 };
    13     print(v);
    14     cout << endl;
    15     cout << Heap_Extract_Max(v) << endl;
    16     Max_Heap_Insert(v, 15);
    17     cout<<Heap_Maximum(v) << endl;
    18     HeapSort(v);
    19     print(v);
    20 }
    21 int main()
    22 {
    23     Priority_Queue();
    24 }
  • 相关阅读:
    【排序】题解_P1093奖学金
    简单了解连接服务器的要求
    centos7安装(纯文字版)
    JAVA虚拟机
    集合
    IO流
    反射
    多线程
    JAVA基础
    博客园皮肤文档
  • 原文地址:https://www.cnblogs.com/Z-s-c11/p/13836433.html
Copyright © 2011-2022 走看看