+ """a minheap implementation of a priority queue"""
+ def __init__(self,cap=100):
+ """creates a priority queue with keys in the set {0..cap-1}"""
+ # list of pairs (key,priority) in a minheap structure
+ self.__heap = [ (k,self.INF) for k in range(cap) ]
+ self.__key = [ k for k in range(cap) ]
+ """return the string representation of the priority queue"""
+ return str(self.__heap)
+ """return the number of keys in the data structure"""
+ return len(self.__heap)
+ """is the given index the root of the minheap?"""
+ """return the parent index of i; it might not exist"""
+ """return the left child index of i; it might not exist"""
+ """return the right child index of i; it might not exist"""
+ def __heapify_up(self,i):
+ """heapify up index i in the heap"""
+ if self.__heap[i][1] < self.__heap[p][1]:
+ ki,kp = self.__heap[i][0],self.__heap[p][0]
+ self.__heap[i],self.__heap[p] = self.__heap[p],self.__heap[i]
+ self.__key[ki],self.__key[kp] = p,i
+ def __heapify_down(self,i):
+ """heapify down index i in the heap"""
+ l,r,b = self.__left(i),self.__right(i),i
+ if l<len(self) and self.__heap[b][1]>self.__heap[l][1]:
+ if r<len(self) and self.__heap[b][1]>self.__heap[r][1]:
+ ki,kb = self.__heap[i][0],self.__heap[b][0]
+ self.__heap[i],self.__heap[b] = self.__heap[b],self.__heap[i]
+ self.__key[ki],self.__key[kb] = b,i
+ """is the given k a key in the queue?"""
+ def get_priority(self,k):
+ """return the priority of the given key k"""
+ return self.__heap[self.__key[k]][1]
+ """return the pair (key,priority) with the highest priority"""
+ """make the priority of the element with the highest priority the
+ self.__heap[0] = (self.__heap[0][0],self.INF)
+ def decrease_key(self,k,p):
+ """decrease the priority of the given key k to p; it should be the
+ case that k is a valid key and p <= get_priority(k)
+ assert self.get_priority(k)>=p
+ self.__heap[self.__key[k]] = (k,p)
+ self.__heapify_up(self.__key[k])
+ """sets the priority of key k to be p, assuming that it has the
+ assert self.get_priority(k) == self.INF
+ """is the priority queue empty in the sense that no key has a
+ return self.__heap[0][1] == self.INF
+ """is the priority queue full in the sense that all keys have a
+ return self.__heap[-1][1] != self.INF
+ """add the next key to the priority queue with the worst priority
+ self.__heap.append((len(self.__heap),self.INF))
+ self.__key.append(len(self.__key))