Example #1
0
void dijkstra() {
	std::fill(d + 1, d + n + 1, INF);
	for (int i = 1; i <= n; i++) {
		if (!w[i]) continue;
		heap.push((Heapnode){d[i] = 0, i});
	}
	while (!heap.empty()) {
		Heapnode top = heap.top(); heap.pop();
		if (v[top.node]) continue;
		v[top.node] = true;
		for (int i = h[top.node]; i; i = e[i].next)
			if (!v[e[i].node] && d[e[i].node] > top.dist + e[i].dist) {
				d[e[i].node] = top.dist + e[i].dist;
				p[e[i].node] = top.node;
				heap.push((Heapnode){d[e[i].node], e[i].node});
			}
	}
	s = 0;
	for (int i = 1, cnt = 0; i <= n; i++) {
		if (!w[i]) continue;
		c[i] = ++s;
	}
	for (int i = 1; i <= n; i++) {
		if (w[i]) continue;
		fa[getfa(i)] = getfa(p[i]);
	}
	for (int i = 1; i <= n; i++) {
		if (w[i]) continue;
		c[i] = c[getfa(i)];
	}
}
Example #2
0
// -------------------------------------------------------------------------
void GraphDefinition::explore(
    int cur_node,
    GraphEdgeInfo& cur_edge,
    bool isStart,
    LongVector &vecIndex,
    std::priority_queue<PDP, std::vector<PDP>,
    std::greater<PDP> > &que)
{
    unsigned int i;
    double extCost = 0.0;
    GraphEdgeInfo* new_edge;
    // int new_node;
    double totalCost;
    for(i = 0; i < vecIndex.size(); i++)
    {
        new_edge = m_vecEdgeVector[vecIndex[i]];
        extCost = 0.0;
        if(m_bIsturnRestrictOn)
        {
            extCost = getRestrictionCost(cur_edge.m_lEdgeIndex, *new_edge, isStart);
        }
        if(new_edge->m_lStartNode == cur_node)
        {
            if(new_edge->m_dCost >= 0.0)
            {
                //new_node = new_edge->m_lEndNode;
                
                if(isStart)
                    totalCost = m_dCost[cur_edge.m_lEdgeIndex].endCost + new_edge->m_dCost + extCost;
                else
                    totalCost = m_dCost[cur_edge.m_lEdgeIndex].startCost + new_edge->m_dCost + extCost;
                if(totalCost < m_dCost[vecIndex[i]].endCost)
                {
                    m_dCost[vecIndex[i]].endCost = totalCost;
                    parent[new_edge->m_lEdgeIndex].v_pos[0] = (isStart?0:1);
                    parent[new_edge->m_lEdgeIndex].ed_ind[0] = cur_edge.m_lEdgeIndex;
                    que.push(std::make_pair(totalCost, std::make_pair(new_edge->m_lEdgeIndex, true)));
                }
            }
        }
        else
        {
            if(new_edge->m_dReverseCost >= 0.0)
            {
                // new_node = new_edge->m_lStartNode;
                if(isStart)
                    totalCost = m_dCost[cur_edge.m_lEdgeIndex].endCost + new_edge->m_dReverseCost + extCost;
                else
                    totalCost = m_dCost[cur_edge.m_lEdgeIndex].startCost + new_edge->m_dReverseCost + extCost;
                if(totalCost < m_dCost[vecIndex[i]].startCost)
                {
                    m_dCost[vecIndex[i]].startCost = totalCost;
                    parent[new_edge->m_lEdgeIndex].v_pos[1] = (isStart?0:1);
                    parent[new_edge->m_lEdgeIndex].ed_ind[1] = cur_edge.m_lEdgeIndex;
                    que.push(std::make_pair(totalCost, std::make_pair(new_edge->m_lEdgeIndex, false)));
                }
            }
        }
    }
}
Example #3
0
int main() {
	freopen("F.in", "r", stdin);
	while (scanf("%d%d", &n, &m) == 2 && n && m) {
		for (int i = 1; i <= n; i++) {
			scanf("%s", map[i] + 1);
		}
		scanf("%d%d", &sx, &sy);
		scanf("%d%d", &ex, &ey);
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= m; j++) {
				v[i][j] = false;
				d[i][j] = INF;
			}
		heap.push(std::make_pair(d[sx][sy] = 0, std::make_pair(sx, sy)));
		while (!heap.empty()) {
			std::pair<int, std::pair<int, int> > top = heap.top(); heap.pop();
			if (v[top.second.first][top.second.second]) continue;
			v[top.second.first][top.second.second] = true;
			for (int dir = 0; dir < 4; dir++) {
				int nx = top.second.first + dx[dir];
				int ny = top.second.second + dy[dir];
				if (nx < 1 || nx > n || ny < 1 || ny > m) continue;
				int cost = map[nx][ny] == '.';
				if (!v[nx][ny] && d[nx][ny] > d[top.second.first][top.second.second] + cost) {
					d[nx][ny] = d[top.second.first][top.second.second] + cost;
					heap.push(std::make_pair(d[nx][ny], std::make_pair(nx, ny)));
				}
			}
		}
		printf("%d\n", d[ex][ey]);
	}
	return 0;
}
Example #4
0
int main(void)
{
	scanf("%u %u", &words, &maxLength);
	for(unsigned int w = 0; w < words; ++ w)
	{
		scanf("%s", word);
		sWord[w] = std::string(word);
		que.push(sWord[w]);
	}

	while(!que.empty() && que.top().length() <= maxLength)
	{
		act = que.top();
		que.pop();
		if(isPalindrome(act))
		{
			++ result;
			if(result == 835454957)
				result = 0;
		}

		for(unsigned int w = 0; w < words; ++ w)
			que.push(act + " " + sWord[w]);
	}

	printf("%u\n", result);


	return 0;
}
Example #5
0
int main(void)
{
    while(scanf("%d", &numbers) != -1 && numbers)
    {
        result = 0;
        for(int n = 0; n < numbers; ++ n)
        {
            scanf("%d", &number);
            que.push(number);
        }

        while(que.size() > 1)
        {
            int first = que.top(); que.pop();
            int second = que.top(); que.pop();
            que.push(first + second);
            result += first + second;
        }

        que.pop();
        printf("%lld\n", result);
    }

    return 0;
}
Example #6
0
// Update the Queue. If the queue size less than K, just push.
// Otherwise, if the new value less than the max value, delete the max
// and push new node into queue.
void updataQ(std::priority_queue<Node>& q, RealT d, int i){
  if(q.size() < K) q.push(Node(i,d));
  else{
    if(q.top().dis > d){
      q.pop();
      q.push(Node(i,d));
    }
  }
}
Example #7
0
 void rearrange(Attributes *attr, TWeight score)
 {
     AttrsPtr a;
     while ((a = opened.top()), opened.pop(), (a.pa != attr)) temp_buff.push_back(a);
     a.pa->fscore = score;
     opened.push(a);
     while (!temp_buff.empty())
     {
         opened.push(temp_buff.back());
         temp_buff.pop_back();
     }
 }
