下边所示算法中私有数据有 5 个,理解这五个变量在算法中的作用是理解该算法的关键。

    private int maxN;        // maximum number of elements on PQprivate int n; // number of elements on PQ private int[] pq; // binary heap using 1-based indexing private int[] qp; // inverse of pq - qp[pq[i]] = pq[qp[i]] = i private Key[] keys; // keys[i] = priority of i

  如下图所示,用户依次输入:

  insert(x, key_x)

  insert(y, key_y)

  insert(z, key_z)

  qp[ ], pq[ ],keys[ ] 之间存在如下关系。

  pq[ ],qp[ ] 之间存在一一映射关系,keys[ ]作用是能够通过 index 找到对应的 key 值。

  数据在 pq[ ] 中按照堆形式排列,在 swim(),sink() 中要保持 qp[ ],pq[ ]之间的映射关系不变!!!下边的代码就是实现的对应的功能:

    private void exch(int i, int j) {int swap = pq[i]; pq[i] = pq[j]; pq[j] = swap;

     /*刷新qp[]中的内容,保持映射关系*/ qp[pq[i]] = i; qp[pq[j]] = j; }

/*******************************************************************************  Compilation:  javac IndexMinPQ.java*  Execution:    java IndexMinPQ*  Dependencies: StdOut.java**  Minimum-oriented indexed PQ implementation using a binary heap.*******************************************************************************/package edu.princeton.cs.algs4;import java.util.Iterator;
import java.util.NoSuchElementException;/***  The {@code IndexMinPQ} class represents an indexed priority queue of generic keys.*  It supports the usual <em>insert</em> and <em>delete-the-minimum</em>*  operations, along with <em>delete</em> and <em>change-the-key</em> *  methods. In order to let the client refer to keys on the priority queue,*  an integer between {@code 0} and {@code maxN - 1}*  is associated with each key—the client uses this integer to specify*  which key to delete or change.*  It also supports methods for peeking at the minimum key,*  testing if the priority queue is empty, and iterating through*  the keys.*  <p>*  This implementation uses a binary heap along with an array to associate*  keys with integers in the given range.*  The <em>insert</em>, <em>delete-the-minimum</em>, <em>delete</em>,*  <em>change-key</em>, <em>decrease-key</em>, and <em>increase-key</em>*  operations take logarithmic time.*  The <em>is-empty</em>, <em>size</em>, <em>min-index</em>, <em>min-key</em>,*  <em>contains</em>, and <em>key-of</em> operations take constant time.*  Construction takes time proportional to the specified capacity.*  <p>*  For additional documentation, see <a href="https://algs4.cs.princeton.edu/24pq">Section 2.4</a> of*  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.**  @author Robert Sedgewick*  @author Kevin Wayne**  @param <Key> the generic type of key on this priority queue*/
public class IndexMinPQ<Key extends Comparable<Key>> implements Iterable<Integer> {private int maxN;        // maximum number of elements on PQprivate int n;           // number of elements on PQprivate int[] pq;        // binary heap using 1-based indexingprivate int[] qp;        // inverse of pq - qp[pq[i]] = pq[qp[i]] = iprivate Key[] keys;      // keys[i] = priority of i/*** Initializes an empty indexed priority queue with indices between {@code 0}* and {@code maxN - 1}.* @param  maxN the keys on this priority queue are index from {@code 0}*         {@code maxN - 1}* @throws IllegalArgumentException if {@code maxN < 0}*/public IndexMinPQ(int maxN) {if (maxN < 0) throw new IllegalArgumentException();this.maxN = maxN;n = 0;keys = (Key[]) new Comparable[maxN + 1];    // make this of length maxN??pq   = new int[maxN + 1];qp   = new int[maxN + 1];                   // make this of length maxN??for (int i = 0; i <= maxN; i++)qp[i] = -1;}/*** Returns true if this priority queue is empty.** @return {@code true} if this priority queue is empty;*         {@code false} otherwise*/public boolean isEmpty() {return n == 0;}/*** Is {@code i} an index on this priority queue?** @param  i an index* @return {@code true} if {@code i} is an index on this priority queue;*         {@code false} otherwise* @throws IllegalArgumentException unless {@code 0 <= i < maxN}*/public boolean contains(int i) {if (i < 0 || i >= maxN) throw new IllegalArgumentException();return qp[i] != -1;}/*** Returns the number of keys on this priority queue.** @return the number of keys on this priority queue*/public int size() {return n;}/*** Associates key with index {@code i}.** @param  i an index* @param  key the key to associate with index {@code i}* @throws IllegalArgumentException unless {@code 0 <= i < maxN}* @throws IllegalArgumentException if there already is an item associated*         with index {@code i}*/public void insert(int i, Key key) {if (i < 0 || i >= maxN) throw new IllegalArgumentException();if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue");n++;qp[i] = n;pq[n] = i;keys[i] = key;swim(n);}/*** Returns an index associated with a minimum key.** @return an index associated with a minimum key* @throws NoSuchElementException if this priority queue is empty*/public int minIndex() {if (n == 0) throw new NoSuchElementException("Priority queue underflow");return pq[1];}/*** Returns a minimum key.** @return a minimum key* @throws NoSuchElementException if this priority queue is empty*/public Key minKey() {if (n == 0) throw new NoSuchElementException("Priority queue underflow");return keys[pq[1]];}/*** Removes a minimum key and returns its associated index.* @return an index associated with a minimum key* @throws NoSuchElementException if this priority queue is empty*/public int delMin() {if (n == 0) throw new NoSuchElementException("Priority queue underflow");int min = pq[1];exch(1, n--);sink(1);assert min == pq[n+1];qp[min] = -1;        // deletekeys[min] = null;    // to help with garbage collectionpq[n+1] = -1;        // not neededreturn min;}/*** Returns the key associated with index {@code i}.** @param  i the index of the key to return* @return the key associated with index {@code i}* @throws IllegalArgumentException unless {@code 0 <= i < maxN}* @throws NoSuchElementException no key is associated with index {@code i}*/public Key keyOf(int i) {if (i < 0 || i >= maxN) throw new IllegalArgumentException();if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");else return keys[i];}/*** Change the key associated with index {@code i} to the specified value.** @param  i the index of the key to change* @param  key change the key associated with index {@code i} to this key* @throws IllegalArgumentException unless {@code 0 <= i < maxN}* @throws NoSuchElementException no key is associated with index {@code i}*/public void changeKey(int i, Key key) {if (i < 0 || i >= maxN) throw new IllegalArgumentException();if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");keys[i] = key;swim(qp[i]);sink(qp[i]);}/*** Change the key associated with index {@code i} to the specified value.** @param  i the index of the key to change* @param  key change the key associated with index {@code i} to this key* @throws IllegalArgumentException unless {@code 0 <= i < maxN}* @deprecated Replaced by {@code changeKey(int, Key)}.*/@Deprecatedpublic void change(int i, Key key) {changeKey(i, key);}/*** Decrease the key associated with index {@code i} to the specified value.** @param  i the index of the key to decrease* @param  key decrease the key associated with index {@code i} to this key* @throws IllegalArgumentException unless {@code 0 <= i < maxN}* @throws IllegalArgumentException if {@code key >= keyOf(i)}* @throws NoSuchElementException no key is associated with index {@code i}*/public void decreaseKey(int i, Key key) {if (i < 0 || i >= maxN) throw new IllegalArgumentException();if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");if (keys[i].compareTo(key) <= 0)throw new IllegalArgumentException("Calling decreaseKey() with given argument would not strictly decrease the key");keys[i] = key;swim(qp[i]);}/*** Increase the key associated with index {@code i} to the specified value.** @param  i the index of the key to increase* @param  key increase the key associated with index {@code i} to this key* @throws IllegalArgumentException unless {@code 0 <= i < maxN}* @throws IllegalArgumentException if {@code key <= keyOf(i)}* @throws NoSuchElementException no key is associated with index {@code i}*/public void increaseKey(int i, Key key) {if (i < 0 || i >= maxN) throw new IllegalArgumentException();if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");if (keys[i].compareTo(key) >= 0)throw new IllegalArgumentException("Calling increaseKey() with given argument would not strictly increase the key");keys[i] = key;sink(qp[i]);}/*** Remove the key associated with index {@code i}.** @param  i the index of the key to remove* @throws IllegalArgumentException unless {@code 0 <= i < maxN}* @throws NoSuchElementException no key is associated with index {@code i}*/public void delete(int i) {if (i < 0 || i >= maxN) throw new IllegalArgumentException();if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");int index = qp[i];exch(index, n--);swim(index);sink(index);keys[i] = null;qp[i] = -1;}/**************************************************************************** General helper functions.***************************************************************************/private boolean greater(int i, int j) {return keys[pq[i]].compareTo(keys[pq[j]]) > 0;}private void exch(int i, int j) {int swap = pq[i];pq[i] = pq[j];pq[j] = swap;qp[pq[i]] = i;qp[pq[j]] = j;}/**************************************************************************** Heap helper functions.***************************************************************************/private void swim(int k) {while (k > 1 && greater(k/2, k)) {exch(k, k/2);k = k/2;}}private void sink(int k) {while (2*k <= n) {int j = 2*k;if (j < n && greater(j, j+1)) j++;if (!greater(k, j)) break;exch(k, j);k = j;}}/**************************************************************************** Iterators.***************************************************************************//*** Returns an iterator that iterates over the keys on the* priority queue in ascending order.* The iterator doesn't implement {@code remove()} since it's optional.** @return an iterator that iterates over the keys in ascending order*/public Iterator<Integer> iterator() { return new HeapIterator(); }private class HeapIterator implements Iterator<Integer> {// create a new pqprivate IndexMinPQ<Key> copy;// add all elements to copy of heap// takes linear time since already in heap order so no keys movepublic HeapIterator() {copy = new IndexMinPQ<Key>(pq.length - 1);for (int i = 1; i <= n; i++)copy.insert(pq[i], keys[pq[i]]);}public boolean hasNext()  { return !copy.isEmpty();                     }public void remove()      { throw new UnsupportedOperationException();  }public Integer next() {if (!hasNext()) throw new NoSuchElementException();return copy.delMin();}}/*** Unit tests the {@code IndexMinPQ} data type.** @param args the command-line arguments*/public static void main(String[] args) {// insert a bunch of stringsString[] strings = { "it", "was", "the", "best", "of", "times", "it", "was", "the", "worst" };IndexMinPQ<String> pq = new IndexMinPQ<String>(strings.length);for (int i = 0; i < strings.length; i++) {pq.insert(i, strings[i]);}// delete and print each keywhile (!pq.isEmpty()) {int i = pq.delMin();StdOut.println(i + " " + strings[i]);}StdOut.println();// reinsert the same stringsfor (int i = 0; i < strings.length; i++) {pq.insert(i, strings[i]);}// print each key using the iteratorfor (int i : pq) {StdOut.println(i + " " + strings[i]);}while (!pq.isEmpty()) {pq.delMin();}}
}/*******************************************************************************  Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.**  This file is part of algs4.jar, which accompanies the textbook**      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,*      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.*      http://algs4.cs.princeton.edu***  algs4.jar is free software: you can redistribute it and/or modify*  it under the terms of the GNU General Public License as published by*  the Free Software Foundation, either version 3 of the License, or*  (at your option) any later version.**  algs4.jar is distributed in the hope that it will be useful,*  but WITHOUT ANY WARRANTY; without even the implied warranty of*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the*  GNU General Public License for more details.**  You should have received a copy of the GNU General Public License*  along with algs4.jar.  If not, see http://www.gnu.org/licenses.******************************************************************************/

