当前位置: 首页>>代码示例>>C++>>正文


C++ PriorityQueue::insert方法代码示例

本文整理汇总了C++中PriorityQueue::insert方法的典型用法代码示例。如果您正苦于以下问题:C++ PriorityQueue::insert方法的具体用法?C++ PriorityQueue::insert怎么用?C++ PriorityQueue::insert使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PriorityQueue的用法示例。


在下文中一共展示了PriorityQueue::insert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: assignRandomNeighbors

///Assign random number to modify the priority of neighbors counter
///@param queue is a priority queue stores the number of neighbors for each empty cell of current game
///@param counter is a vector stores pair of index value of empty cells and count of neighbors
///@return NONE
void Strategy::assignRandomNeighbors(PriorityQueue<int, int>& queue,
                                     vector<pair<int, int> >& counter,
                                     int currentempty) {

  long long seed =
      hexgame::chrono::system_clock::now().time_since_epoch().count();
//TODO refactor to have consistent codes for C++11 and < C++11
#if __cplusplus > 199711L
  default_random_engine generator(seed);
#else
  boost::mt19937 generator(static_cast<unsigned>(seed));
  srand(static_cast<unsigned>(seed));
#endif

  //ensure assign unique number
  vector<int> numbers(currentempty);
  for (int i = 0; i < currentempty; i++)
    numbers[i] = (i + 1);
#if __cplusplus > 199711L
  shuffle(numbers.begin(), numbers.end(), generator);
#else
  std::random_shuffle(numbers.begin(), numbers.end());
#endif
  hexgame::uniform_real_distribution<float> probability(0.0, 1.0);
  for (int i = 0; i < currentempty; i++) {
    float prob = probability(generator);
    //if randomness = 1, then doing shuffle
    int weight = static_cast<int>((counter[i].second) * (1.0 - randomness));
    if (prob <= randomness)
      queue.insert(counter[i].first, -(weight + numbers[i]));
    else
      queue.insert(counter[i].first, -weight);
  }
}
开发者ID:renewang,项目名称:HexGame,代码行数:38,代码来源:Strategy.cpp

示例2: insert_edge_to_heap

void insert_edge_to_heap(int v, EdgeNode *p){
	edgepair *ep = new edgepair;
	ep->x = v;
	ep->y = p->y;
	ep->weight = p->weight;
	min_heap.insert(ep);
}
开发者ID:avanishgiri,项目名称:Algorithms,代码行数:7,代码来源:graph.cpp

示例3: e

// Return a list<Edge> containing the list of edges in the minimum spanning tree found by Kruskal's Algorithm
list<Edge> KruskalMST::tree() {
  list<Edge> mst;
  PriorityQueue<Edge> p;
  Node selected;
  Edge selectedEdge;
  
  // Add each node of the graph to its own set
  list<Node> allNodes = graph.vertices();  
  for(list<Node>::iterator i=allNodes.begin(); i != allNodes.end(); ++i)
    makeSet(*i);
  
  // Insert all edges from the graph into priority queue
  for(list<Node>::iterator i=allNodes.begin(); i != allNodes.end(); ++i) {
    list<Node> iEdges = graph.neighbors((*i).getNodeNumber());
    for(list<Node>::iterator j=iEdges.begin(); j != iEdges.end(); ++j) {
      Edge e((*i).getNodeNumber(),(*j).getNodeNumber(),(*j).getEdgeWeight());
      p.insert(e);
    }
  }
 
  while(p.size() != 0) {
    selectedEdge = p.top();	// Remove the lower edge from the priority queue
    if (findSet(selectedEdge.getSrc()) != findSet(selectedEdge.getDst())) {
      mst.push_back(selectedEdge);	// If src and dst are in different sets, then add this edge to mst
      combineSet(selectedEdge.getSrc(),selectedEdge.getDst());	// Combine both sets into one
    } 
  }
     
  return mst;
}
开发者ID:,项目名称:,代码行数:31,代码来源:

示例4: getOptimalPath

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;
}
开发者ID:uzipaz,项目名称:AStarPathFinding,代码行数:47,代码来源:main.cpp

示例5: PriorityQueue