Example #8
0
void Median::insert(int value)
{
   size_t l = maxHeap1.size();
   size_t m = minHeap2.size();
   if (l - m == 0) {
      if (l != 0 && value > maxHeap1.top()) {
         minHeap2.push(value);
      } else {
         maxHeap1.push(value);
      }
   } else if (labs(l - m) == 1) {
      if (l > m) {
         if (maxHeap1.top() > value) {
            int r = maxHeap1.top();
            maxHeap1.pop();
            minHeap2.push(r);
            maxHeap1.push(value);
         } else {
            minHeap2.push(value);
         }
      } else {
         if (minHeap2.top() < value) {
            int r = minHeap2.top();
            minHeap2.pop();
            maxHeap1.push(r);
            minHeap2.push(value);
         } else {
            maxHeap1.push(value);
         }
      }
   }
}
int main()
{		
	for(scanf("%d",&n);i<n;i++)
		scanf("%d",a+i);
	for(i=0;i<n;i++)
		scanf("%d",b+i);
	std::sort(a,a+n);
	std::sort(b,b+n);
	for(i=0;i<n;i++){
		q.push((S){a[i]+b[0],0});			
		printf("%d ",(t=q.top()).s);
		q.pop();
		if(t.b<n)
			q.push((S){t.s-b[t.b]+b[t.b+1],t.b+1});
	}
}
Example #10
0
/**
 * Moves a board in all the possible directions and adds the new states to the queue.
 * @param board The board to be moved.
 * @param queue The priority queue holding all board states.
 */
