int main(){
        ios::sync_with_stdio(false);
        ll n, idx = 0, val, rs; cin >> n;
        Node nd; cin >> nd.x >> nd.y;
        val = nd.x, nd.diff = nd.y - nd.x + 1, Score.push_back(nd);
        for (int i = 1; i < n; i++){
                cin >> nd.x >> nd.y;
                nd.diff = nd.y - nd.x + 1;
                if (nd.x > val) idx++;
                Score.push_back(nd);
        }
        rs = idx;
        sort(all(Score), cmp);
        PriorityQueue pq;
        int lstidx = idx + 1;
        for (int i = 0; i < idx; i++){
                pq.add(Score[i].diff);
        }
        while (val >= pq.top()){
                if (!rs || pq.top() == -1) break;
                if (pq.top() <= val){
                        val -= pq.top();
                        pq.remove();
                        idx--;
                }
                while (lstidx < n && Score[lstidx].x > val){
                        pq.add(Score[lstidx].diff);
                        lstidx++;
                        idx++;
                }
                rs = min(rs, idx);
        }
        cout << rs + 1 << ln;
        return 0;
}
Exemplo n.º 2
0
// 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;
}
Exemplo n.º 3
0
	double skipToTs(double ts)
	{
		double ret = -1000000000.0;

		for(int i = 0; i < 100; i++){
			// "tick" the video, filling up the frame queue
			tick(true);
				
			// throw away any frames below the requested time
			double curr = .0;
			while(frameQueue.GetContainer().size() > 0 && (curr = timeFromTs(frameQueue.GetContainer().at(0)->GetPts())) < ts){
				ret = curr;
				frameQueue.GetContainer().erase(frameQueue.GetContainer().begin());
			}

			// done if the frameQueue has a timestamp equal to or larger than the requested time
			if(frameQueue.size() > 0 && timeFromTs(frameQueue.top()->GetPts()) >= ts)
				break;
		}

		if(frameQueue.size() > 0){
			// return the actual timestamp achieved
			ret = timeFromTs(frameQueue.GetContainer().at(0)->GetPts());
			audioHandler->discardQueueUntilTs(ret);
		}
		
		return ret;
	}
// @snip <sh19910711/contest:setlib/disjoints_set.cpp>
template <typename GraphType> const typename std::vector<typename GraphType::Edge> get_minimum_spanning_forest( const GraphType& G ) {
  typedef typename std::vector<typename GraphType::Edge> Edges;
  typedef typename GraphType::Edge GraphEdge;
  typedef typename GraphType::Edges GraphEdges;
  typedef std::priority_queue<GraphEdge, Edges, std::greater<GraphEdge> > PriorityQueue;
  typedef setlib::DisjointSets UnionFind;

  Edges res;
  PriorityQueue E;
  UnionFind uf(G.num_vertices);

  for ( int i = 0; i < G.num_vertices; ++ i ) {
    for ( typename GraphEdges::const_iterator it_i = G.vertex_edges[i].begin(); it_i != G.vertex_edges[i].end(); ++ it_i ) {
      const GraphEdge& e = **it_i;
      E.push(GraphEdge(e.from, e.to, e.weight));
    }
  }

  while ( ! E.empty() ) {
    GraphEdge e = E.top();
    E.pop();
    if ( ! uf.same(e.from, e.to) ) {
      res.push_back(e);
      uf.merge(e.from, e.to);
    }
  }

  return res;
}
Exemplo n.º 5
0
void dumpContents( const string & msg, PriorityQueue & pq )
{
    cout << msg << ":" << endl;
    while( !pq.empty( ) )
    {
        cout << pq.top( ) << endl;
        pq.pop( );
    }
}
int main(){
  PriorityQueue<int> pq;
  for(int i=0;i<10;i++){
    pq.push(i);
  }
  while(!pq.empty()){
    cout<<pq.top()<<" ";
    pq.pop();
  }
}
Exemplo n.º 7
0
	FramePtr fetchFrame()
	{
		bool wasStepIntoQueue = stepIntoQueue;

		if(frameQueue.empty() && IsEof() && !reportedEof)
		{
			reportedEof = true;
			messageCallback(MEof, "eof");
		}

		if(stepIntoQueue && !frameQueue.empty())
		{
			stepIntoQueue = false;
			timeHandler->SetTime(timeFromTs(frameQueue.top()->GetPts()) + .001);
			audioHandler->discardQueueUntilTs(timeHandler->GetTime());
		}

		double time = timeHandler->GetTime();

		FramePtr newFrame = 0;

		// Throw away all old frames (timestamp older than now) except for the last
		// and set the pFrame pointer to that.
		int poppedFrames = 0;

		while(!frameQueue.empty() && timeFromTs(frameQueue.top()->GetPts()) < time)
		{
			newFrame = frameQueue.top();
			frameQueue.pop();
			poppedFrames++;
		}
			
		if(poppedFrames > 1){
			FlogD("skipped " << poppedFrames - 1 << " frames");
		}

		if(newFrame != 0 && (newFrame->GetPts() >= time || wasStepIntoQueue))
			return newFrame;

		return 0;
	}
