FAQ Database Discussion Community


Priority queue with insert/delmin operations in constant (amortized) running times

data-structures,queue,priority-queue
Is it possible implement a priority queue with O(1) (amortized) running time of operations insert and delete_min (delete element with the lowest priority) if I know the range of priorities? I thought of some modification of Fibonacci heap, but it does not seem to work due to the O(logn) amortized...

How to restore the PriorityQueue to its initial state before the method call?

java,algorithm,data-structures,priority-queue,priority
I am doing a practice problem Practice IT Kth Smallest This problem is basically you're passed in a PriorityQueue and a certain k, and you are to return the kth smallest value in that PriorityQueue. You are also to restore the PriorityQueue to its initial state and can use one...

Single process blocking queue

java,queue,message-queue,priority-queue
I am writing an application that communicates with hardware. While the application can receive and process multiple requests simultaneously in parallel, the hardware cannot! The hardware requires these parallel requests to basically be organised into a linear request chain each one executed one after the other. I also have a...

Priority Queue using a Max-Heap Data Structure

python,insert,heap,priority-queue,max-heap
I am implementing a priority queue using a max-heap data structure in Python. I'm using several names that have numbers associated with them as their priority (9 being the highest and 1 being the lowest). The issue I am facing is that when I dequeue an item from the priority...

How to apply ordering to a Scala Priority Queue?

algorithm,scala,priority-queue
I've defined a priority queue like so import scala.collection.mutable.PriorityQueue ... val queue = new PriorityQueue[(Int,Int)]() I want to use this ordering: If we are comparing two items A and B in the queue, A is bigger than B if the first element of its (Int,Int) tuple is larger than B's....

Inherit from both 'heapq' and 'deque' in python?

python,multiple-inheritance,priority-queue,deque
I'am trying to implement a 'heapq' or a 'deque' dynamically (according to user's input) class MyClass(): def __init__(self, choose = True ): self.Q = [] self.add = self.genAdd(choose) self.get = self.genGet(choose) def genAdd(self, ch): if(ch == True): def f(Q, elem): return Q.append else: def f(Q): return heappush return f and...

Issues with Declaring a C++ Priority Queue using a custom Comparator

c++,compare,priority-queue
I have been trying to implement a Priority queue consisting of a custom data type and a custom comparator but when I try to compile I get this error. I have tried multiple declarations but they all yield this error. priority_queue<myData, vector<myData>, myComp> myPQ; priority_queue<myData, vector<myData>, myComp> myPQ(compVariable); I also...

Getting error “reference to non-static member function must be called” when calling push on priority queue

c++,priority-queue
This might be an obvious issue but being a novice to C++ I'm not quite sure why this error occurs. I have the following setup, I use a priority_queue that I typedef like this: typedef priority_queue<int,vector<int>,PayloadIndexComparison> PayloadIndexPQ; Then, I have a class that is using this priority queue: struct MappingTechnique...

What's wrong with my code, it seems correctly, but it's not