std::pair<bool, Board*> MoveAllDirectionsAndAddToQueue(Board* &board,
    std::priority_queue<Board*, std::vector<Board*>, QueueCompareClass> &queue) {

    // For all 4 directions, try to move in that direction.
    for (unsigned int i = 0; i < 4; ++i) {
        int direction = DIRECTIONS[i];
        // If the board can move in that direction, then move it.
        // If it can't, then do nothing.
        if (CanMoveInDirection(direction, board)) {
            // Create a copy of the current board, and move the copy.
            Board* new_board = new Board(*board);
            // Actually move the board.
            MoveInDirection(direction, new_board);
            // Set the previous board state.
            new_board->SetPreviousState(board);
            // Check if the board is at the goal state, if so then stop.
            if (new_board->IsAtGoalState()) {
                return std::make_pair(true, new_board);
            }
            // Do not add the new state to the queue if the new board is the
            // same as the previous state.
            if (board->GetPreviousState() &&
                *(board->GetPreviousState()) == *new_board) {
                delete new_board;
                new_board = NULL;
            } else {
                queue.push(new_board);
            }
        }
    }

    return std::make_pair(false, reinterpret_cast<Board*>(NULL));
}
Example #11
0
void enqueue(map_t* map, unsigned int i, unsigned int j, 
	     unsigned int src_i, unsigned int src_j,
	     std::priority_queue<CellData>& Q,
	     CachedDistanceMap* cdm,
	     unsigned char* marked)
{
  if(marked[MAP_INDEX(map, i, j)])
    return;

  unsigned int di = abs(i - src_i);
  unsigned int dj = abs(j - src_j);
  double distance = cdm->distances_[di][dj];

  if(distance > cdm->cell_radius_)
    return;

  map->cells[MAP_INDEX(map, i, j)].occ_dist = distance * map->scale;

  CellData cell;
  cell.map_ = map;
  cell.i_ = i;
  cell.j_ = j;
  cell.src_i_ = src_i;
  cell.src_j_ = src_j;

  Q.push(cell);

  marked[MAP_INDEX(map, i, j)] = 1;
}
int expand()
{
    Nodes node= nodes.top();
   
    if(nodes.size()==0)
    {
             cout<<"error";
             getch();
             return 0;
    }                  
    nodes.pop();
    if(visited[node.node]==1)
         return 0;
    else 
         visited[node.node]=1;
         
    if(node.node==end)
    {
       cout<<"Minimum delay from source to destination device:"<<node.cost;
       return 1;
    }
    else
    {
        for(int j=0;j<n;j++)
        {
           if(a[j][node.node]!=0)
           {
                nodes.push(Nodes(j,node.cost+a[j][node.node]));
           }
        }    
        
    }
   return 0;
}
int expand()
{
    Nodes node= nodes.top();
    getch();
    if(nodes.size()==0)
    {
             cout<<"error";
             getch();
             return 0;
    }                  
    nodes.pop();
    if(visited[node.node]==1)
         return 0;
    else 
         visited[node.node]=1;
         
    if(node.node==end)
    {
       cout<<"finalcost"<<node.cost;
       return 1;
    }
    else
    {
        for(int j=0;j<n;j++)
        {
           if(a[j][node.node]!=0)
           {
                nodes.push(Nodes(j,node.cost+a[j][node.node]));
           }
        }    
        
    }
   return 0;
}
			/**
			 * decode next alignment
			 *
			 * @param algn reference to alignment object to be filled
			 * @return true iff next alignment could be read, false when no more alignments are available
			 **/
			bool readAlignment(libmaus::bambam::BamAlignment & algn)
			{
				if ( Q.empty() )
					return false;
				
				uint64_t const t = Q.top();
				Q.pop();
				
				libmaus::bambam::BamAlignment::D_array_type T = algn.D;
				
				algn.D = data[t].D;
				algn.blocksize = data[t].blocksize;
				
				data[t].D = T;
				data[t].blocksize = 0;
				
				if ( index[t].second-- )
				{
					#if !defined(NDEBUG)
					bool const alok = 
					#endif
					        libmaus::bambam::BamDecoder::readAlignmentGz(*(streams[t]),data[t],0,false);
					        
					#if !defined(NDEBUG)
					assert ( alok );
					#endif
					
					Q.push(t);
				}
					
				return true;
			}
	shared_ptr<RunItem> scheduleFixedInterval(std::function<void()> task, chrono::steady_clock::duration delay) {
		shared_ptr<RunItem> retval(new RunItem(task, delay, true));
		lock_guard<mutex> lock(m);
		delayworkqueue.push(retval);
		cv.notify_one();
		return retval;
	}