Exemplo n.º 8
0
inline
void inpainting_loop(VertexListGraph& g, InpaintingVisitorType vis,
                      BoundaryStatusMap& boundaryStatusMap, PriorityQueue& boundaryNodeQueue,
                      NearestNeighborFinder find_inpainting_source, 
                      PatchInpainter inpaint_patch) 
{
  typedef typename boost::graph_traits<VertexListGraph>::vertex_descriptor Vertex;
  typedef typename boost::graph_traits<VertexListGraph>::edge_descriptor Edge;
  typedef typename boost::property_traits<PositionMap>::value_type PositionValueType;
  
  // When this function is called, the priority-queue should already be filled 
  // with all the hole-vertices (which should also have "Color::black()" color value).
  // So, the only thing this function does is run the inpainting loop. All of the
  // actual code is externalized in the functors and visitors (vis, find_inpainting_source, inpaint_patches, etc.).

  while(true) 
  {
    // find the next target to in-paint:
    Vertex targetNode;
    do
    {
      if( boundaryNodeQueue.empty() )
      {
        std::cout << "Queue is empty, exiting." << std::endl;
        return;  //terminate if the queue is empty.
      }
      targetNode = boundaryNodeQueue.top();
      boundaryNodeQueue.pop();
    } while( get(boundaryStatusMap, targetNode) == false );

    // Notify the visitor that we have a hole target center.
    vis.discover_vertex(targetNode, g);

    // next, we want to find a source patch-center that matches best to our target-patch:
    Vertex source_patch_center = find_inpainting_source(targetNode);
    vis.vertex_match_made(targetNode, source_patch_center, g);

    // finally, do the in-painting of the target patch from the source patch.
    //  the inpaint_patch functor should take care of iterating through the vertices in both
    //  patches and call "vis.paint_vertex(target, source, g)" on the individual vertices.
    inpaint_patch(targetNode, source_patch_center, g, vis);

    if(!vis.accept_painted_vertex(targetNode, g))
      {
      throw std::runtime_error("Vertex was not painted successfully!");
      }

    vis.finish_vertex(targetNode, g);
  } // end main iteration loop
  
};
Exemplo n.º 9
0
	Node getNode(char name){
		if (find(name)){
			PriorityQueue tempQueue;
			while (top().name != name){
				tempQueue.push(top());
				pop();
			}
			Node node = top();
			while (!tempQueue.empty()){
				push(tempQueue.top());
				tempQueue.pop();
			}
			return node;
		}
	}