转载于:https://www.cnblogs.com/rivsidn/p/10853402.html

chapter_2 索引优先队列相关推荐

  1. 索引超出了数组界限_还在用优先队列?来试试索引优先队列吧(优先队列amp;索引优先队列)...

    一.优先队列 简介 优先队列也被称为堆(heap),队列中允许的操作是 先进先出(FIFO),在队尾插入元素,在队头取出元素.而堆也是一样,在堆底插入元素,在堆顶取出元素.二叉树的衍生,有最小堆最大堆 ...

  2. 数据结构之优先队列:最小索引优先队列,Python代码实现——15

    最小索引优先队列(Min index priority queue) 在之前实现的最大优先队列和最小优先队列,他们可以分别快速访问到队列中最大元索和最小元素,但是他们有一 个缺点,就是没有办法通过索引 ...

  3. 02优先队列和索引优先队列-优先队列-数据结构和算法(Java)

    文章目录 1 概述 1.1 需求 1.2 优先队列特点 1.3 优先队列分类 1.4 应用场景 1.5 相关延伸 2 说明 3 索引优先队列 3.1 实现思路 3.2 API设计 3.2 代码实现及简 ...

  4. 数据结构及算法基础--优先队列(Priority Queue)

    这真的是一个包含很多东西的数据结构.我们会逐步解析,来讲解优先队列: 首先知道什么是优先队列: 普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除(first in, last ou ...

  5. 数据结构与算法——二叉树、堆、优先队列

    *************************************优雅的分割线 ********************************** 分享一波:程序员赚外快-必看的巅峰干货 七 ...

  6. 数据结构之图:加权无向图与寻找最小生成树,Python——27

    加权无向图与prim算法和Kruskal算法寻找最小生成树 加权无向图的介绍 引入 加权无向图是一种为每条边关联一 个权重值或 是成本的图模型.这种图能够自然地表示许多应用.在一副航空图中,边表示航线 ...

  7. Android课程设计:基于离线地图服务器的Android地图应用

    Android开发课程设计:基于离线地图服务器的Android地图应用 此项目的灵感来源于伯克利cs61b的Project3: cs61b的官网地址:Project 3: Bear Maps 我的实验 ...

  8. 如何在 Java 中实现最小生成树算法

    Python微信订餐小程序课程视频 https://edu.csdn.net/course/detail/36074 Python实战量化交易理财系统 https://edu.csdn.net/cou ...

  9. 加权无向图与最小生成树(Prim算法和Kruskal算法)

    目录 0 引入 1 图的最小生成树定义及相关约定 2 最小生成树原理 2.1 性质 2.2 切分定理 3 贪心思想 4 Prim算法 4.1 算法步骤 4.2 API设计 4.3 Java代码演示 5 ...

最新文章

  1. Java基础-Date类常用方法介绍
  2. iOS开发之--解决 swap file “*.swp”already exists!问题
  3. squid 使用 笔记
  4. 第九章、文件与文件系统的压缩与打包 3. 打包命令: tar
  5. [Leetcode] 445. Add Two Numbers II
  6. AngularJs学习笔记--E2E Testing
  7. 依赖反转原则DIP 与使用了Repository模式的asp.net core项目结构
  8. 【渝粤教育】国家开放大学2018年春季 0603-22T建筑工程管理与实务 参考试题
  9. JavaScript高级程序设计
  10. mysql自增id 重置
  11. 史上最详细的UE4安装教程(没有之一,就是史上最详细,不服气你来打我呀)
  12. java:布局方法(边界布局)
  13. Ubuntu 更改环境变量 PATH
  14. SQL Server Always Encrypted加密使用
  15. 配备透明触摸屏 看3D全息投影概念手机
  16. 电路维修知识-可控硅
  17. 网络栈主要结构介绍(socket、sock、sk_buff,etc)
  18. JDK15已发布!网友:我还在JDK8踏步走...
  19. 数据结构(使用尾插法实现单链表)
  20. 如何在Win11 IE浏览器打开网银界面

热门文章

  1. 大数处理之一(加法和乘法)
  2. Google Latitude 能否成为所有移动社会网络的杀手?
  3. mysql 8.0创建远程连接用户
  4. 计算机前端专业术语,学习计算机知识必须懂得50个专业术语
  5. ubuntu 14.04 安装oracle 11g,ubuntu 14.04 安装 oracle 11g
  6. python36块砖36人搬算法_剑指offer python实现 66道算法题
  7. 山东科技大学计算机控制系统期末考试试卷,山东科技大学_计算机操作系统试题A...
  8. oracle数据库备份方法主要有哪几种,Oracle数据库备份方法有哪三种?
  9. jsx后缀的是什么文件_React-从JSX到虚拟DOM
  10. Python进阶2——向量模拟