Example #16
0
void DifferenceCut::rankImages (std::vector<RowSpan>& spans, std::priority_queue<Ranker>& ordered) {
  assert(ordered.empty());
  float score, dist;
  const unsigned char *Itest, *Iavoid;
  Vec3i Vtest, Vavoid;
  int x, y, index;

  for (unsigned int i=0; i<_images.size(); ++i) {
    score = 0;
    ImageAbs* im = _images[i];
    for (unsigned int j=0; j<spans.size(); ++j) {
      x = spans[j]._x; y = spans[j]._y;
      for (int s=0; s<spans[j]._num; ++s) {
	index = y*_w + x + s;
	Itest = im->data(x+s,y);
	Iavoid = _imptr(_labels[index], Coord(x+s,y));
	Vtest.Set(Itest[0], Itest[1], Itest[2]);
	Vavoid.Set(Iavoid[0], Iavoid[1], Iavoid[2]);
	dist = sqrt(Vtest.distanceTo2(Vavoid));
	//printf("%f\n",dist);
	if (dist > 25)
	  score += 25.;
	else
	  score += dist;
      }
    }
    printf("Image %d, score %f\n",i, score);
    ordered.push(Ranker(i,score));
  }
}
//Maintains the size of the priority queue at the specified size with each push
//For now this function is for priority queue that is in ascending order, top is smallest.
void pushPriorityQueueBounded(std::priority_queue<int, std::vector<int>, std::greater<int> >  &pq,
                              int newElement, unsigned long priorityQueueBound)
{
   if(pq.empty() || newElement > pq.top())
      pq.push(newElement);
   if(pq.size() > priorityQueueBound)
      pq.pop();
}
void UCS()
{
     int check=0;
     nodes.push(Nodes(start,0));
     visited[start]=0;
     while(check==0) 
     check=expand();
}
    inline void push(T item, P priority)
    {
        queue_item qitem(item, priority);

        delay_mtx.lock();
        data.push(qitem);
        delay_mtx.unlock();
    }