Exemplo n.º 10
0
// 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;
}
Exemplo n.º 11
0
static bool A_star(DGR& dg, Weight& w, Digraph::Node s, Digraph::Node t, int k, DistMap& dist, PredMap& pred)
{
    if(s == t) return false;

	typedef QNode Node;
    typedef std::vector<QNode> NodeCon;
    typedef std::priority_queue<Node,NodeCon> PriorityQueue;
    PriorityQueue pq;

    int cnt = 0;
    pred[s] = INVALID;
	pq.push(Node(s, INVALID, 0, dist[s]));
    while(!pq.empty())
    {
		Node node = pq.top();
		Digraph::Node u = node.u;
		pred[u] = node.parent;
		//cout<<"->pop:f("<<Digraph::id(u)<<")="<<node.g+p.h
		//	  <<"\tg("<<Digraph::id(u)<<")="<<node.g
		//	  <<"\th("<<Digraph::id(u)<<")="<<node.h
		//	  <<endl;
        pq.pop();
        if(u == t)
        {
			//cout<<"---------------------"<<endl;
            cnt++;
        }
        if(cnt == k)
        {
            break;
        }
        for(typename DGR::OutArcIt e(dg,u);e!=INVALID;++e)
        {
            Digraph::Node v = dg.target(e);
            pred[v] = u;
			Node child_node(v, u, node.g + w[e], dist[v]);
			//cout<<"\t->push:f("<<Digraph::id(v)<<")="<<child_node.g+child_node.h
				//<<"\tg("<<Digraph::id(v)<<")="<<child_node.g
				//<<"\th("<<Digraph::id(v)<<")="<<child_node.h
				//<<endl;
			pq.push(child_node);
        }
    }
    return (cnt == k);
}
Exemplo n.º 12
0
// Return a list<Edge> containing the list of edges in the minimum spanning tree found by Prim's Algorithm
list<Edge> PrimMST::tree() {
  list<Edge> mst;
  PriorityQueue<Edge> p;
  Node selected;
  Edge selectedEdge;
  
  // Create selectedNodes empty set
  // Create candidateNodes set containing all nodes
  list<Node> selectedNodes;
  list<Node> candidateNodes = graph.vertices();

  while (!candidateNodes.empty()) {
    // Add first node from candidateNodes set to selectedNodes set and remove it from candidateNodes
    selected = candidateNodes.front();
    selectedNodes.push_back(selected);
    candidateNodes.remove(selected);
    
    // Insert all edges from first node into priority queue
    list<Node> sEdges = graph.neighbors(selected.getNodeNumber());
    for(list<Node>::iterator j=sEdges.begin(); j != sEdges.end(); ++j) {
      Edge e(selected.getNodeNumber(),(*j).getNodeNumber(),(*j).getEdgeWeight());
      p.insert(e);
    }

    while(p.size() != 0) {
      selectedEdge = p.top();	// Remove the lower edge from the priority queue
      if ((isSrcInSet(selectedEdge,selectedNodes)) && (isDstInSet(selectedEdge,candidateNodes))) {
	mst.push_back(selectedEdge);
	// Add selected node to selectedNodes set and remove it from candidateNodes set
	selected = getNodeInSet(selectedEdge.getDst(),candidateNodes);
	selectedNodes.push_back(selected);
	candidateNodes.remove(selected);
	// Insert all edges from dst node into priority queue
	sEdges = graph.neighbors(selected.getNodeNumber());
	for(list<Node>::iterator j=sEdges.begin(); j != sEdges.end(); ++j) {
	  Edge e(selected.getNodeNumber(),(*j).getNodeNumber(),(*j).getEdgeWeight());
	  p.insert(e);
	}
      } 
    }
  }
     
  return mst;
}
Exemplo n.º 13
0
	void adjustTime(){
		// Checks so that the current time doesn't diff too much from the decoded frames.
		// If it does the stream probably jumped ahead or back, so current time needs to 
		// be adjusted accordingly.

		if(frameQueue.empty())
			return;

		double time = timeHandler->GetTime();
		double pts = timeFromTs(frameQueue.top()->GetPts());

		// If the next frame is far into the future or the past, 
		// set the time to now

		if(pts > time + 100.0 || pts < time - 100.0){
			FlogD("adjusted time");
			timeHandler->SetTime(pts);
		}
	}
Exemplo n.º 14
0
inline void sweep(Range const& range, PriorityQueue& queue,
                  InitializationVisitor& initialization_visitor,
                  EventVisitor& event_visitor,
                  InterruptPolicy const& interrupt_policy)
{
    typedef typename PriorityQueue::value_type event_type;

    initialization_visitor.apply(range, queue, event_visitor);
    while (! queue.empty())
    {
        event_type event = queue.top();
        queue.pop();
        event_visitor.apply(event, queue);
        if (interrupt_policy.enabled && interrupt_policy.apply(event))
        {
            break;
        }
    }

    geofeatures_boost::ignore_unused(interrupt_policy);
}
Exemplo n.º 15
0
	void													myerase(Node val)
	{
		PriorityQueue <Node, std::vector<Node>, Compare>	tmp;

		while (this->c.size() > 0)
		{
			auto											first = this->c.begin();
			if (first->getTab() == val.getTab())
			{
				this->pop();
				break;
			}
			tmp.push(*first);
			this->pop();
		}
		while (tmp.size() > 0)
		{
			this->push(tmp.top());
			tmp.pop();
		}
	}