java,priority-queue
The problem is I have to read a text file. I have 24 candidates, and each number from 1-24 is correspond to candidates 1, 2, 3, 4, 5 ...., 24. (I.e: if the digit 1 is seen 10 times in the text file then it means the first candidate has...

Priority queue with O(1) Get-Min, Delete-Min and Merge operations

algorithm,heap,priority-queue,splay-tree
I'm wondering if there is a way to construct a priority queue structure that supports constant-time get-min, delete-min, and merge operations. I don't care about the time complexity of insertions and it doesn't have to support the decrease-key operation. My use case in (bad) pseudo-code: func periodical(current_state) { // always_executed_jobs...

Add Key and Value into an Priority Queue and Sort by Key in Java

java,priority-queue
I am trying to take in a List of strings and add them into a Priority Queue with Key and Value. The Key being the word and the value being the string value of the word. Then I need to sort the queue with the highest string value first. The...

How to implement a priority queue using the field of a class in java

java,priority-queue
I have a java class called MeterReading with two fields String MeterName and int MeterLevel. Now, if the MeterLevel is between 0 and 3, that is Low, when between 3 and 6, Medium and from 6 above is High. How would I pass in that class MeterReading to a priority...

What happens when you erase an element from boost::fibonacci_heap?

c++,boost,data-structures,priority-queue,fibonacci-heap
Does an erase operation also update the heap after the element is removed? I went through member functions explanation in boost documentation for fibonacci_heap where it is mentioned what happens after increase/decrease operations, but when it comes to erase the only thing that is stated is that it erases the...

C++ STL priority queue getting bad_alloc

c++11,std,priority-queue
I'm trying to use a STL priority queue, defined as: template <typename T> using min_queue = std::priority_queue<T, std::vector<T>, std::greater<T>>; When running the following code: Label kNN(int k, const Matrix &trainingSet, const std::vector<Label> &trainingLabels, Matrix &evSet, int i1, const DistanceF &f) { Timer timer("kNN Timer"); min_queue<std::pair<double, Label>> distances; for (int i...

sort priority queue of objects by specified value

java,priority-queue
i want to add objects to priority queue by using specified value like this PriorityQueue<Edge> queue=new PriorityQueue<Edge>(); this is class Edge which i want to sort in priority queue by its weight public class Edge { private int start,end; private double weight; public Edge(int s, int e,Double w){ start=s; end=e;...

Prim Algorithm Priority Queue

java,priority-queue,prims-algorithm
I am trying to implement Prim's algorithm in Java with a priority queue. I can't find my mistake. :/ I just recognize that the queue doesn't order the nodes correctly. example for a graph: 0 4 7 5 4 0 2 3 7 2 0 1 5 3 1 0...

How to set fixed size to PriorityQueue in Java? [duplicate]

java,priority-queue
This question already has an answer here: Is there a PriorityQueue implementation with fixed capacity and custom comparator? 7 answers I have a simple question. I am implementing PriorityQueue in my project. My question is can i set a fixed size for PriorityQueue is Java ?...

Queue with multi-field sorting on priority and time

java,queue,priority-queue
Intent Implement a task queue with sorting based on 1) priority and 2) time, specifically, time at which task was created or time-stamped (not inserted in the queue), giving preference to tasks with older time stamps. Tried This is what I got so far; much simpler than I thought having...

How to declare an stl::priority_queue with initial data and custom comparator?

c++,constructor,priority-queue
I need a priority_queue for my structs. I want to construct one using both initial data from an array and a custom comparator: class mycomparison { public: mycomparison(const bool& maxOnTop=false, const int& compField = 0); ... }; mergeRecord initialRecords[N]; // my array mycomparison(false, field); // my custom comparator std::priority_queue<mergeRecord, std::vector<mergeRecord>,...

Get top 10 and last 10 from a million records

java,binary-tree,binary-search-tree,priority-queue
I have a report which shows 2-4 million records. I get the records from oracle to java and push it to an excel report. All this is already done! Now, I also need to add a new tab with top 10 and last 10 records. What would be the best...

How does this priority queue work?

java,priority-queue
import java.util.PriorityQueue; public class QueueInts{ public static void main(String[] args) { PriorityQueue<Integer> q = new PriorityQueue<>(); String expression = "(2+4)-8 * (3-1)"; String symbols = "()+-*/% "; for (int i = 0; i < expression.length(); i++) { if (!symbols.contains("" + expression.charAt(i))) q.add((int)expression.charAt(i)-48); System.out.println(q); } System.out.println(q); while (q.size() > 0) System.out.println("...

implementing PriorityQueue on ThreadPoolExecutor

java,priority-queue,future,threadpoolexecutor
Been struggling with this for over 2 days now. implemented the answer I saw on here Specify task order execution in Java public class PriorityExecutor extends ThreadPoolExecutor { public PriorityExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } //Utitlity method to create...

Priority Queue using just array and binary search

data-structures,queue,priority-queue,binary-search
So I have come across priority queue data structure, the implementation is usually with heaps or binary tree. Why can't a priority queue just use a simple array and use binary search for insertion, it would still be O(logn) with retrieval time of O(1). while true { // We will...

Python: Using my heap in a priority queue implementation

python,heap,priority-queue,binary-heap
I am having real trouble using my custom-made heap class functions to be used in my Priority Queue class. I am having trouble on what functions from my heap class to use for my "enqueue", "dequeue", "front" and "size" functions for my PriorityQueue. I know for "enqueue" I need to...

Retrieve item from the middle of a PriorityQueue in Java

java,priority-queue
Given the following code: import java.util.*; class SimpleTest { public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.add(1); pq.add(2); pq.add(3); pq.add(4); pq.add(5); pq.add(6); pq.add(7); int index = 0; int middleNumber = 0; Iterator it = pq.iterator(); //Is number odd if(pq.size() % 2 != 0) { System.out.println(pq.size()); //keep...

Java: Uniform Cost Search with Node class

java,graph-algorithm,priority-queue,comparable
The below code is supposed to detect an image, create a 2d array containing the pixel values from that image, and determine the path of lowest cost (I used Uniform Cost Search) from a Point A inside the image to a Point B inside the image. When I run my...

priority_queue with custom comparator as a class method

c++,priority-queue
i have code like this priority_queue<int, std::vector<int>, decltype(&VD::CompareByDistance)> pqDistances(&VD::CompareByDistance); where class VD { ... bool CompareByDistance(int indexLeft, int indexRight) const; }; But i get error error C2064: term does not evaluate to a function taking 2 arguments How can i pass class member as a compator, the thing is that...

Priority Queues: Enqueue returns 'None' instead of int value

python,priority-queue
I am having problems with my PriorityQueue class in python. I think I set it up all the way and now I'm trying to test it, but I keep getting the word "None" when I print out the value I am enqueuing which isn't right. This is my test code,...

How to implement a priority queue using SQS(Amazon simple queue service)

python,boto,priority-queue,amazon-sqs
I have a situtaion when a msg fails and I would like to replay that msg with an highest priority using python boto package so he will be taken first. If I'm not wrong SQS queue does not support priority queue, so I would like to implement something simple. Important...

Does PriorityQueue maintain natural order? [duplicate]

java,collections,queue,priority-queue,comparable
This question already has an answer here: Print content of priority queue[java] 1 answer The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. However, in the following example, when I...

How to sort a multidimensional vector of floats?

c++,sorting,vector,priority-queue
So, I have a set of points in 3D, and I would like to store them in a 3 dimensional vector. Then I need sort that vector, giving priority first to the X dimention, then Y, then Z. So, for example, if I have this set of points: P1 =...

How to use different comparators for a priority queue depending on conditions

c++,priority-queue,comparator
I'm working on an assignment, where I have a priority queue and I want it to work like this: if(field == '0') priority_queue<record_t*,vector<record_t*>, CompareRecordID > pq; else if(field == '1') priority_queue<record_t*,vector<record_t*>, CompareRecordNum > pq; else if(field == '2') priority_queue<record_t*,vector<record_t*>, CompareRecordStr > pq; else if(field == '3') priority_queue<record_t*,vector<record_t*>, CompareRecordNumStr > pq;...

Priority Queue - Consecutive Groups of Integers

java,priority-queue
I am working on this question: Divide a list of numbers into group of consecutive numbers but their original order should be preserved? e.g. input: 8,2,4,7,1,0,3,6 output: 2,4,1,0,3 and 8,7,6 I implemented a solution, simply put: Store the original array into a map with the key being the input elements...

C++ int PriorityQueue using stack

c++,arrays,stack,priority-queue
Im just starting to learn C++ programming and for exercise i found this task. I have to write a PriorityQueue using dynamic, array based, integer stack. This is what i have got so far. #include <iostream> using namespace std; class PrioQueue { private: int *bottom_; int *top_; int size_; public:...

Python Heap Priority Queue sift_up()

python,queue,heap,priority-queue
I am still rather new to Python, but am having a problem with a heap priority queue. Here are my init(), str(), add(), and my sift_up() method: def __init__(self): self.queue = [] def __str__(self): return str(self.queue) def add(self, item): self.queue.append(item) self.sift_up(len(self.queue) - 1) def sift_up(self, item): parent = (item -...

Implementing Min priority Queue(C++ STL) using user-defined objects

c++11,stl,priority-queue
I am implementing Prims Algorithm. I have a vector of Edges along with their weights. The problem is, after inserting, the queue does not remain in increasing order according to weight of edges. The relevant code is given below:- struct weightcomp // To be used solely for priority Queue... {...