TEST(Solution, TwoSamePrioString) {
    PriorityQueue pq = PriorityQueue();
    std::string x = "xxx";
    std::string w = "www";
    std::string y = "yyy";

    pq.insert(20, x);
    pq.insert(20, w);
    pq.insert(10, y);

    std::string call1 = pq.next();
    EXPECT_TRUE(call1 == w || call1 == x);
    std::string call2 = pq.next();
    EXPECT_TRUE(call2 == w || call2 == x);
    // How to handle when there are no elements? EXPECT_TRUE(NULL == pq.next());
    EXPECT_EQ(y, pq.next());
}
开发者ID:skarab7,项目名称:Programming-Kata---Playground,代码行数:17,代码来源:solution_unittest.cpp

示例6:

TEST(QueueTest, PrioritySortTest)
{
    // Check that inserting several nodes sorts them
    // in order of f (g+h)
    PriorityQueue queue;
    Node n1(0,1,4,5,false), n2(1,2,4,3,false),
         n3(2,1,3,6,false), n4(1,0,4,7,false);
    queue.insert(&n1);
    queue.insert(&n2);
    queue.insert(&n3);
    queue.insert(&n4);
    // Order should be n2,n3,n1,n4
    ASSERT_EQ(&n2, queue.removeFront());
    ASSERT_EQ(&n3, queue.removeFront());
    ASSERT_EQ(&n1, queue.removeFront());
    ASSERT_EQ(&n4, queue.removeFront());
}
开发者ID:NevilleS,项目名称:astar,代码行数:17,代码来源:QueueTest.cpp

示例7: search

    Node<Plot>* search(std::map<Plot*, std::vector<Plot*> >& path, Plot& start, Plot& goal)
    {
        Node<Plot>* node_goal = new Node<Plot>(goal);
        Node<Plot>* node_start = new Node<Plot>(start);

        PriorityQueue queue;
        std::unordered_map<Plot*, int> closeList;
        queue.insert(node_start);
        int iter = 0;

        while (!queue.empty())
        {
            iter++;
            Node<Plot> *current(*(queue.begin()));
            queue.erase(queue.begin());

            std::vector<Plot*>& neighbours(path[current->node]);
            for (Plot *p : neighbours)
            {

                Node<Plot>* next = new Node<Plot>(*p);
                next->g = current->g + manhattan_distance(current->node, p);
                next->h = manhattan_distance(p, &goal);
                next->f = next->g + next->h;
                next->x = current->x + 1; // nb turns

                next->parent = current;

                if (p == node_goal->node)
                {
                    std::cout << "nbIter: " << iter << std::endl;
                    return next;
                }

                if (isWorthTrying(next, queue, closeList))
                {
                    queue.insert(next);
                }
            }
            closeList[current->node] = current->f;
            delete current;
        }
        return nullptr;
    }
开发者ID:hutamaki,项目名称:cg,代码行数:44,代码来源:main.cpp

示例8: main