Example #20
0
int main(int argc, char **argv)	
{
  
  Object* object;

  /*	object = new Object(Vector(-3.0, 0.0, 0.0), Vector(1.0, 0.0, 0.0), 0.5);

	objects.push_back(object);

	object = new Object(Vector(0.0, -1.0, 0.0), Vector(0.0, 0.4, 0.0), 0.5);

	objects.push_back(object);
        
        object = new Object(Vector(3.0, 0.0, 0.0), Vector(-2.2, 0.0, 0.0), 0.5);
      
	objects.push_back(object); 

  */
	object = new Object(Vector(-3.0, 0.0, 0.0), Vector(velocity, 0.0, 0.0), 0.5, 2.0, 1.0);

	objects.push_back(object);


        object = new Object(Vector(4.0, 0.7, 0.0), 
                                Vector(-velocity, 0.0, 0.0), 
                                0.5, 2.0, 1.0, 
                                Vector(0.0, 0.0, 0.0));
      
	objects.push_back(object); 
        
//        object = new Object(Vector(3.0, 0.0, 0.0), Vector(-velocity, 0.0, 0.0), 0.5, 5, 10.0);
      
//	objects.push_back(object); 


	for(int i = 0; i < objects.size(); i++)
		for(int j = i + 1; j < objects.size(); j++){
			ObjectPair* pair = new ObjectPair(*objects[i], *objects[j]);
			pair->calc_wake_up();
			pairs.push(pair);
		}

        glutInitWindowSize( 600, 450);        
        glutInit(&argc,argv);
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB |GLUT_DEPTH );

        glutCreateWindow("Physics Testlab");

	glutDisplayFunc(display);
	glutIdleFunc(display);

	gfx_init();

	current_time=0.0;
        glutMainLoop();

        return 0;
}
Example #21
0
void AddToHeaps(std::priority_queue<double, std::vector<double>, std::greater<double> >& m,
		std::priority_queue<double>& M, double x){

	// decide on initial heap to place element into
	if(m.empty() || x < m.top())
		M.push(x);
	else
		m.push(x);
	// make sure that heaps are balanced
	if(m.size() > M.size() + 1){
		M.push( m.top() );
		m.pop();	
	}
	else if(M.size() > m.size() + 1){
		m.push( M.top() );
		M.pop();
	}
}
Example #22
0
int main() {
	freopen("1757.in" , "r", stdin );
	freopen("1757.out", "w", stdout);

	scanf("%d %d", &n, &m);
	for (int i=0, cur; i<n; i++) {
		scanf("%d", &cur);
		sands.push(cur);
	}

	const int first = (n - 2) % (m - 1) + 2;
	sands.push(Merge(first));
	for (; sands.size() > 1; )
		sands.push(Merge(m));
	printf("%d\n", ans);

	return 0;
}
Example #23
0
void PushTime( double T )
{
    // don't push in bad times
    // (0 is a special time when no timestamps are in use)
    if( T >= 0 ) {
        std::lock_guard<std::mutex> lock(MUTEX);
        QUEUE.push( T );
    }
}
bool IDAStar::insertState(GameState* currentState,GameState* newState,std::priority_queue<GameState*, std::vector<GameState*>, GameStateComparator>&queue){
	newState->calcEstimatedCosts();
	newState->setPrev(currentState);
	queue.push(newState);

	//std::cout<<"Possible new state with costs:" << newState->getCosts() << std::endl;
	//MapUtils::printMap(*newState,std::cout);
	return true;
}
Example #25
0
void HClustNNbasedSingle::getNearestNeighbors(
   std::priority_queue< HeapHierarchicalItem > & pq,
   size_t index)
{
   if (!shouldFind[index])
      return;

   size_t clusterIndex = ds.find_set(index);
#ifdef GENERATE_STATS
#ifdef _OPENMP
#pragma omp atomic
#endif
   ++stats.nnCals;
#endif
   NNHeap nnheap;
   getNearestNeighborsFromMinRadius(index, clusterIndex, minRadiuses[index], nnheap);
   size_t newNeighborsCount = 0.0;

#ifdef _OPENMP
   omp_set_lock(&pqwritelock);
#endif
   while (!nnheap.empty()) {
      if (isfinite(nnheap.top().dist) && nnheap.top().index != SIZE_MAX) {
         ++newNeighborsCount;
         pq.push(HeapHierarchicalItem(index, nnheap.top().index, nnheap.top().dist));
         minRadiuses[index] = std::max(minRadiuses[index], nnheap.top().dist);
      }
      nnheap.pop();
   }
   neighborsCount[index] += newNeighborsCount;
#ifdef GENERATE_STATS
   stats.nnCount += newNeighborsCount;
#endif
   if (neighborsCount[index] > n - index || newNeighborsCount == 0)
      shouldFind[index] = false;
   else {
      pq.push(HeapHierarchicalItem(index, SIZE_MAX, minRadiuses[index])); // to be continued...
   }
#ifdef _OPENMP
   omp_unset_lock(&pqwritelock);
#endif
}
int main()
{
	scanf( "%d", &N );
	REP(i, N)
	{
		int x;
		scanf( "%d", &x );
		pq.push(x);
		while (pq.size() > N / 2 + 1)
		      pq.pop();
	}
	shared_ptr<RunItem> post(std::function<void()> task, std::chrono::steady_clock::duration delay) {
		shared_ptr<RunItem> retval(new RunItem(task, delay, false));
		lock_guard<mutex> lock(m);
		if(delay == std::chrono::steady_clock::duration(0)){
			workqueue.push_back(retval);
		} else {
			delayworkqueue.push(retval);
		}
		cv.notify_one();
		return retval;
	}
Example #28
0
int main(){
	int n;
	while(scanf("%d",&n)!=EOF&&n){
		while(!L.empty())L.pop();
		int i,res=0,t;
		num x,y;
		for(i=1;i<=n;i++){
			scanf("%d",&t);
			L.push( (num){t} );
			}
		while(L.size()>1){
			x=L.top();L.pop();
			y=L.top();L.pop();
			res+=x.x+y.x;
			if(L.empty())break;
			L.push( (num){x.x+y.x} );
			}
		printf("%d\n",res);
		}
	return 0;
	}
Example #29
0
void update_world(double frame_start,double tot_time){

        double frame_stop = current_time+tot_time;
        double dt;
        
        ObjectPair* pair;
        
        if(pairs.size() > 0 ){
                while( pairs.top()->wake_up < frame_stop){

                        pair = pairs.top();
			// cout << "Popped pair: " << pair->id << ".\n";
                        
                        dt = pair->wake_up - pair->sim_time();
                        if( dt < min_dt)
                                dt=min_dt;
                        
                        //the object will be simulated this far when the loo has ended
                        
                        pairs.pop();
                        pair->simulate(dt);
                                                
                        if(pair->has_collided()){
                                Collision col = pair->get_collision();
                                pair->collide(col);
                                pair->simulate(min_dt);
                                        
                              while(pair->has_collided()){
                                      pair->simulate(min_dt);
                              }
                               
                        }

                

			//		cout << "Before -- Pair: " << pair->id << " Wake_up: " << pair->wake_up << ".\n";
		pair->calc_wake_up();
		//		cout << "After -- Pair: " << pair->id << " Wake_up: " << pair->wake_up << ".\n";

                pairs.push(pair);// bara om de inte har dött
                }                
        }
        
        
        for(int i = 0; i < objects.size(); i++){
                dt = frame_stop - objects[i]->sim_time;
                if(dt > 0)
                    objects[i]->simulate(dt);
        }


}
Example #30
0
bool LogEntryParser::getAllEntrys(std::priority_queue<model::LogEntry>& list)
{
	openLogFile();

	std::vector<std::string> last10LogEntrys;
	readLast10Entrys(last10LogEntrys);

	for(std::vector<std::string>::iterator entryIt = last10LogEntrys.begin(); entryIt != last10LogEntrys.end(); entryIt++)
		list.push(parseLogEntry(*entryIt));

	closeLogFileIfOpen();
	return true;
}