堆优先级队列如何记住数组中的索引?

时间:2012-11-18 23:25:21

标签: java

实现此队列的最简单方法是什么,以便我可以在每个相应的MyEntry对象中保存每个索引(条目在ArrayList堆中的位置),而不使用键或值来执行此操作?

public class HeapPriorityQueue<K,V> {

protected ArrayList<Entry<K,V>> heap;
protected Comparator<K> comp;

protected static class MyEntry<K,V> implements Entry<K,V> {
    protected K key;
    protected V value;
    public MyEntry(K k, V v) {key = k; value = v;}
    public K getKey() {return key;}
    public V getValue() {return value;}
    public String toString() {return "(" + key + "," + value + ")";}
}

2 个答案:

答案 0 :(得分:1)

你在找类似的东西吗?

public class HeapPriorityQueue<K,V> {

  protected ArrayList<Entry<K,V>> heap;
  protected TreeMap<Entry<K,V>, Integer> index;
  protected Comparator<K> comp;

  public synchronized void addEntry(K key, V value) {
    // requires O(log(n))
    Entry<K, V> entry = new Entry<K, V>(key, value);
    int insertionPos = heap.size();
    heap.add(entry);
    index.put(entry, insertionPos);
  }

  public int indexOfEntry(Entry<K,V> entry ) {
    // requires O(log(n))
    return index.get(entry);
  }

  protected static class MyEntry<K,V> implements Entry<K,V> {
    protected K key;
    protected V value;
    public MyEntry(K k, V v) {key = k; value = v;}
    public K getKey() {return key;}
    public V getValue() {return value;}
    public String toString() {return "(" + key + "," + value + ")";}
  }
}

答案 1 :(得分:0)

可以简单地使用一个Map<int,int>来存储数组的索引和值来解决。 并且 One Priority Queue<Pair<int,int>> pq 再次存储对应于优先级队列中的优先级的索引和值。

C++ 代码:

#include<bits/stdc++.h>
using namespace std;

// Author : @devangs

int main(){
    int i,j;
    vector<int> v ={1,2,3,4,5,2,5,4};
    int n=v.size();

    unordered_map<int,int> mp;
    for (i=0; i<n; i++)
    {
        mp[i]=v[i];
    }
    
    cout<<"Map With Index and Values Are: "<<endl;
    for (auto it:mp)
        cout<<it.first<<" "<<it.second<<endl;
    
    cout<<endl;
        
    cout<<"Map With Index and PQ Value Are: " <<endl;           
    priority_queue<pair<int,int>> pq; 
    for(auto it = mp.begin(); it != mp.end(); it++)
    {
        pq.push(make_pair(it->second, it->first));
    }
        
    while (!pq.empty()){
        cout<<pq.top().second<<" "<<pq.top().first<<endl;  
        pq.pop();
    }
    return 0;
}