Exemplo n.º 16
0
// 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);
            }
        }
    }
}
Exemplo n.º 17
0
void Prim::mst(int root,Color color){
	Q.clear();
	int size=G->V();  // number of vertices
	for(int i=0;i<size;i++){
		dist[i]=1000.0;
		edges[i]=NO_EDGE;
		if(G->get_node_value(i)==color){  // only choose the same color
		    	//dist[i]=INF;    // equal to infinite
			//cout<<"insert node!"<<i<<" and dist is "<<dist[i]<<endl;
		Q.Insert(Type_Queue_Element (i,dist[i]));  // assign V[G] to Q
		}
	}
	dist[root]=0.0;
	if(!Q.contains(root)) cout<<"not include root !!"<<endl;
	else {
		Q.chgPrioirity(root,dist[root]);   //dist[i] and priority value in priority queue must be synchronized
		edges[root]=ROOT_EDGE;
		while(!Q.empty()){
			Type_Queue_Element currElement=Q.top();
            Q.minPrioirty();  // remove from priority queue
			int currNode=currElement.first;
			if(edges[currNode]!=NO_EDGE){
				dist[currNode]=currElement.second;
				vector<int> neibs=G->neighbors(currNode,color);
				for(unsigned int i=0;i<neibs.size();i++){
					if(Q.contains(neibs[i]) && (G->get_edge_value(neibs[i],currNode)<dist[neibs[i]]) ){
						edges[neibs[i]]=currNode;
						dist[neibs[i]]=G->get_edge_value(neibs[i],currNode);
						Q.chgPrioirity(neibs[i],dist[neibs[i]]);
					}
				}
			}

		}
	}
}
Exemplo n.º 18
0
	void decreaseKey(char node, int newKey, char newPi){
		cout << "decreaseKey(" << node << ", " << newKey << ", " << newPi << endl;
		if (find(node)){
			cout << "found" << endl;
			PriorityQueue tempQueue;
			while (top().name != node){
				cout << "popping out" << endl;
				tempQueue.push(top());
				pop();
			}
			Node node = top();
			cout << "orig: " << node.name << ", " << node.pi << ", " << node.key << endl;
			pop();
			node.key = newKey;
			node.pi = newPi;
			push(node);
			while (!tempQueue.empty()){
				cout << "pushing back" << endl;
				push(tempQueue.top());
				tempQueue.pop();
			}
		}
		cout << "leaving" << endl;
	}
bool Hex<T>::shortest_path(T source, T target, player_t player)
{
	PriorityQueue<T,T> priorityQueue;
	// Apart from board positions, we also add source and target in the priority queue.
	// source & target: These are virtual home and goal.

	//Initialize cost of vertices as infinite except the source vertex
	for (T vtx_i = 0; vtx_i != graph_.nVertex(); ++vtx_i)
	{
		vecVisited_[vtx_i] = false;
		if (vtx_i == source)
		{
			vecCost_[vtx_i] = 0;
			priorityQueue.insert_element(vtx_i,0);
		} 
		else
		{
			vecCost_[vtx_i] = std::numeric_limits<T>::max();

			if ( ( is_pos_on_board(vtx_i) && (board_.position_player(vtx_i) == player) ) ||
				(vtx_i == target) )
			{
				priorityQueue.insert_element(vtx_i,std::numeric_limits<T>::max());
			}
		}
	}

	bool reachedTarget = false;
	while (!priorityQueue.empty())
	{
		std::pair<T,T> topElem = priorityQueue.top();
		T vtxTop = topElem.first;
		T costTop = topElem.second;
		vecVisited_[vtxTop] = true;
		priorityQueue.remove_element(vtxTop,costTop);

		if (costTop == std::numeric_limits<T>::max())
		{
			break; // reaching here means path from source to target is not present
		}
		if (vtxTop == target)
		{
			reachedTarget = true;
			break;
		}

		std::vector<T> neighbors = graph_.neighbors(vtxTop);
		for (std::vector<T>::iterator it = neighbors.begin(); it != neighbors.end(); ++it)
		{
			if (vecVisited_[*it])
			{
				continue;
			}
			// For a board position consider this neighbor only if the current player has placed
			// his/her hex on this position.
			
			if (is_pos_on_board(*it))
			{
				if (board_.position_player(*it) != player)
				{
					continue;
				}
			}
			else if ((*it) != target)
			{
				continue;
			}

			T newCost = vecCost_[vtxTop] + 1;
			if (newCost < vecCost_[*it])
			{
				priorityQueue.change_priority(*it,vecCost_[*it],newCost);
				vecCost_[*it] = newCost;
			}
		}
	}

	return reachedTarget;
}
Exemplo n.º 20
0
//- "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;
}