int main() {
	string op;

	int idx = 0;
	PriorityQueue <int> h;
	while (cin >> op) {
		if (op == "push") {
			int v;
			cin >> v;
			h.insert(idx, v);
		} else if (op == "extract-min") {
开发者ID:zakharvoit,项目名称:discrete-math-labs,代码行数:11,代码来源:PriorityQueue.cpp

示例9: testPriorityQueue

void testPriorityQueue() {
    cout << "PriorityQueue => ";
    PriorityQueue* q = new PriorityQueue();
    CharString* cc = new CharString("[email protected]#$%^*()_+1234567890",24);
    q->insert(0,cc);
    CharString* qq = (CharString*)q->removeMin();
    if(qq == cc) {
        cout << "Pass" << endl;
    } else {
        cout << "Fail" << "(" << qq->get() << ")" << endl;
    }
}
开发者ID:,项目名称:,代码行数:12,代码来源:

示例10: while

// Return a list<char> containing the list of nodes in the shortest path between 'u' and 'w'
list<char> ShortestPath::path(char u, char w)
{
  // Initialize candidates list with all nodes
  list<char> candidates = graph.vertices(), desiredPath;
  list<NodeInfo> minPaths;
  PriorityQueue p;
  NodeInfo lastSelected, n;
     
  // Calculate shortest path from 'u' to 'w' (Dijkstra's Algorithm)
  candidates.remove(u);			// Remove 'u' from candidates list
  lastSelected.nodeName = u;		// Set 'u' as lastSelected
  lastSelected.minDist = 0;
  lastSelected.through = u;
  minPaths.push_back(lastSelected);	// Add 'u' to minPath list
  while ((!candidates.empty()) && (lastSelected.nodeName !=w))
  {
    // For each node in candidate list calculate the cost to reach that candidate through lastSelected 
    for(list<char>::iterator i=candidates.begin(); i != candidates.end(); ++i)
    {
      n.nodeName=*i;
      n.minDist=lastSelected.minDist+graph.get_edge_value(lastSelected.nodeName,*i);
      n.through=lastSelected.nodeName;
      if (!p.contains(n))	// Add candidate to priority queue if doesn't exist 
	p.insert(n);
      else
	if (p.isBetter(n))	// Update candidate minDist in priority queue if a better path was found
	  p.chgPriority(n);
    }
    lastSelected = p.top();			// Select the candidate with minDist from priority queue
    p.minPriority();				// Remove it from the priority queue
    minPaths.push_back(lastSelected);		// Add the candidate with min distance to minPath list
    candidates.remove(lastSelected.nodeName);	// Remove it from candidates list
  }
  
  // Go backward from 'w' to 'u' adding nodes in that path to desiredPath list
  lastSelected=minPaths.back();
  desiredPath.push_front(lastSelected.nodeName);
  while(lastSelected.nodeName!=u)
  {
    for(list<NodeInfo>::iterator i=minPaths.begin(); i != minPaths.end(); ++i)
      if ((*i).nodeName==lastSelected.through)
      {
	lastSelected=(*i);
	desiredPath.push_front(lastSelected.nodeName);
      }
  }
  return desiredPath;
}
开发者ID:,项目名称:,代码行数:49,代码来源:

示例11: run

// Run a simulation finding the Prim's and Kruskal's MST in a given graph 
void MonteCarlo::run(Graph g)
{
  static int turn=0;
  
  cout << endl << "=== RUNNING SIMULATION No. " << ++turn << " ===" << endl;
  
  // Print out graph information
  double d = static_cast<double>(g.E())/((static_cast<double>(g.V())*static_cast<double>(g.V())-1)/2)*100;	// Calculate real density reached
  cout << "Vertices: " << g.V() << endl;
  cout << "Edges: " << g.E() << " (density: " << d << "%)" << endl;
  cout << "Nodes: " << g.vertices() << endl;
  cout << "Graph: " << g << endl;
  cout << "Graph (.dot format): " << endl;
  cout << "graph Homework3 {" << endl;
  // Insert all edges from the graph into priority queue
  list<Node> allNodes = g.vertices(); 
  PriorityQueue<Edge> p;
  for(list<Node>::iterator i=allNodes.begin(); i != allNodes.end(); ++i) {
    list<Node> iEdges = g.neighbors((*i).getNodeNumber());
    for(list<Node>::iterator j=iEdges.begin(); j != iEdges.end(); ++j) {
      Edge e((*i).getNodeNumber(),(*j).getNodeNumber(),(*j).getEdgeWeight());
      p.insert(e);
    }
  }
  cout << p;
  cout << "}" << endl;
  
  PrimMST prim(g);
  cout << "Prim MST (.dot format): " << endl;
  cout << "graph PrimMST {" << endl;
  cout << prim.tree();
  cout << "}" << endl;
  cout << "Prim MST cost: " << prim.cost() << endl;
  cout << endl;

  KruskalMST kruskal(g);
  cout << "Kruskal MST (.dot format): " << endl;
  cout << "graph KruskalMST {" << endl;
  cout << kruskal.tree();
  cout << "}" << endl;
  cout << "Kruskal MST cost: " << kruskal.cost() << endl;
}
开发者ID:,项目名称:,代码行数:43,代码来源:

示例12: testMinHeap

//--------------------------------------------------------------------------------------------------
	void testMinHeap()
	{
		PriorityQueue *minHeap = new MinHeap();
		minHeap->insert(22);
		minHeap->insert(8);
		minHeap->insert(50);
		minHeap->insert(3);
		minHeap->insert(2);
		minHeap->insert(30);
		minHeap->insert(100);
		minHeap->display();
		cout << "Minimum value is - " << (dynamic_cast<MinHeap *>(minHeap))->getMin() << endl;
		cout << "Now I am deleting max value" << endl;
		(dynamic_cast<MinHeap *>(minHeap))->deleteMin();
		minHeap->display();
	}
开发者ID:KunjeshBaghel,项目名称:DS,代码行数:17,代码来源:ArrayImplTest.cpp

示例13: DijkstraDistances

// DESC: Dijkstra's algorithm to find shortest distance from source to destination on a graph.
// INPUT: Graph to expand on, Vertex to represent as the source.
// OUTPUT: Linked list of the path
LinkedListT* DijkstraDistances(Graph* graph, Vertex* source) {
    // form a cloud to every point.
    // Store this cloud in the PQueue.
    LinkedListT* verticies = graph->verticies();
    PriorityQueue* pq = new PriorityQueue();

    // loop through verticies
    for(int i=0; i<verticies->size(); i++) {
        Vertex* vv = (Vertex*)verticies->get(i);
        if(vv == source) {
            vv->distance = 0; // set vertex to zero if it is the source vertex.
        } else {
            vv->distance = 999999999; // set verticies to infinity to represent an unreachable location.
        }

        // insert into queue.
        pq->insert(vv->distance,vv);
    }

    // empty out the set
    while(!pq->empty()) {
        // remove the minimum distance from the set. (usually source vertex on start)
        Vertex* v = (Vertex*)pq->removeMin();
        LinkedListT* vt = v->incidentEdges;

        // loop through incident Edges
        for(int i=0; i<vt->size(); i++) {
            Edge* e = (Edge*)vt->get(i);
            Vertex* v2 = e->opposite(v);
            int r = v->distance + e->data;

            // if the total range is less than v2's distance, then set it.
            if(r < v2->distance) {
                v2->distance = r;
                pq->replaceKey(pq->top(),(void*)v2,r);
            }
        }
    }
}
开发者ID:,项目名称:,代码行数:42,代码来源:

示例14: 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);
                }
            }
        }

