本文整理汇总了C++中PriorityQueue类的典型用法代码示例。如果您正苦于以下问题:C++ PriorityQueue类的具体用法?C++ PriorityQueue怎么用?C++ PriorityQueue使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PriorityQueue类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: prim
void prim(Graph graph, char startNode){
PriorityQueue priorityQueue;
Node node;
node.key = INT_MAX;
node.pi = '\0';
// for (auto it = graph.getVertices().begin(); it != graph.getVertices().end(); it++){
// node.name = *it;
// priorityQueue.push(node);
// }
string tempString = "";
for (auto it = graph.getVertices().begin(); it != graph.getVertices().end(); it++)
tempString += *it;
cout << tempString << "!!!" << endl;
for (int i = 0; i < tempString.length(); i++){
node.name = tempString.c_str()[i];
priorityQueue.push(node);
}
// Node node;
// node.key = INT_MAX;
// node.pi = '\0';
// node.name = 'i';
// priorityQueue.push(node);
// node.name = 'a';
// priorityQueue.push(node);
// node.name = 'b';
// priorityQueue.push(node);
// node.name = 'c';
// priorityQueue.push(node);
// node.name = 'd';
// priorityQueue.push(node);
// node.name = 'e';
// priorityQueue.push(node);
// node.name = 'f';
// priorityQueue.push(node);
// node.name = 'g';
// priorityQueue.push(node);
// node.name = 'h';
// priorityQueue.push(node);
cout << "finished inserting vertices" << endl;
priorityQueue.decreaseKey(startNode, 0, '\0');
while (!priorityQueue.empty()){
Node node = priorityQueue.extractMin();
cout << "extracted: " << node.name << ": " << node.key << ", " << node.pi << endl;
if (node.name != node.pi && node.pi != '\0')
cout << "(" << node.name << ", " << node.pi << ") " << endl;
for (auto it = graph.getEdges().begin(); it != graph.getEdges().end(); it++){
cout << "checking " << it->first << endl;
if (it->first.c_str()[0] == node.name || it->first.c_str()[1] == node.name){// Adjacency
char adjacency = (it->first.c_str()[0] == node.name)?it->first.c_str()[1]:it->first.c_str()[0];
cout << "going for adj" << adjacency << endl;
if (priorityQueue.find(adjacency) && priorityQueue.getNode(adjacency).key > graph.getWeight(node.name, adjacency)){
cout << "decreasingKey: " << adjacency << ", w: " << graph.getWeight(node.name, adjacency) << ", " << node.name << endl;
priorityQueue.decreaseKey(adjacency, graph.getWeight(node.name, adjacency), node.name);
}
}
}
}
cout << endl;
}
示例2: printQueue
void printQueue(PriorityQueue<int> &queue) //print out current list
{
std::cout << "The current queue is: ";
queue.print(); //print out list
std::cout << std::endl << std::endl;
}
示例3: enqueueEdges
/*
* Method: enqueueEdges
* Parameters: BasicGraph graph by reference
* PriorityQueue of Edge pointer variables
* that comprise the graph
* - - - - - - - - - - - - - - - - - - - - - - - - - -
* Returns by reference a Priority Queue of Edge pointer
* variables according to their randomly assigned weights.
* This PQueue is then used to construct the minimum spanning tree.
*/
void enqueueEdges(BasicGraph& graph, PriorityQueue<Edge*>& pqueue) {
Set<Edge*> graphEdges = graph.getEdgeSet();
for(Edge* edge : graphEdges) {
pqueue.enqueue(edge, edge->cost);
}
}
示例4: main
int main( int argc, char **argv )
{
// VARIABLES FOR INPUT
char str[ MAX_LINE_LENGTH +1 ] ;
ssize_t nchars;
state_t state; // state_t is defined by the PSVN API. It is the type used for individual states.
PriorityQueue<state_t> open;
//state_map_t *map = new_state_map();//******
// VARIABLES FOR ITERATING THROUGH state's SUCCESSORS
state_t child;
ruleid_iterator_t iter; // ruleid_terator_t is the type defined by the PSVN API successor/predecessor iterators.
int ruleid ; // an iterator returns a number identifying a rule
int64_t totalNodes;
// READ A LINE OF INPUT FROM stdin
printf("Please enter a state followed by ENTER: ");
if ( fgets(str, sizeof str, stdin) == NULL ) {
printf("Error: empty input line.\n");
return 0;
}
// CONVERT THE STRING TO A STATE
nchars = read_state( str, &state );
if (nchars <= 0) {
printf("Error: invalid state entered.\n");
return 0;
}
printf("The state you entered is: ");
print_state( stdout, &state );
printf("\n");
List StateList = List();
// state_map_add( map, &state, 0 );//******dont know if its a must
open.Add(0,0,state);
StateList.add(&state);
StateList.change_color(&state,1);// Gray
// StateList.change_distance(&state,0);
totalNodes = 0;
int d = 0;
/* Search */
while ( !open.Empty() ) {
// g.n
d = open.CurrentPriority();
printf("D: %d\n",d);
state = open.Top();
open.Pop();
totalNodes++;
/* DDD */
if (StateList.get_color(&state)==0 || (StateList.get_distance(&state)>(d-1))){
StateList.change_distance(&state,d);
if (is_goal(&state)==1){
//PRINT STUFF
printf("Estado: ");
print_state( stdout, &state);
printf(" Estados Generados: %"PRId64" , costo: %d",totalNodes,StateList.get_distance(&state));
return 1;//SUCCES
}
/* expand node */
init_fwd_iter(&iter, &state);
while((ruleid = next_ruleid(&iter)) >= 0){
apply_fwd_rule(ruleid,&state,&child);//'child' is a succesor state_t of 'state'
StateList.add(&child);
StateList.change_color(&child, 1);//Gray
const int child_d = d + get_fwd_rule_cost(ruleid);
StateList.change_distance( &child , child_d );
open.Add( child_d , child_d , child );
}
StateList.change_color(&state,2); //Black
}
}
printf("FAIL!");
return 2; //FAIL
}
示例5: while
//- "k_nearest_neighbor"
//- Find the K nearest neighbors to a point.
//-
//- Description:
//- This algorithm is based on the best-first search. The goal of this
//- algorithm is to minimize the number of nodes visited by using the
//- distance to each subtree's bounding box to avoid visiting subtrees
//- which could not possibly contain one of the k nearest objects.
//-
template <class Z> CubitStatus KDDTree<Z>::k_nearest_neighbor
(CubitVector &q, int k, double &closest_dist, DLIList<Z> &nearest_neighbors,
typename KDDTree<Z>::DistSqFunc dist_sq_point_data
)
{
//// Create the priority queues
PriorityQueue<KDDTreeNode<Z>*> *queue = new PriorityQueue<KDDTreeNode<Z>*> (KDDTree<Z>::less_than_func);
PriorityQueue<KDDTreeNode<Z>*> *queueTemp = new PriorityQueue<KDDTreeNode<Z>*> (KDDTree<Z>::less_than_func);
KDDTreeNode<Z> *element = root;
// push this node on the queue
element->set_dist (min_dist_sq (q, element->safetyBox));
element->set_dist_data (DD_SAFETY);
queue->push (element);
// if the k closest nodes on the tree are not leaf-nodes, expand the closest
// non-leaf node
while ( !queue->empty() )
{
element = queue->top();
queue->pop();
if (element->get_dist_data() == DD_LEAF)
{
// this node is a leaf, so it can be pushed onto the temporary queue
queueTemp->push (element);
}
else
{
// one of the top k nodes is a non-leaf node, so expand it
if (element->left)
{
element->left->set_dist (min_dist_sq (q, element->left->safetyBox));
element->left->set_dist_data (DD_SAFETY);
queue->push (element->left);
}
if (element->right)
{
element->right->set_dist (min_dist_sq (q, element->right->safetyBox));
element->right->set_dist_data (DD_SAFETY);
queue->push (element->right);
}
element->set_dist (dist_sq_point_data (q, element->data));
element->set_dist_data (DD_LEAF);
queue->push (element);
// take all the elements in the temporary queue and reinsert them into
// the actual queue
while ( !queueTemp->empty() )
{
queue->push ( queueTemp->top() );
queueTemp->pop ();
}
}
if (queueTemp->size() == k)
{
// success-- place the k nodes into the nearest_neighbors list
element = queueTemp->top();
queueTemp->pop();
closest_dist = element->get_dist();
nearest_neighbors.append (element->data);
while ( !queueTemp->empty() )
{
nearest_neighbors.append ( queueTemp->top()->data );
queueTemp->pop();
}
return CUBIT_SUCCESS;
}
}
return CUBIT_FAILURE;
}
示例6: main
int main()
{
cout << "\n\nLab 12b, PriorityQueueBigOh.cpp\n";
cout << "Programmer: Aysin Oruz \n";
cout << "Editor(s) used: JNotePad and Xcode \n";
cout << "Compiler(s) used: Xcode and Terminal \n";
cout << "Description: The purpose of this lab is for you to learn how to create and apply 12b, PriorityQueueBigOh and get values with BigO().\n";
cout << "File: " << __FILE__ << endl;
cout << "Compiled: " << __DATE__ << " at " << __TIME__ << endl;
const int REPS = 100000; // for timing fast operations, use REPS up to 100th of the starting n
int n = 10000000; // THE STARTING PROBLEM SIZE (MAX 250 MILLION)
string bigOh = "O(log n)"; // YOUR PREDICTION: O(1), O(log n), O(n), O(n log n), or O(n squared)
int elapsedTimeTicksNorm = 0;
double expectedTimeTicks = 0;
cout << "\nEnqueue() O(log n)\n" << endl;
for (int cycle = 0; cycle < 4; cycle++, n*= 2)
{
//Declare PQ
PriorityQueue<int> List;
//Go thru loop to enter values
for (int i = n; i > 0; i--)
List.enqueue(i);
clock_t startTime = clock(); // start the timer
assert(List.getSize() == n);
for(int j = 0; j < REPS; j++ )
List.enqueue(n + j);
assert(List.getSize() == n + REPS);
clock_t endTime = clock(); //stop time
for (int i = 0; i < List.getSize(); i++)
{
int first = List.dequeue();
int second = List.dequeue();
assert(first >= second);
}
// compute timing results
long elapsedTimeTicks = (long)(endTime - startTime);
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;
cout << elapsedTimeTicks;;
if (cycle == 0) cout << " (expected " << bigOh << ')';
else cout << " (expected " << expectedTimeTicks << ')';
cout << " for n = " << n << endl;
}
{
const int REPS = 10000; // for timing fast operations, use REPS up to 100th of the starting n
int n = 1000000; // THE STARTING PROBLEM SIZE (MAX 250 MILLION)
cout << "\nDequeue() O(log n)\n" << endl;
for (int cycle = 0; cycle < 4; cycle++, n*= 2)
{
PriorityQueue<int> List;
for(int i = n; i > 0; i--)
List.enqueue(i);
assert(List.getSize() == n);
//start timing
clock_t startTime = clock();
for(int j = 0; j < REPS; j++)
List.dequeue();
clock_t endTime = clock(); //stop timign
assert(List.getSize() == n - REPS);
for (int i = 0; i < List.getSize(); i++)
{
int first = List.dequeue();
int second = List.dequeue();
assert(first >= second);
}
// compute timing results
long elapsedTimeTicks = (long)(endTime - startTime);
double factor = pow(2.0, cycle);
if (cycle == 0)
elapsedTimeTicksNorm = elapsedTimeTicks;
else if (bigOh == "O(1)")
expectedTimeTicks = elapsedTimeTicksNorm;
//.........这里部分代码省略.........
示例7: main
int main(int argc, char **argv)
{
// using PriorityQueue = pg::heap::Binary<int>;
using PriorityQueue = pg::heap::Pairing<int>;
// using PriorityQueue = StdWrapper<int>;
test("Basic Push/Pop", []()
{
PriorityQueue pq;
pq.Push(10);
pq.Push(5);
pq.Push(8);
pq.Push(12);
pq.Push(1);
pq.Push(90);
pq.Push(9);
assertEquals(1, pq.Pop());
assertEquals(5, pq.Pop());
assertEquals(8, pq.Pop());
assertEquals(9, pq.Pop());
assertEquals(10, pq.Pop());
assertEquals(12, pq.Pop());
assertEquals(90, pq.Pop());
assertEquals(true, pq.Empty());
});
test("Update value", []()
{
PriorityQueue pq;
pq.Push(10);
pq.Push(5);
pq.Push(8);
pq.Push(12);
pq.Push(1);
pq.Push(90);
pq.Push(9);
pq.Update(70, 5);
pq.Update(7, 12);
assertEquals(1, pq.Pop());
assertEquals(7, pq.Pop());
assertEquals(8, pq.Pop());
assertEquals(9, pq.Pop());
assertEquals(10, pq.Pop());
assertEquals(70, pq.Pop());
assertEquals(90, pq.Pop());
assertEquals(true, pq.Empty());
});
test("Performance", []()
{
constexpr auto size = 1000000;
std::default_random_engine random_engine(time(nullptr));
std::uniform_int_distribution<int> distribution(1,9999999);
auto rand = std::bind ( distribution, random_engine );
std::vector<int> test;
PriorityQueue pq;
for(int i = 0 ; i < size; i++)
pq.Push(rand());
while(!pq.Empty())
test.push_back(pq.Pop());
assertEquals(true, std::is_sorted(test.begin(), test.end()));
});
return 0;
}
示例8: main
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
//.........这里部分代码省略.........
示例9: MakeTree
// Builds the tree
TreeNode<SymbolPriority>* MakeTree(const string& message)
{
char currentChar;
vector<SymbolPriority> temp;
PriorityQueue<TreeNode<SymbolPriority>*> myPriorityQueue;
for (int i = 0; i < int(message.size()); i++)
{
currentChar = message[i];
if ( temp.empty() )
temp.push_back( SymbolPriority(currentChar, 1) );
else if ( characterExists(temp, currentChar) )
{
for (int c = 0; c < int (temp.size()); i++)
if (currentChar == temp[i].Symbol)
temp[i].Priority++;
}
else
temp.push_back( SymbolPriority(currentChar, 1) );
}
for (int i = 0; i < int(temp.size()); i++)
{
if (myPriorityQueue.GetSize() <= 1)
myPriorityQueue.Push( new TreeNode<SymbolPriority>( temp[i]) );
else
{
char aChar;
TreeNode<SymbolPriority>* tempNode;
// create a new TreeNode<SymbolPriority>* and
// make the first popped element its left child
// make the second popped element its right child
// set its value to the sum of its left and right child priorities
tempNode->Left = myPriorityQueue.Top();
aChar = myPriorityQueue.Top()->Data.Priority;
myPriorityQueue.Pop();
tempNode->Right = myPriorityQueue.Top();
aChar += myPriorityQueue.Top()->Data.Priority;
myPriorityQueue.Pop();
myPriorityQueue.Push( tempNode );
}
}
return myPriorityQueue.Top();
}
示例10: main
int main()
{
// print my name and this assignment's title
cout << "LAB 11a: Write And Test A Priority Queue Template\n";
cout << "Programmer: Jacky Chow\n";
cout << "Editor(s) used: Notepad++\n";
cout << "Compiler(s) used: Visual C++\n";
cout << "File: " << __FILE__ << endl;
cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl << endl;
PriorityQueue<int> pq;
int temp;
cout << "Created a PriorityQueue<int> named pq\n";
cout << "Its size should be 0. It is: " << pq.size() << endl;
assert(0 == pq.size());
if(pq.empty()) cout << "pq.empty() returned true that it was empty\n";
else cout << "Error: pq.empty() returned false for empty PQ\n";
assert(pq.empty());
cout << "\nEnqueuing the ints 13, 8, 4, 20, 10 into pq\n";
pq.enqueue(13);
pq.enqueue(8);
pq.enqueue(4);
pq.enqueue(20);
pq.enqueue(10);
if(!pq.empty()) cout << "pq.empty() returned false that it was empty\n";
else cout << "Error: pq.empty() returned true for a non-empty PQ\n";
assert(!pq.empty());
cout << "\nIts size should now be 5. It is: " << pq.size() << endl;
assert(5 == pq.size());
cout << "The front should be 20. It is: " << pq.front() << endl;
assert(20 == pq.front());
cout << "The back should be 10. It is: " << pq.back() << endl;
assert(10 == pq.back());
//const copy constructor test
{
cout << "\nCreating const copy with copy constructor\n";
const PriorityQueue<int> copy = pq;
if(!copy.empty()) cout << "copy.empty() returned false that it was empty\n";
else cout << "Error: copy.empty() returned true for a non-empty PQ\n";
assert(!copy.empty());
cout << "Copy size should now be 5. It is: " << copy.size() << endl;
assert(5 == copy.size());
}
//operator= copy test
{
cout << "\nCreating copy with with operator=\n";
PriorityQueue<int> copy;
cout << "Should initially have size 0. It is: " << copy.size() << endl;
assert(copy.empty());
cout << "Assigning copy to = pq\n";
copy = pq;
if(!copy.empty()) cout << "copy.empty() returned false that it was empty\n";
else cout << "Error: copy.empty() returned true for a non-empty copy\n";
assert(!copy.empty());
cout << "Copy 2's size should now be 5. It is: " << copy.size() << endl;
assert(5 == copy.size());
cout << "The front should be 20. It is: " << copy.front() << endl;
assert(20 == copy.front());
cout << "The back should be 10. It is: " << copy.back() << endl;
assert(10 == copy.back());
cout << "Dequeuing the entire copy of pq: \n";
for(; copy.size();)
cout << copy.dequeue() << ' ';
cout << "\nCopy should now be size 0. It is: " << copy.size() << endl;
assert(copy.empty());
if(copy.empty()) cout << "copy.empty() returned true that it was empty\n";
else cout << "Error: copy.empty() returned false for an empty copy\n";
assert(copy.empty());
}
temp = pq.dequeue();
cout << "\nDequeuing root of pq. It should return 20. It is: " << temp << endl;
assert(20 == temp);
cout << "\nIts size should now be 4. It is: " << pq.size() << endl;
assert(4 == pq.size());
cout << "The front should be 13. It is: " << pq.front() << endl;
assert(13 == pq.front());
cout << "The back should be 8. It is: " << pq.back() << endl;
assert(8 == pq.back());
cout << "\nNow using clear to clear pq\n";
pq.clear();
cout << "Size should now be 0. It is: " << pq.size() << endl;
assert(0 == pq.size());
if(pq.empty()) cout << "pq.empty() returned true that it was empty\n";
else cout << "Error: pq.empty() returned false for empty PQ\n";
assert(pq.empty());
}
示例11: singleDefUse
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);
}
}
}
//.........这里部分代码省略.........
示例12: dijkstrasAlgorithm
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;
}
}
示例13: LOG_SETUP
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/log/log.h>
LOG_SETUP("priority_queue_test");
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/vespalib/util/priority_queue.h>
using namespace vespalib;
TEST("require that default priority order works") {
PriorityQueue<int> queue;
EXPECT_EQUAL(true, queue.empty());
EXPECT_EQUAL(0u, queue.size());
queue.push(5);
queue.push(3);
queue.push(7);
queue.push(10);
queue.push(2);
EXPECT_EQUAL(false, queue.empty());
EXPECT_EQUAL(5u, queue.size());
EXPECT_EQUAL(2, queue.front());
queue.front() = 6;
queue.adjust();
EXPECT_EQUAL(3, queue.front());
queue.pop_front();
EXPECT_EQUAL(5, queue.front());
queue.pop_front();
EXPECT_EQUAL(6, queue.front());
queue.pop_front();
EXPECT_EQUAL(7, queue.front());
queue.pop_front();
EXPECT_EQUAL(10, queue.front());
示例14: aStar
//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;
}
}
示例15: UpdateGrid
//.........这里部分代码省略.........
for (size_t i = 0; i < edgesAA.size(); ++i)
{
m_DebugOverlayShortPathLines.push_back(SOverlayLine());
m_DebugOverlayShortPathLines.back().m_Color = CColor(0, 1, 1, 1);
std::vector<float> xz;
xz.push_back(edgesAA[i].p0.X.ToFloat());
xz.push_back(edgesAA[i].p0.Y.ToFloat());
xz.push_back(edgesAA[i].p0.X.ToFloat());
xz.push_back(edgesAA[i].p1.Y.ToFloat());
xz.push_back(edgesAA[i].p1.X.ToFloat());
xz.push_back(edgesAA[i].p1.Y.ToFloat());
xz.push_back(edgesAA[i].p1.X.ToFloat());
xz.push_back(edgesAA[i].p0.Y.ToFloat());
xz.push_back(edgesAA[i].p0.X.ToFloat());
xz.push_back(edgesAA[i].p0.Y.ToFloat());
SimRender::ConstructLineOnGround(GetSimContext(), xz, m_DebugOverlayShortPathLines.back(), true);
}
}
// Do an A* search over the vertex/visibility graph:
// Since we are just measuring Euclidean distance the heuristic is admissible,
// so we never have to re-examine a node once it's been moved to the closed set.
// To save time in common cases, we don't precompute a graph of valid edges between vertexes;
// we do it lazily instead. When the search algorithm reaches a vertex, we examine every other
// vertex and see if we can reach it without hitting any collision edges, and ignore the ones
// we can't reach. Since the algorithm can only reach a vertex once (and then it'll be marked
// as closed), we won't be doing any redundant visibility computations.
PROFILE_START("A*");
PriorityQueue open;
PriorityQueue::Item qiStart = { START_VERTEX_ID, start.h };
open.push(qiStart);
u16 idBest = START_VERTEX_ID;
fixed hBest = start.h;
while (!open.empty())
{
// Move best tile from open to closed
PriorityQueue::Item curr = open.pop();
vertexes[curr.id].status = Vertex::CLOSED;
// If we've reached the destination, stop
if (curr.id == GOAL_VERTEX_ID)
{
idBest = curr.id;
break;
}
// Sort the edges so ones nearer this vertex are checked first by CheckVisibility,
// since they're more likely to block the rays
std::sort(edgesAA.begin(), edgesAA.end(), EdgeSort(vertexes[curr.id].p));
std::vector<EdgeAA> edgesLeft;
std::vector<EdgeAA> edgesRight;
std::vector<EdgeAA> edgesBottom;
std::vector<EdgeAA> edgesTop;
SplitAAEdges(vertexes[curr.id].p, edgesAA, edgesLeft, edgesRight, edgesBottom, edgesTop);
// Check the lines to every other vertex
for (size_t n = 0; n < vertexes.size(); ++n)
{