int main() { PriorityQueue<int> *testQueue = new PriorityQueue<int>(3); // push a few random int's testQueue->enqueue(4); testQueue->enqueue(7); testQueue->enqueue(1); // queue shouldn't be empty; check this if(testQueue->isEmpty()) { cout << "The queue is empty!" << endl; } // pop items (more items than were pushed) cout << testQueue->dequeue() << endl; cout << testQueue->dequeue() << endl; cout << testQueue->dequeue() << endl; cout << testQueue->dequeue() << endl; // should be empty now; check this if(testQueue->isEmpty()) { cout << "The queue is empty!" << endl; } return 0; }
int main(){ PriorityQueue* pr = new PriorityQueue(); pr->insertElem(4,13); pr->insertElem(3,5); pr->insertElem(2,9); pr->insertElem(1,2); for(int i=0 ; i<pr->size() ;i++){ printf("%d\n", pr->minQueue[i]->priority ); } if( pr->contains(4) ) { pr->changePriority(4,1); } while(!pr->isEmpty()){ Element * elem = pr->minPriority(); printf("(%d,%d)\n",elem->vertex,elem->priority); } }
vector<Node *> dijkstrasAlgorithm(BasicGraph& graph, Vertex* start, Vertex* end) { graph.resetData(); vector<Vertex*> path; for (Vertex* node : graph.getNodeSet()){ //initiate all nodes with an inf. cost node->cost = INFINITY; } PriorityQueue<Vertex*> pQueue; start->cost = 0; pQueue.enqueue(start, start->cost); //start of search while (!pQueue.isEmpty()){ Vertex* v = pQueue.dequeue(); v->visited = true; v->setColor(GREEN); if (v == end){ return pathBuilderToStart(start, v); //same as the one bfs uses }else{ for(Arc* edge : graph.getEdgeSet(v)){ //Go through each edge from the Vertex v, counting the cost for each newly visited vertex Vertex* next = edge->finish; if (!next->visited){ double cost = v->cost + edge->cost; if (cost < next->cost){ //found a lesser cost, what dijkstra is all about next->setColor(YELLOW); next->cost = cost; next->previous = v; pQueue.enqueue(next, cost); //pQueue.changePriority(next, cost); Only do this if next already is in the queue, but this should not ever occur? } } } } } return path; }
/* * Method: aStar * Parameters: BasicGraph graph by reference * Vertex pointer variable for path start * Vertex pointer variable for path end * - - - - - - - - - - - - - - - - - - - - - - - - - - * Returns a Vector of Vertex pointer variables for which * each index corresponds to a step in the path between * the path's start and end points, if any exists. * This function uses A*'s algorithm, which evaluates * the estimated total cost of all neighbors' paths to the end * from the starting vertex before continuing. It differs from Dijkstra's * in its prioritization of location based on their estimated total cost * or distance from the starting point, as opposed to the current cost * up to that point. Because A* also orients subsequent vertices * to their earlier parent, this function uses a helper function to * rewind the shortest route from end to start, if applicable, * returning an empty vector if not. */ Vector<Vertex*> aStar(BasicGraph& graph, Vertex* start, Vertex* end) { graph.resetData(); Vector<Vertex*> path; PriorityQueue<Vertex*> pqueue; pqueue.enqueue(start, heuristicFunction(start, end)); while(!pqueue.isEmpty()) { Vertex* current = pqueue.dequeue(); visitVertex(current); if(BasicGraph::compare(current, end) == 0) break; for(Edge* edge : current->edges) { double cost = current->cost + edge->cost; if(!edge->finish->visited && edge->finish->getColor() != YELLOW) { enqueueVertex(edge->finish, current, cost); pqueue.enqueue(edge->finish, cost + heuristicFunction(edge->finish, end)); } if(edge->finish->getColor() == YELLOW && cost < edge->finish->cost) { enqueueVertex(edge->finish, current, cost); pqueue.changePriority(edge->finish, cost + heuristicFunction(edge->finish, end)); } } } determinePath(start, end, path); return path; }
Node* buildTree(Vector <int> & weightOfChars, char & delimiter){ PriorityQueue<Node*> weightsOfNodes; // declare a PriorityQueue for simple sorting weights of nodes bool flag = 1; // set flag to prevent overwriting a delimiter for(int i = 0; i < weightOfChars.size(); ++i){ if(weightOfChars[i] > 0){ Node* node = new Node((i - 128), weightOfChars[i]); weightsOfNodes.enqueue(node, weightOfChars[i]); } else if((flag && (i < 128)) || (flag && (i > 159))){ // looking for a character that is not a control code and has a number of occurences which is equal zero delimiter = i; flag = 0; } } // if file is empty the pointer of root of the tree is a NULL if(weightsOfNodes.isEmpty()){ return NULL; } while (weightsOfNodes.size() > 1) { Node* lNode = weightsOfNodes.dequeue(); Node* rNode = weightsOfNodes.dequeue(); Node* newNode = new Node(lNode, rNode); weightsOfNodes.enqueue(newNode, newNode->weight); } Node* root = weightsOfNodes.dequeue(); return root; }
vector<T> print_queue(PriorityQueue<T> &q){ vector<T> ret; while(!q.isEmpty()) { ret.push_back(q.getTop()); q.pop(); } return ret; }
float* Dijkstra::dijkstra(Graph *&graph, int s) { int n = graph->getVerticesNum(); if ((s < 0)||(s >= n)) return 0; int m = graph->getRealSize(); Data** dist = new Data*[n]; int* up = new int[n]; for (int i = 0; i < n; i++){ up[i] = 0; dist[i] = new DataFloat(i, FLT_MAX); } dist[s]->priority = 0; PriorityQueue *queue = new PriorityQueue(dist, n, 4); Edge** edges = graph->getEdgeSet(); int edgeCount = m; while ((edgeCount != 0) && (!queue->isEmpty())) { Data* tmp = queue->pop(); int v = ((DataFloat*)tmp)->v; int v0 = -1; float delta; for (int i = 0; i < m; i++) { v0 = -1; if (edges[i]->K == v) v0 = edges[i]->N; if (edges[i]->N == v) v0 = edges[i]->K; if (v0 == -1) continue; //edgeCount--; delta = dist[v0]->priorities - (dist[v]->priorities + graph->getWeight(v, v0)); if (delta > 0){ dist[v0]->priorities = graph->getWeight(v, v0) + dist[v]->priorities; up[v0] = v; } } } float *result = new float[n]; for (int i = 0; i < n; i++) result[i] = dist[i]->priorities; for (int i = 0; i < n; i++) delete dist[i]; delete []dist; delete queue; delete []up; return result; }
int main() { PriorityQueue<TaskData> taskPQ; // Priority queue of tasks TaskData task; // Task int simLength, // Length of simulation (minutes) minute, // Current minute numPtyLevels = 2, // Number of priority levels numArrivals = 0, // Number of new tasks arriving j; // Loop counter // Seed the random number generator srand((unsigned int)time(NULL)); // cout << endl << "Enter the number of priority levels : "; // cin >> numPtyLevels; cout << "Enter the length of time to run the simulator : "; cin >> simLength; time_t timer; for (minute = 0; minute < simLength; minute++) { // Dequeue the first task in the queue (if any). if (taskPQ.isEmpty() == false) { task=taskPQ.dequeue(); cout << "Priority " << task.priority << " task arrived at " << task.arrived << " & completed at " << minute << endl; } numArrivals = rand() % 4; switch (numArrivals) { case 2: task.arrived = minute; task.priority = rand() % numPtyLevels; //task.priority = rand() % numPtyLevels - (task.arrived / simLength); taskPQ.enqueue(task); case 1: task.arrived = minute; task.priority = rand() % numPtyLevels; taskPQ.enqueue(task); default: break; } } return 0; }
Vector<Vertex*> dijkstrasAlgorithm(BasicGraph& graph, Vertex* start, Vertex* end) { graph.resetData(); PriorityQueue<Vertex*> pqueue; Vector<Vertex*> path; pqueue.enqueue(start, 0); start->cost = 0.0; start->setColor(YELLOW); while(!pqueue.isEmpty()) { Vertex* v = pqueue.dequeue(); v->setColor(GREEN); if (v == end) break; for (auto edge : v->edges) { Vertex* next_v = edge->finish; if (next_v->getColor() == 0) { next_v->setColor(YELLOW); double next_cost = v->cost + edge->cost; next_v->previous = v; next_v->cost = next_cost; pqueue.enqueue(next_v, next_cost); } else if (next_v->getColor() == YELLOW) { double next_cost = v->cost + edge->cost; if (next_cost < next_v->cost) { next_v->cost = next_cost; next_v->previous = v; pqueue.changePriority(next_v, next_v->cost); } } } } if (end->getColor() == GREEN) { Vertex* path_v = end; while (path_v->previous) { path.insert(0, path_v); path_v = path_v->previous; } path.insert(0, path_v); } return path; }
/* * A* search. Will explore from 'end' until it finds 'start' or can determine that no valid path exists. * It explores in reverse to make it easier to build path array. */ vector<Node *> aStar(BasicGraph& graph, Vertex* start, Vertex* end) { graph.resetData(); vector<Vertex*> path; PriorityQueue<Vertex*> openQueue; //Setup starting state end->cost = 0; end->visited = true; openQueue.enqueue(end, end->cost); Vertex* current = nullptr; //While there are still reachable nodes to explore while(!openQueue.isEmpty()){ //Set current node to the next node in the queue current = openQueue.dequeue(); current->setColor(GREEN); //If current node is target, build path and return if(current == start){ rewind(end, start, path); return path; } //Add any unvisited neighbor to queue, adjust cost for already visited neighbor nodes for(Vertex* neighbor : graph.getNeighbors(current)){ if(!neighbor->visited){ neighbor->previous = current; neighbor->visited = true; neighbor->cost = current->cost + graph.getArc(current, neighbor)->cost; openQueue.enqueue(neighbor, neighbor->cost + neighbor->heuristic(start)); neighbor->setColor(YELLOW); }else{ double newCost = current->cost + graph.getArc(current, neighbor)->cost; if(neighbor->cost > newCost){ neighbor->previous = current; neighbor->cost = newCost; openQueue.changePriority(neighbor, neighbor->cost + neighbor->heuristic(start)); neighbor->setColor(YELLOW); } } } } return path; }
/* * Method: kruskal * Parameters: BasicGraph graph by reference * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * Returns a set of Edges that correspond to the minimum * spanning tree of the graph passed by reference. This Kruskal * algorithm implementation leverages a Priority Queue to * connect each Vertex with its minimum cost Edge without * creating cycles, ensuring its a minimum spanning tree. */ Set<Edge*> kruskal(BasicGraph& graph) { Set<Edge*> mst; Map<Vertex*, Set<Vertex*> > clusters; PriorityQueue<Edge*> pqueue; initializeClusters(graph, clusters); enqueueEdges(graph, pqueue); while(!pqueue.isEmpty()) { Edge* edge = pqueue.dequeue(); if(!clusters[edge->start].contains(edge->finish)) { mergeClusters(clusters, edge->start, edge->finish); mst.add(edge); } } return mst; }
int* getOptimalPath(Vertex Graph[], int size, int start, int goal) { PriorityQueue<float> PQ; LinkedList<edge>* Edges; int current, next, i; float NewCost; float *CostSoFar = new float[size]; for (i = 1; i < size; i++) CostSoFar[i] = FLT_MAX; CostSoFar[0] = 0.0; int* parent = new int[size]; //PQ.insert(start, getEuclideanDistance(Coordinates[start], Coordinates[goal])); PQ.insert(start, 0); while (!PQ.isEmpty()) { //PQ.Print(); current = PQ.remove(); if (current == goal) { delete [] CostSoFar; return parent; } else { Edges = &Graph[current].getEdges(); for (Edges->begin(); !Edges->end(); Edges->next()) { next = Edges->getCurrent().to; NewCost = CostSoFar[current] + Edges->getCurrent().cost /*+ getEuclideanDistance(Coordinates[next], Coordinates[goal])*/; if (NewCost < CostSoFar[next]) { CostSoFar[next] = NewCost; parent[next] = current; PQ.insert(next, NewCost); } } } } delete [] CostSoFar; return NULL; }
void Graph::dijkstra(Vertex *src) { comparisons = 0;//tallies number of comparisons made src->d = 0; src->p = NULL; PriorityQueue<Vertex*> pq; for(int i = 0;i<vertList.size();++i){//Fill priority queue if(vertList[i]->getID() != src->getID()){ vertList[i]->d = INT_MAX; vertList[i]->p = NULL; } pq.insertItem(vertList[i]->d, vertList[i], vertList[i]->getID()); } while(!pq.isEmpty()){//Start sifting through the vertices Vertex* u = pq.minElement(); pq.removeMin(); int sz = u->outList.size(); for(int i =0; i < sz;++i){ int alt = u->d + u->outList[i]->getWeight(); Vertex* evalVert = u->outList[i]->geteVertP(); comparisons++; if(u->outList[i]->geteVertP()->d == INT_MAX){//relax function Locator repkey = pq.getLoc(evalVert->getID()); pq.replaceKey(repkey,alt); evalVert->setD(alt); evalVert->setP(u); } else if(alt < u->outList[i]->geteVertP()->d){//relax function Locator repkey = pq.getLoc(evalVert->getID()); pq.replaceKey(repkey,alt); evalVert->setD(alt); evalVert->setP(u); } } } comparisons += pq.getComps();//grab comparisons from priority queue return; }
int main() { PriorityQueue<DataType> testPQA; PriorityQueue<DataType> testPQB; PriorityQueue<DataType> testPQC; char cmdChar; DataType dataItem; int qPriority; char qProcess[ SMALL_STR_LEN ]; bool dataChanged; ShowMenu(); do { dataChanged = false; cout << endl << "Command: "; // Read command cmdChar = GetCommandInput( qProcess, qPriority ); switch ( cmdChar ) { case 'c': case 'C': // clear priority queue while( !testPQA.isEmpty() ) { testPQA.dequeue( dataItem ); } if( VERBOSE ) { cout << " Priority Queue has been cleared " << endl; } dataChanged = true; break; case 'd': case 'D': // dequeue one data item testPQA.dequeue( dataItem ); if( VERBOSE ) { cout << " Process: " << dataItem.process << " has been dequeued with a priority of " << dataItem.priority << PERIOD << endl; } dataChanged = true; break; case 'e': case 'E': // enqueue testPQA.enqueue( qPriority, qProcess ); if( VERBOSE ) { cout << " Process: " << qProcess << " has been enqueued with a priority of " << qPriority << PERIOD << endl; } dataChanged = true; break; case 'h': case 'H': // help request ShowMenu(); break; case 'p': case 'P': // peek at next item testPQA.peekAtFront( dataItem ); if( VERBOSE ) { cout << " Process: " << dataItem.process << " with priority: " << dataItem.priority << " found at front of queue." << endl; } break; case 'q': case 'Q': // quit the test program if( VERBOSE ) { cout << " End Program Requested" << endl; } cout << endl; break; case 'x': case 'X': // create copy constructor PQ // tempPQ constructed in code block to control scope { PriorityQueue<DataType> tempPQ( testPQA ); testPQC = tempPQ; } if( VERBOSE ) { cout << " Test PQ \'C\' has been constructed with test PQ \'A\'." << endl; } dataChanged = true; break; case 'z': case 'Z': // assign to b PQ testPQB = testPQA; if( VERBOSE ) { cout << " Test PQ \'A\' has been assigned to test PQ \'B\'." << endl; } dataChanged = true; break; default : // Invalid command // clear to end of line in case further data input cin.ignore( SMALL_STR_LEN, ENDLINE_CHAR ); if( VERBOSE ) { cout << " Inactive or invalid command" << endl; } } if( dataChanged ) { testPQA.showStructure( 'A' ); testPQB.showStructure( 'B' ); testPQC.showStructure( 'C' ); } } while ( cmdChar != 'q' && cmdChar != 'Q' ); return 0; }
void testPriorityQueue(){ PriorityQueue<int> mycontainer; cout << "\n\n Begin test function for the PriorityQueue<T> class\n"; // Testing the enqueue function cout << "Testing size of new empty container: " << mycontainer.length() << endl; cout << "Testing enqueue(1), length(), and isEmpty() functions. mycontainer is empty? " << (mycontainer.isEmpty() ? " true\n" : "false\n"); mycontainer.enqueue(1); cout << "Size is " << mycontainer.length() << endl; cout << "Testing enqueue(2), length(), and isEmpty() functions. mycontainer is empty? " << (mycontainer.isEmpty() ? " true\n" : "false\n"); mycontainer.enqueue(2); cout << "Size is " << mycontainer.length() << endl; cout << "Testing enqueue(2), length(), and isEmpty() functions. mycontainer is empty? " << (mycontainer.isEmpty() ? " true\n" : "false\n"); mycontainer.enqueue(2); cout << "Size is " << mycontainer.length() << endl; cout << "Testing enqueue(2), length(), and isEmpty() functions. mycontainer is empty? " << (mycontainer.isEmpty() ? " true\n" : "false\n"); mycontainer.enqueue(2); cout << "Size is " << mycontainer.length() << endl; cout << "Testing enqueue(2), length(), and isEmpty() functions. mycontainer is empty? " << (mycontainer.isEmpty() ? " true\n" : "false\n"); mycontainer.enqueue(2); cout << "Size is " << mycontainer.length() << endl; cout << "Testing enqueue(2), length(), and isEmpty() functions. mycontainer is empty? " << (mycontainer.isEmpty() ? " true\n" : "false\n"); cout << "Size is " << mycontainer.length() << endl << endl; int size = mycontainer.length(); cout << "Testing pop_back(), front(), back(), length() and isEmpty() functions \n" << "in a for loop with iterations greater than container size."; for (int i = 0; i < size + 1; i++) { cout << "\nIteration: " << i + 1 << "\n"; if (!mycontainer.isEmpty()) { cout << " mycontainer is empty? " << (mycontainer.isEmpty() ? " true\n" : "false\n"); cout << "PriorityQueue size before pop is " << mycontainer.length() << endl; //cout<<"Front of container is " << mycontainer.front()<<endl; //cout<<"Back of container is " << mycontainer.back()<<endl; //cout << "Popping: " << mycontainer.front() << endl << endl; mycontainer.pop_back(); } else { cout << "The PriorityQueue is empty.\n"; } cout << "PriorityQueue size is now: " << mycontainer.length() << endl; } cout << "\nFinished for loop\n"; cout << "\nTesting the reference for front() and back() functions.\n"; cout << "Start with int test = 7. mycontainer.enqueue(test)\n"; int test = 7; mycontainer.enqueue(test); cout << "Testing with test = 8. test=mycontainer.front(). mycontainer.front() = 13 \n"; test = 8; test = mycontainer.front(); mycontainer.front() = 13; cout << "Test is now " << test << " front of container is " << mycontainer.front() << " back of container is " << mycontainer.back() << endl; test = 11; mycontainer.enqueue(test); cout << "Back of container is: " << mycontainer.back() << endl; cout << "Test is now " << test << " front of container is " << mycontainer.front() << " back of container is " << mycontainer.back() << endl; mycontainer.back() = test; cout << "Test is now " << test << " front of container is " << mycontainer.front() << " back of container is " << mycontainer.back() << endl; cout << "mycontainer size is " << mycontainer.length() << endl; cout << "\nTesting the clear() function: \n"; mycontainer.clear(); cout << "mycontainer size now is " << mycontainer.length() << " mycontainer is empty: " << (mycontainer.isEmpty() ? " true\n" : "false\n"); cout << "\nTesting assignment operator: container2 = mycontainer\n"; cout << "Filling mycontainer with ints starting at 42\n"; size = 5; // Fill mycontainer with ints to test copy constructor for (int i = 0; i < size; i++) { mycontainer.enqueue(i + 41); } cout << "mycontainer size now is " << mycontainer.length() << " mycontainer is empty: " << (mycontainer.isEmpty() ? " true\n" : "false\n"); PriorityQueue<int> container2; container2 = mycontainer; cout << "mycontainer size is: " << mycontainer.length() << endl; cout << "container2 size is: " << container2.length() << endl; cout << "Testing the contents of container2 and mycontainer using back() and pop_back() functions:\n"; size = container2.length(); for (int i = 0; i < size; i++) { cout << "Attempting front and pop functions. Iteration: " << i + 1 << "\n"; // Don't perform the operation if either container is empty. // Output should be the same for both containers if (!container2.isEmpty() || !mycontainer.isEmpty()) { cout << "\tcontainer2 - front(): " << container2.front() << " back(): " << container2.back() << endl; container2.pop_back(); cout << "\tmycontainer - front(): " << mycontainer.front() << " back(): " << mycontainer.back() << endl; mycontainer.pop_back(); } else { cout << "Containers are empty.\n"; } } cout << "\nTesting the copy constructor. Filling mycontainer ints\n"; size = 5; // Fill mycontainer with ints to test copy constructor for (int i = 0; i < size; i++) { mycontainer.enqueue(i + 41); } cout << "mycontainer size now is " << mycontainer.length() << " mycontainer is empty: " << (mycontainer.isEmpty() ? " true\n" : "false\n"); PriorityQueue<int> container3(mycontainer); cout << "container3 size is: " << container3.length(); cout << "\nTesting the contents of container3 and mycontainer using back() and pop_back() functions:\n"; size = container3.length(); for (int i = 0; i < size; i++) { cout << "Attempting front and pop functions. Iteration: " << i + 1 << "\n"; // Don't perform the operation if either container is empty. // Output should be the same for both containers if (!container3.isEmpty() || !mycontainer.isEmpty()) { cout << "\tcontainer3 - front(): " << container3.front() << " back(): " << container3.back() << endl; container3.pop_back(); cout << "\tmycontainer - front(): " << mycontainer.front() << " back(): " << mycontainer.back() << endl; mycontainer.pop_back(); } else { cout << "Containers are empty.\n"; } } cout << "\nEnd of test function for the PriorityQueue<T> class\n\n"; }
inline void singleDefUse(FlowGraph* fg, X86Instruction* ins, BasicBlock* bb, Loop* loop, std::pebil_map_type<uint64_t, X86Instruction*>& ipebil_map_type, std::pebil_map_type<uint64_t, BasicBlock*>& bpebil_map_type, std::pebil_map_type<uint64_t, LinkedList<X86Instruction::ReachingDefinition*>*>& alliuses, std::pebil_map_type<uint64_t, LinkedList<X86Instruction::ReachingDefinition*>*>& allidefs, int k, uint64_t loopLeader, uint32_t fcnt){ // Get defintions for this instruction: ins LinkedList<X86Instruction::ReachingDefinition*>* idefs = ins->getDefs(); LinkedList<X86Instruction::ReachingDefinition*>* allDefs = idefs; // Skip instruction if it doesn't define anything if (idefs == NULL) { return; } if (idefs->empty()) { delete idefs; return; } set<LinkedList<X86Instruction::ReachingDefinition*>*> allDefLists; allDefLists.insert(idefs); PriorityQueue<struct path*, uint32_t> paths = PriorityQueue<struct path*, uint32_t>(); bool blockTouched[fg->getFunction()->getNumberOfBasicBlocks()]; bzero(&blockTouched, sizeof(bool) * fg->getFunction()->getNumberOfBasicBlocks()); // Initialize worklist with the path from this instruction // Only take paths inside the loop. Since the definitions are in a loop, uses in the loop will be most relevant. if (k == bb->getNumberOfInstructions() - 1){ ASSERT(ins->controlFallsThrough()); if (bb->getNumberOfTargets() > 0){ ASSERT(bb->getNumberOfTargets() == 1); if (flowsInDefUseScope(bb->getTargetBlock(0), loop)){ // Path flows to the first instruction of the next block paths.insert(new path(bb->getTargetBlock(0)->getLeader(), idefs), 1); } } } else { // path flows to the next instruction in this block paths.insert(new path(bb->getInstruction(k+1), idefs), 1); } // while there are paths in worklist while (!paths.isEmpty()) { // take the shortest path in list uint32_t currDist; struct path* p = paths.deleteMin(&currDist); X86Instruction* cand = p->ins; idefs = p->defs; delete p; LinkedList<X86Instruction::ReachingDefinition*>* i2uses, *i2defs, *newdefs; i2uses = alliuses[cand->getBaseAddress()]; // Check if any of idefs is used if(i2uses != NULL && anyDefsAreUsed(idefs, i2uses)){ // Check if use is shortest uint32_t duDist; duDist = trueDefUseDist(currDist, fcnt); if (!ins->getDefUseDist() || ins->getDefUseDist() > duDist) { ins->setDefUseDist(duDist); } // If dist has increased beyond size of function, we must be looping? if (currDist > fcnt) { ins->setDefXIter(); break; } // Stop searching along this path continue; } // Check if any defines are overwritten i2defs = allidefs[cand->getBaseAddress()]; newdefs = removeInvalidated(idefs, i2defs); // If all definitions killed, stop searching along this path if (newdefs == NULL) continue; allDefLists.insert(newdefs); // end of block that is a branch if (cand->usesControlTarget() && !cand->isCall()){ BasicBlock* tgtBlock = bpebil_map_type[cand->getTargetAddress()]; if (tgtBlock && !blockTouched[tgtBlock->getIndex()] && flowsInDefUseScope(tgtBlock, loop)){ blockTouched[tgtBlock->getIndex()] = true; if (tgtBlock->getBaseAddress() == loopLeader){ paths.insert(new path(tgtBlock->getLeader(), newdefs), loopXDefUseDist(currDist + 1, fcnt)); } else { paths.insert(new path(tgtBlock->getLeader(), newdefs), currDist + 1); } } } // non-branching control if (cand->controlFallsThrough()){ BasicBlock* tgtBlock = bpebil_map_type[cand->getBaseAddress() + cand->getSizeInBytes()]; if (tgtBlock && flowsInDefUseScope(tgtBlock, loop)){ X86Instruction* ftTarget = ipebil_map_type[cand->getBaseAddress() + cand->getSizeInBytes()]; if (ftTarget){ if (ftTarget->isLeader()){ if (!blockTouched[tgtBlock->getIndex()]){ blockTouched[tgtBlock->getIndex()] = true; if (ftTarget->getBaseAddress() == loopLeader){ paths.insert(new path(ftTarget, newdefs), loopXDefUseDist(currDist + 1, fcnt)); } else { paths.insert(new path(ftTarget, newdefs), currDist + 1); } } } else { paths.insert(new path(ftTarget, newdefs), currDist + 1); } } } } } if (!paths.isEmpty()){ ins->setDefUseDist(0); } while (!paths.isEmpty()){ delete paths.deleteMin(NULL); } while (!allDefs->empty()){ delete allDefs->shift(); } for(set<LinkedList<X86Instruction::ReachingDefinition*>*>::iterator it = allDefLists.begin(); it != allDefLists.end(); ++it){ delete *it; } }
vector<Node *> dijkstrasAlgorithm(BasicGraph& graph, Vertex* start, Vertex* end) { graph.resetData(); //set as predescessor if that is undefined Vertex* unDefined; //the current node we are checking Vertex* currentNode; //sets startnode cost to zero start->cost=0.0; //create prioqueue PriorityQueue<Vertex*> vertexPrioQueue; //used to keep track of all predeccesors map<Vertex*,Vertex*> predecessor; //set all costs, sets predecessor and adds the to the queue for (Node *node :graph.getNodeSet()){ //all nodes but start should have infinity cost if (node!=start){ node->cost=INFINITY; predecessor[node]=unDefined; } //add all nodes to queue vertexPrioQueue.enqueue(node,node->cost); } //keep track of the alternative cost double alt; //while the queue is not empty while (!vertexPrioQueue.isEmpty()){ //put current node to the one with highest priority currentNode= vertexPrioQueue.front(); vertexPrioQueue.dequeue(); currentNode->setColor(YELLOW); currentNode->visited=true; if (currentNode==end){ break; } //check all the node's neighbors for(Node *node :graph.getNeighbors(currentNode)){ //if we have not visited that node if (!node->visited){ //we check the alternative cost alt=currentNode->cost+graph.getArc(currentNode,node)->cost; //if the alternative cost is lower then we set that to our new cost if (alt<node->cost){ node->cost=alt; predecessor[node]=currentNode; vertexPrioQueue.changePriority(node,alt); } } } currentNode->setColor(GREEN); } //if we havent found end if(predecessor[end]==unDefined){ vector<Vertex*> path; return path; } else{ //if we have found end we trace through the predecessor map to find the path stack<Vertex*> vertexStack; vector<Vertex*> path; currentNode=end; while (currentNode!=start){ vertexStack.push(currentNode); currentNode=predecessor[currentNode]; } vertexStack.push(start); while (!vertexStack.empty()){ path.push_back(vertexStack.top()); vertexStack.pop(); } return path; } }
/* main() manages the user interface; * instantiates priority queue object, then operates loop to read input * from user and call the appropriate priority queue method */ int main() { PriorityQueue pq; TokenScanner scanner; while (true) { string line = getLine("> "); scanner.setInput(line); scanner.ignoreWhitespace(); string cmd=scanner.nextToken(); if (cmd == "help") { helpCommand(); } else if (cmd == "enqueue") { if(scanner.hasMoreTokens()){ string value=scanner.nextToken(); if(scanner.hasMoreTokens()){ scanner.scanNumbers(); string priorityStr=scanner.nextToken(); double priority=stringToDouble(priorityStr); pq.enqueue(value,priority); } else pq.enqueue(value); } } else if (cmd == "dequeue") { if(pq.isEmpty()) cout<<"The queue is empty"<<endl; else cout<<pq.dequeue()<<endl; } else if (cmd == "peek") { if(pq.isEmpty()) cout<<"The queue is empty"<<endl; else cout<<pq.peek()<<endl; } else if (cmd == "peekPriority"||cmd=="peekpriority") { if(pq.isEmpty()) cout<<"The queue is empty"<<endl; else cout<<pq.peekPriority()<<endl; } else if (cmd == "clear") { pq.clear(); } else if (cmd == "size") { cout<<pq.size()<<endl; } else if (cmd == "isEmpty"||cmd=="isempty") { if(pq.isEmpty()) cout<<"true"; else cout<<"false"; cout<<endl; } else if(cmd=="list") list(pq); else { cout << "Undefined command: " << cmd << endl; } } return 0; }
int main() { // problem setup goes here bool test1=true, test2=true; PriorityQueue<double> pq; int i, REPS = 1000000; srand (time(NULL)); while(test1) // operator[] assignment at zeroth index, O(1) { cout << "\n Test 1 - enqueue, O(log n)\n\n"; // programmer customizations go here double n = 500000; // THE STARTING PROBLEM SIZE string bigOh = "O(log n)"; // YOUR PREDICTION: O(1), O(log n), O(n), O(n log n), or O(n squared) int elapsedTimeTicksNorm; double expectedTimeTicks, m; for (int cycle=0; cycle<4; cycle++, n*=2) { // more problem setup goes here -- the stuff not timed for(i=0; i<n; i++) pq.enqueue(rand() % RAND_MAX); long elapsedTimeTicks = 0; for (i=0; i<REPS; i++) { m = rand() % RAND_MAX; assert(pq.size()==n); // initize the timer clock_t startTime = clock(); // do something where n is the "size" of the problem pq.enqueue(m); // compute timing results clock_t endTime = clock(); elapsedTimeTicks += (long)(endTime - startTime); pq.dequeue(m); } double factor = pow(2.0, cycle); if (cycle == 0) elapsedTimeTicksNorm = elapsedTimeTicks; else if (bigOh == "O(1)") expectedTimeTicks = elapsedTimeTicksNorm; else if (bigOh == "O(log n)") expectedTimeTicks = log(double(n)) / log(n / factor) * elapsedTimeTicksNorm; else if (bigOh == "O(n)") expectedTimeTicks = factor * elapsedTimeTicksNorm; else if (bigOh == "O(n log n)") expectedTimeTicks = factor * log(double(n)) / log(n / factor) * elapsedTimeTicksNorm; else if (bigOh == "O(n squared)") expectedTimeTicks = factor * factor * elapsedTimeTicksNorm; // reporting block cout << elapsedTimeTicks; if (cycle == 0) cout << " (expected " << bigOh << ')'; else cout << " (expected " << expectedTimeTicks << ')'; cout << " for n=" << n << endl; pq.makeEmpty(); assert(pq.isEmpty()); } test1=false; } REPS = 500000; while(test2) // operator[] assignment at 100th index, O(1) { cout << "\n\n Test 2 - dequeue, O(log n)\n\n"; // programmer customizations go here double n = 500000; // THE STARTING PROBLEM SIZE string bigOh = "O(log n)"; // YOUR PREDICTION: O(1), O(log n), O(n), O(n log n), or O(n squared) int elapsedTimeTicksNorm; double expectedTimeTicks; for (int cycle=0; cycle<4; cycle++, n*=2) { // more problem setup goes here -- the stuff not timed for(i=0; i<n; i++) pq.enqueue(rand() % RAND_MAX); // fill pq long elapsedTimeTicks = 0; clock_t startTime, endTime; double j; for (i=0; i<REPS; i++) { assert(pq.size()==n); // initize the timer startTime = clock(); // do something where n is the "size" of the problem pq.dequeue(j); // compute timing results endTime = clock(); elapsedTimeTicks += (long)(endTime - startTime); pq.enqueue(j); } double factor = pow(2.0, cycle); if (cycle == 0) elapsedTimeTicksNorm = elapsedTimeTicks; else if (bigOh == "O(1)") expectedTimeTicks = elapsedTimeTicksNorm; else if (bigOh == "O(log n)") expectedTimeTicks = log(double(n)) / log(n / factor) * elapsedTimeTicksNorm; else if (bigOh == "O(n)") expectedTimeTicks = factor * elapsedTimeTicksNorm; else if (bigOh == "O(n log n)") expectedTimeTicks = factor * log(double(n)) / log(n / factor) * elapsedTimeTicksNorm; else if (bigOh == "O(n squared)") expectedTimeTicks = factor * factor * elapsedTimeTicksNorm; // reporting block cout << elapsedTimeTicks; if (cycle == 0) cout << " (expected " << bigOh << ')'; else cout << " (expected " << expectedTimeTicks << ')'; cout << " for n=" << n << endl; pq.makeEmpty(); assert(pq.isEmpty()); } test2=false; } cout << endl; return 0; }
//this is the same as dijkstrasAlgorithm except for one thing which is commented vector<Node *> aStar(BasicGraph& graph, Vertex* start, Vertex* end) { graph.resetData(); Vertex* unDefined; Vertex* currentNode; start->cost=0.0; PriorityQueue<Vertex*> vertexPrioQueue; map<Vertex*,Vertex*> predecessor; for (Node *node :graph.getNodeSet()){ if (node!=start){ node->cost=INFINITY; predecessor[node]=unDefined; } vertexPrioQueue.enqueue(node,node->cost);; } double alt; while (!vertexPrioQueue.isEmpty()){ currentNode= vertexPrioQueue.front(); vertexPrioQueue.dequeue(); currentNode->setColor(YELLOW); currentNode->visited=true; if (currentNode==end){ break; } for(Node *node :graph.getNeighbors(currentNode)){ if (!node->visited){ alt=currentNode->cost+graph.getArc(currentNode,node)->cost; if (alt<node->cost){ node->cost=alt; predecessor[node]=currentNode; //this is the change, the queuepriority comes from the node cost + the heuristic vertexPrioQueue.changePriority(node,node->cost+node->heuristic((end))); } } } currentNode->setColor(GREEN); } if(predecessor[end]==unDefined){ vector<Vertex*> path; return path; } else{ stack<Vertex*> vertexStack; vector<Vertex*> path; currentNode=end; while (currentNode!=start){ vertexStack.push(currentNode); currentNode=predecessor[currentNode]; } vertexStack.push(start); while (!vertexStack.empty()){ path.push_back(vertexStack.top()); vertexStack.pop(); } return path; } }
/* * Function: kruskal * -------------------- * This function implements kruskal algorithm to create a minimum graph with all * vertexes connected with least cost or number of edges * * Preconditions: * * @param: graph: The graph to be minimized * * @return: returns a set of edges in the MST */ Set<Edge*> kruskal(BasicGraph& graph) { graph.resetData(); // Reset data jic PriorityQueue<Edge*> pq; // pq to hold the edges with least cost first Map<Vertex*, Set<Vertex*>*> mp; // Our cluster storing structure Set<Edge*> mst; // Our edge return set // PLace all edges into a pq with cost=priority for(Edge* e:graph.getEdgeSet()){ pq.add(e,e->cost); } // Make clusters through map structure for(Vertex* v:graph.getVertexSet()){ Set<Vertex*>* clusterSet = new Set<Vertex*>; clusterSet->add(v); mp.add(v,clusterSet); } // While the priority queue is not empty while(!pq.isEmpty()){ Edge* e = pq.dequeue(); Vertex* v1 = e->start; Vertex* v2 = e->end; // If the pointers point to the same Set, they must // be connected if(mp[v1]!=mp[v2]){ // Make a temporary pointer to v2's Set Set<Vertex*>* tempPointer = mp[v2]; // Set all clusters in v2's set to point to v1's set for(Vertex* v:*tempPointer){ mp[v1]->add(v); Set<Vertex*>* tempPointer2 = mp[v]; mp[v] = mp[v1]; // Dont delete same pointer twice if(tempPointer2!=tempPointer) delete tempPointer2; } // Delete abandoned memory delete tempPointer; // Add edge e to MST mst.add(e); } } // Free large cluster of memory for(Vertex* v:mp){ Set<Vertex*>* toDelete = mp[v]; delete toDelete; break; } return mst; }
/* * Function: aStar * -------------------- * This function implements aStar search (variation of dijkstras with a heuristic) * * Preconditions: * * @param: graph: The graph to be searched * start: The start vertex * end:The end vertex * @return: returns a vector of vertexes containing the path (empty if no path) */ Vector<Vertex*> aStar(BasicGraph& graph, Vertex* start, Vertex* end) { graph.resetData(); // reset Vector<Vertex*> path; // the return path Set<Vertex*> inQueue; // A vector holding the values that we have already put into the queue // INitialize every vertex to have infinite cost for(Vertex* s:graph.getVertexSet()){ s->cost = POSITIVE_INFINITY; } PriorityQueue<Vertex*> pq; // A pq to see where to search next (cost+heuristic = priority) // Set start's cost to 0 + heuristicFxn val start->cost = 0 + heuristicFunction(start,end); // Enqueue start vertex pq.enqueue(start,0); start->setColor(YELLOW); inQueue.add(start); // While there are still elements in the pq to try while(!pq.isEmpty()){ Vertex* v = pq.dequeue(); inQueue.remove(v); v->visited = true; v->setColor(GREEN); // We can stop (reached end) if(v == end){ // We have reached the end, deconstruct path.clear(); Vertex* temp = v; path.insert(0,temp); while(temp->previous!=NULL){ // deconstruct temp = temp->previous; path.insert(0,temp); } break; } // For each unvisited neighbor of v vertex for (Vertex* n: graph.getNeighbors(v)){ // And it's unvisited if(n->visited == false){ // v's cost plus weight of edge Edge* e = graph.getEdge(v,n); double edgeCost = e->cost; double costToVertexN = v->cost + edgeCost; // If the costToVertexN < n->cost, we know this is a better way to get to // vertex n if(costToVertexN < n->cost){ n->cost = costToVertexN; n->previous = v; n->setColor(YELLOW); // Check to see if pq already contains n if(inQueue.contains(n)){ // Priority now includes heuristic pq.changePriority(n,costToVertexN + heuristicFunction(n,end)); } else { pq.enqueue(n,costToVertexN + heuristicFunction(n,end)); } } } } } return path; }
int main() { int comps=0; //BH comparisons string txt; cout << "Enter name of txt file without extension: " << endl; cin >> txt; string str(txt + ".txt"); Graph graph(str); graph.PrintGraph(); int sVert, dVert; cout << "Enter the source vertex: " << endl; cin >> sVert; cout << "Enter the destination vertex: " << endl; cin >> dVert; cout << " " << endl; // for storing distances and extracting the minimum; equivalent to Q and d[] on the slides PriorityQueue<int> pq; int size = graph.getSize(); //graph size int kArray[size]; for(int i = 0; i < size; i++) {kArray[i] = INT_MAX;} //key/weight int xArray[size]; for(int i = 1; i <= size; i++) {xArray[i-1] = i;} //element pq.createPriorityQueue(kArray, xArray, xArray, size); // for storing the parent (previous node) on the path; equivalent to pi[] on the slides int* shortestPathParent = new int[size + 1]; for(int i = 0; i < size; i++) {shortestPathParent[i] = 0;} // Dijkstra's algorithm Locator sl = pq.getLocator(sVert); //locator keeps track of element's memory address pq.replaceKey(sl,0); if(sVert > size || dVert > size || sVert < 0 || dVert < 0) throw "No such vertex exists"; vector<Vertex*> del; // removed vertices vector<Vertex*> vertList = graph.getVertices(); while( !pq.isEmpty()) { Vertex* u = vertList[pq.minElement() - 1]; Locator locu = pq.getLocator(u->getID()); int ukey = pq.getKey(locu); pq.removeMin(); del.push_back(u); vector<Edge*> edges = u->getOutEdges(); for( int i = 0; i < edges.size(); i++ ) { Vertex* v = edges[i] -> geteVertP(); int w = edges[i] -> getWeight(); Locator locv = pq.getLocator(v->getID()); if(comps++, pq.getKey(locv) > (ukey + w)) //if (d[b] > d[a] + w(a,b)) { pq.replaceKey(locv, ukey + w); //d[b] = d[a] + w(a,b) shortestPathParent[v->getID()] = u->getID(); //P[b] = a } } } Vertex* d = graph.getVertex(dVert); Vertex* s = graph.getVertex(sVert); vector<int>vers, wt; vector<Edge*> e = vertList[dVert-1]->getInEdges(); int c = 0; vers.push_back(dVert); if (sVert == dVert) { vers.push_back(dVert); wt.push_back(0); } else { while (c != sVert) { //compare edges int minw = e[0]->getWeight(); int minv = e[0]->getsVertP()->getID(); for (int i = 0; i < e.size(); i++) { if(e[i]->getWeight() < minw) { minw = e[i]->getWeight(); minv = e[i]->getsVertP()->getID(); } } wt.push_back(minw); vers.push_back(minv); c = vertList[minv-1]->getID(); e = vertList[minv-1]->getInEdges(); } reverse(wt.begin(),wt.end()); reverse(vers.begin(),vers.end()); } for (int i = 0; i < vers.size()-1; i++) { cout << vers[i] << "--[" << wt[i] << "]-->"; } cout << dVert << endl; int dist = 0; for (int i = 0; i < wt.size(); i++) { dist = dist + wt[i]; } cout << " " << endl; cout << "Total weight of the shortest path from " << sVert << " to " << dVert << " = " << dist << endl; cout << "Total number of comparisons needed to decrease key values: " << comps; return 0; }