//.........这里部分代码省略.........
开发者ID:ThisIsNotOfficialCodeItsJustForks,项目名称:PEBIL,代码行数:101,代码来源:FlowGraph.C

示例15: main


//.........这里部分代码省略.........
        case DISTANCE_VISUALIZATION:
            generate_distance_field();
        case COST_VISUALIZATION:
            viewer.data.set_colors(colors);
            break;
        case SOLID:
            viewer.data.set_colors(RowVector3d(1.0, 1.0, 1.0));
            break;
        }
        viewer.data.set_face_based(false);
    };

    // Function to reset original mesh and data structures
    const auto &reset = [&]() {
        total_decimations = 0;
        mods.clear();
        iters.clear();
        F = OF;
        V = OV;
        igl::edge_flaps(F, E, EMAP, EF, EI);
        Qit.resize(E.rows());

        C.resize(E.rows(), V.cols());
        colors.resize(V.rows(), 3);
        colors.setZero();
        VectorXd costs(V.rows());
        costs.setZero();
        for (int e = 0; e < E.rows(); e++) {
            double cost = e;
            RowVectorXd p(1, 3);

            shortest_edge_and_midpoint(e, V, F, E, EMAP, EF, EI, cost, p);
            C.row(e) = p;
            Qit[e] = Q.insert(std::pair<double, int>(cost, e)).first;
            costs(E(e, 0)) += cost;
            costs(E(e, 1)) += cost;
        }
        igl::jet(costs, true, colors);
        num_collapsed = 0;
        reset_view();
    };

    const auto &collapse_edges = [&](igl::viewer::Viewer &viewer) -> bool {
        // If animating then collapse 10% of edges
        if (viewer.core.is_animating && !Q.empty()) {
            bool something_collapsed = false;
            // collapse edge
            const int num_iters = 50;

            // Store the state from before the collapse so that it can be
            // reversed later.
            MatrixXd prev_V = V;
            MatrixXi prev_F = F;
            MatrixXi prev_E = E;
            num_collapsed = 0;

            int total_failures = 0; // If a certain number of failures have
                                    // occurred, we exit an infinte fail loop.

            for (int j = 0; j < num_iters; j++) {
                int e, e1, e2, f1, f2;
                std::vector<int> faceInd, vertInd;

                if (Q.empty())
                    break;
开发者ID:nwoeanhinnogaehr,项目名称:cmput414,代码行数:66,代码来源:main.cpp


注:本文中的PriorityQueue::insert方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。