`
flyingdutchman
  • 浏览: 353346 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

索引优先队列:最大索引优先队列

阅读更多
        相对于最小优先队列,最大优先队列的代码如下:
 package org.test;

/*************************************************************************
 *  Compilation:  javac IndexMaxPQ.java
 *  Execution:    java IndexMaxPQ
 *
 *  Maximum-oriented indexed PQ implementation using a binary heap.
 *
 *********************************************************************/

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 *  The <tt>IndexMaxPQ</tt> class represents an indexed priority queue of generic keys.
 *  It supports the usual <em>insert</em> and <em>delete-the-maximum</em>
 *  operations, along with <em>delete</em> and <em>change-the-key</em> 
 *  methods. In order to let the client refer to items on the priority queue,
 *  an integer between 0 and NMAX-1 is associated with each key&mdash;the client
 *  uses this integer to specify which key to delete or change.
 *  It also supports methods for peeking at the maximum key,
 *  testing if the priority queue is empty, and iterating through
 *  the keys.
 *  <p>
 *  The <em>insert</em>, <em>delete-the-maximum</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>max-index</em>, <em>max-key</em>, and <em>key-of</em>
 *  operations take constant time.
 *  Construction takes time proportional to the specified capacity.
 *  <p>
 *  This implementation uses a binary heap along with an array to associate
 *  keys with integers in the given range.
 *  <p>
 *  For additional documentation, see <a href="http://algs4.cs.princeton.edu/24pq">Section 2.4</a> of
 *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 */
public class IndexMaxPQ<Key extends Comparable<Key>> implements Iterable<Integer> {
    private 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

   /**
     * Create an empty indexed priority queue with indices between 0 and NMAX-1.
     * @throws java.lang.IllegalArgumentException if NMAX < 0
     */
    public IndexMaxPQ(int NMAX) {
        keys = (Key[]) new Comparable[NMAX + 1];    // make this of length NMAX??
        pq   = new int[NMAX + 1];
        qp   = new int[NMAX + 1];                   // make this of length NMAX??
        for (int i = 0; i <= NMAX; i++) qp[i] = -1;
    }

   /**
     * Is the priority queue empty?
     */
    public boolean isEmpty() { return N == 0; }

   /**
     * Is i an index on the priority queue?
     * @throws java.lang.IndexOutOfBoundsException unless (0 &le; i < NMAX)
     */
    public boolean contains(int i) {
        return qp[i] != -1;
    }


   /**
     * Return the number of keys on the priority queue.
     */
    public int size() {
        return N;
    }

   /**
     * Associate key with index i.
     * @throws java.lang.IndexOutOfBoundsException unless 0 &le; i < NMAX
     * @throws java.util.IllegalArgumentException if there already is an item associated with index i.
     */
    public void insert(int i, Key key) {
        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);
    }

   /**
     * Return the index associated with a maximal key.
     * @throws java.util.NoSuchElementException if priority queue is empty.
     */
    public int maxIndex() { 
        if (N == 0) throw new NoSuchElementException("Priority queue underflow");
        return pq[1];
    }

   /**
     * Return a minimal key.
     * @throws java.util.NoSuchElementException if priority queue is empty.
     */
    public Key maxKey() { 
        if (N == 0) throw new NoSuchElementException("Priority queue underflow");
        return keys[pq[1]];
    }

   /**
     * Delete a maximal key and return its associated index.
     * @throws java.util.NoSuchElementException if priority queue is empty.
     */
    public int delMax() { 
        if (N == 0) throw new NoSuchElementException("Priority queue underflow");
        int min = pq[1];        
        exch(1, N--); 
        sink(1);
        qp[min] = -1;            // delete
        keys[pq[N+1]] = null;    // to help with garbage collection
        pq[N+1] = -1;            // not needed
        return min; 
    }

   /**
     * Return the key associated with index i.
     * @throws java.lang.IndexOutOfBoundsException unless 0 &le; i < NMAX
     * @throws java.util.NoSuchElementException no key is associated with index i
     */
    public Key keyOf(int i) {
        if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
        else return keys[i];
    }


   /**
     * Change the key associated with index i to the specified value.
     * @throws java.lang.IndexOutOfBoundsException unless 0 &le; i < NMAX
     * @throws java.util.NoSuchElementException no key is associated with index i
     * @deprecated Replaced by changeKey()
     */
    @Deprecated public void change(int i, Key key) {
        changeKey(i, key);
    }

   /**
     * Change the key associated with index i to the specified value.
     * @throws java.lang.IndexOutOfBoundsException unless 0 &le; i < NMAX
     * @throws java.util.NoSuchElementException no key is associated with index i
     */
    public void changeKey(int i, Key key) {
        if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
        keys[i] = key;
        swim(qp[i]);
        sink(qp[i]);
    }

   /**
     * Increase the key associated with index i to the specified value.
     * @throws java.lang.IndexOutOfBoundsException unless 0 &le; i < NMAX
     * @throws java.lang.IllegalArgumentException if key &le; key associated with index i
     * @throws java.util.NoSuchElementException no key is associated with index i
     */
    public void increaseKey(int i, Key key) {
        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;
        swim(qp[i]);
    }


   /**
     * Decrease the key associated with index i to the specified value.
     * @throws java.lang.IndexOutOfBoundsException unless 0 &le; i < NMAX
     * @throws java.lang.IllegalArgumentException if key &ge; key associated with index i
     * @throws java.util.NoSuchElementException no key is associated with index i
     */
    public void decreaseKey(int i, Key key) {
        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;
        sink(qp[i]);
    }

   /**
     * Delete the key associated with index i.
     * @throws java.lang.IndexOutOfBoundsException unless 0 &le; i < NMAX
     * @throws java.util.NoSuchElementException no key is associated with index i
     */
    public void delete(int i) {
        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 less(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 && less(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 && less(j, j+1)) j++;
            if (!less(k, j)) break;
            exch(k, j);
            k = j;
        }
    }


   /***********************************************************************
    * Iterators
    **********************************************************************/

   /**
     * Return an iterator that iterates over all of the elements on the
     * priority queue in descending order.
     * <p>
     * The iterator doesn't implement <tt>remove()</tt> since it's optional.
     */
    public Iterator<Integer> iterator() { return new HeapIterator(); }

    private class HeapIterator implements Iterator<Integer> {
        // create a new pq
        private IndexMaxPQ<Key> copy;

        // add all elements to copy of heap
        // takes linear time since already in heap order so no keys move
        public HeapIterator() {
            copy = new IndexMaxPQ<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.delMax();
        }
    }
 }
        
分享到:
评论

相关推荐

    基于java开发的游戏聊天系统

    - 消息队列:lim-mq,kafka实现,负责削峰填谷 - 消息处理:lim-mh,无状态,负责异步消费消息队列中的消息,将消息写入消息存储库和消息同步库 - 消息存储库和索引:influxdb实现,负责持久化会话消息 - 消息同步库...

    StructuresandAlgorithms-Code:重温数据结构与算法,代码实践

    优先队列:堆结构的实现 经典题 括号匹配 表达式求值(中缀表达式转后缀表达式) 队列-层次遍历 栈实现队列、队列实现栈 双端队列-返回滑动窗口的最大值 小顶堆-返回数据流的第k大元素 leetcode建议练习题号: 业界...

    queue-testing

    队列实现拼接队列存储: Array 指数:自然出队: splice()方法DeletingQueue() 商店: Object 索引:手动出队: delete o[index]未定义队列商店: Object 索引:手动出队: o[index] = undefinedMapQueue 商店: ...

    网络爬虫调研报告.doc

    Spider的队列 (1)等待队列 :新发现的 URL被加入到这个队列 ,等待被 Spider程序处理 ; (2)处理队列 :要被处理的 URL被传送到这个队列。为了避免同一个 URL被多次处理 ,当一个 URL被处理过后 ,它将被转移到完成...

    网络爬虫调研报告(1).doc

    Spider的队列 (1)等待队列 :新发现的 URL被加入到这个队列 ,等待被 Spider程序处理 ; (2)处理队列 :要被处理的 URL被传送到这个队列。为了避免同一个 URL被多次处理 ,当一个 URL被处理过后 ,它将被转移到完成...

    网络爬虫调研报告(2).doc

    Spider的队列 (1)等待队列 :新发现的 URL被加入到这个队列 ,等待被 Spider程序处理 ; (2)处理队列 :要被处理的 URL被传送到这个队列。为了避免同一个 URL被多次处理 ,当一个 URL被处理过后 ,它将被转移到...

    索引队列-C#中的自定义队列

    通过允许有效索引访问的替代方法填补了Microsoft Queue产品中的空白

    消息中间件消息队列常见面试题

    Kafka的索引设计有什么亮点? Kafka日志段如何读写解析? Kafka控制器事件处理全流程解析 Kafka请求处理全流程解析 Kafka为什么要抛弃Zookeeper? 进阶必看的 RocketMQ,这次一网打尽 Kafka和RocketMQ底层存储揭秘,...

    扩展矩阵leetcode-algorithms:算法

    堆/优先队列/堆排序: , , 后缀自动机: , , , , , , 最低共同祖先: , , , 计数反转: , , , Euclid 的扩展算法: 后缀树: , , , , , , 动态规划:来自 clrs(essential), , , , , , , , 的章节 基本数据结构: , ,...

    2018阿里巴巴中间件挑战赛-消息队列存储引擎题目设计基于Java.zip

    - 索引做得不是很好,读索引时,随机读写太多,当队列增多时,读索引的时间会大幅增多 - 还有好多好多的优化点和可以进步的地方~ **P.S.** start.sh是一个模拟测评程序的脚本,可以在Linux系统+SSD磁盘下测试使用

    java中负数的源码反码补码-interviews:CS面试学习表

    队列:先进先出(FIFO) 添加一个元素并弹出最旧的元素是O(1)操作 双端队列:栈+队列组合 push添加元素 & pop提取元素 树木 树是无向的、连通的、无环图 有v个顶点和v-1边 任意两个顶点通过唯一路径连接 叶子是度数...

    JavaScript算法源代码(例如:二叉搜索树、笛卡尔乘积、线性搜索、存储桶排序、DFS、 Kruskal算法、欧几里,等等)

    链表、双链表、队列、Stack、哈希表、堆 - 最大和最小堆、优先队列、Trie、树、二叉搜索树、AVL树、红黑树、区段树 - 包含最小/最大/总和范围查询示例、Fenwick Tree(二叉索引树)、图形(有向和无向)、 Disjoint ...

    Redis安装文档及实验.docx

    1、安装文档 2、 实验:(1) 启动redis(2) 停止redis(3)测试连接(发送命令的两种方法) 字符串类型: (4)设置一个键,获得该键值,并判断一个键是否存在 (5)删除键 ...(33)优先级队列:

    论文研究 - 先前治疗过的慢性淋巴细胞白血病的Medicare患者的总体生存和医疗保健费用

    根据观察到的两种最流行的基于苯达莫司汀的治疗方案(索引治疗)将入选患者分类为队列:1)苯达莫司汀+利妥昔单抗(BR队列)和2)苯达莫司汀单药治疗(B-单队列)。 对于每个队列,均报告了每位患者每月(PPPM)在...

    PriorityQueue-MEX-Matlab:这是 C++ STL 优先级队列的 Mexified MATLAB 包装器-matlab开发

    这是 C++ STL 优先级队列的 Mexified MATLAB 包装器这个优先队列实现很简单。 然而,它可以用来保存任意对象的“排序”列表。 我们可以只推送它的索引,而不是推送整个对象。 这是通过首先像往常一样将对象存储在 ...

    基于lucene的搜索引擎总结

    最大匹配法(机械分词):按照一定的策略将待分析的汉字串与一个“充分大的”机器词典中的词条进行配,若在词典中找到某个字符串,则匹配成功。 二元分词 一元分词 自动分类 向量距离分类算法 根据算术平均,为每类...

    advent_of_code

    advent_of_code 代码解决方案(和数据)的出现。... 双端队列: 字典用法(除了基本的查找功能之外): 字母循环/解码: : 基本链接列表: : 带有缺失/推断值的链表: : 从Iterable过滤: 格式遮罩: 生活变体

    com-ihere-lucene:简单学习Lucene,编写测试Demo,使用IK中文分词器

    IHereLucene1.0版本说明实现Lucene对索引...使用队列对索引创建优化,当前创建索引规则为:每次批量取出连续为新增的,设定一次取出最大为100,不够直接执行。否则先执行再继续读队列,如果碰到不是新增的,直接执行。

    数据结构(C语言版)\Java数据结构和算

    9.1 单端优先队列和双端优先队列 9.2 左倾树 9.3 二项式堆 9.4 Fibonacci堆 9.5 配偶堆 9.6 对称最小-最大堆 9.7 区间堆 9.8 参考文献和选读材料 第10章 高效二叉查找树 10.1 最优二叉查找树 10.2 AVL树 ...

    KaraokeList2:应用程序为卡拉OK(CD + G)文件,搜索,在Web和本地队列中编入索引,并播放聚会队列

    卡拉OKList2 应用程序为卡拉OK(CD + G)文件,搜索,在Web和本地队列中编入索引,并播放聚会队列 在此处下载编译的版本: :

Global site tag (gtag.js) - Google Analytics