// CS 1501 Priority Queue that allows for change of priority class PQ { private: int * a; // vertex id in heap order int * place; // location of vertex in heap int * val; // edge weight of vertex int N; public: PQ(int max); ~PQ(); void insert(int v, int key); void change(int v, int key); int remove(); void upheap(int k); void downheap(int k); }; PQ::PQ(int max) { a = new int[max]; place = new int[max]; val = new int[max]; N = 0; } PQ::~PQ() { delete [] a; delete [] place; delete [] val; } void PQ::upheap(int v) //v is a vertex { int temp; temp = val[v]; a[0] = 0; val[0]= 99999999L; int k = place[v]; while ( val[ a[k/2] ] <= temp) { cout << "Moving " << v << " with value " << temp << endl << " up past its parent, " << a[k/2] << " with value " << val[a[k/2]] << endl; place[ a[k/2] ] = k; a[k] = a[k/2]; k = k/2; } a[k] = v; place[v] = k; cout << "Index " << v << " is in location " << k << endl; } void PQ::insert(int v, int key) //v is a vertex and key is the key { val[v]=-key; // val is made negative to make it a min healp // it is probably more appropriate to do this // outside of the heap a[++N] = v; place[v]=N; upheap(v); } void PQ::change(int v, int key) { int aloc = place[v]; int vloc = a[aloc]; val[vloc] = -key; if (val[a[aloc/2]] < (-key)) // after val change, move up or down upheap(v); // based on new value else downheap(v); } void PQ::downheap(int v) // v is a vertex { int k = place[v]; int j; int store = a[k]; while (k <= N/2) { j = k+k; // find left child of vertex if (j= val[ a[j] ]) break; // if heap order is restored, break out of loop cout << "Moving " << v << " with value " << val[store] << endl << " down past " << a[j] << " with value " << val[a[j]] << endl; place[a[j]]=k; // move child up a[k] = a[j]; k = j; // continue from old child location } a[k] = v; place[v]=k; cout << "Index " << v << " is in location " << k << endl; } int PQ::remove() { int v = a[1]; a[1] = a[N--]; place[a[1]]=1; downheap(a[1]); return v; }