Пример #1
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;
}
Пример #2
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);
         }
      }
   }
}
Пример #3
0
int main() {
    scanf("%d %d", &n, &m);
    for (int i = 0; i < m; i++) {
        scanf("%d %d %d", &a, &b, &t);
        adj[a].push_back(std::make_pair(b, t));
        adj[b].push_back(std::make_pair(a, t));
    }
    
    dist[0] = 0;
    q.push(std::make_pair(0, 0));
    for (int i = 1; i < n; i++) {
        dist[i] = 0x3f3f3f3f;
        q.push(std::make_pair(-dist[i], i));
    }
    
    while (!q.empty()) {
        std::tie(cur_dist, cur_index) = q.top(); q.pop();
        cur_dist *= -1;
        vis[cur_index] = 1;
        for (std::pair<int, int> p : adj[cur_index]) {
            if (!vis[p.first]) {
                const int alt = cur_dist + p.second;
                if (alt < dist[p.first]) {
                    dist[p.first] = alt;
                    q.push(std::make_pair(-alt, p.first));
                }
            }
        }
    }

    dist2[0] = 0;
    q.push(std::make_pair(0, n - 1));
    for (int i = 0; i < n - 1; i++) {
        dist2[i] = 0x3f3f3f3f;
        q.push(std::make_pair(-dist2[i], i));
    }

    while (!q.empty()) {
        std::tie(cur_dist, cur_index) = q.top(); q.pop();
        cur_dist *= -1;
        vis2[cur_index] = 1;
        for (std::pair<int, int> p : adj[cur_index]) {
            if (!vis2[p.first]) {
                const int alt = cur_dist + p.second;
                if (alt < dist2[p.first]) {
                    dist2[p.first] = alt;
                    q.push(std::make_pair(-alt, p.first));
                }
            }
        }
    }
    
    for (int i = 0; i < n; i++) {
        ans = std::max(ans, dist[i] + dist2[i]);
    }
    printf("%d\n", ans);
}
Пример #4
0
void checkCollision() {
    int i, j;
    if ( events.size()!=0) {
        while( elapsedTime >= events.top().timeOccuring)
        {
            i = events.top().i;

            if( checkOutdated( events.top() ) ) {
                printf("---POOPZIES of %d, timeInserted=%f, lastCollition=%f\n",
                       i, events.top().timeInserted, sphere[i].lastCollision );
                events.pop();
            } else if (events.top().j!=-1) {
                j = events.top().j;

                sphere[i].q0 += (events.top().timeOccuring - sphere[i].t0) * sphere[i].speedVec;
                sphere[i].speedVec = sphere[i].newSpeedVec;
                sphere[i].t0 = events.top().timeOccuring;

                sphere[j].q0 += (events.top().timeOccuring - sphere[j].t0) * sphere[j].speedVec;
                sphere[j].speedVec = sphere[j].newSpeedVec;
                sphere[j].t0 = events.top().timeOccuring;

                sphere[i].cols++;
                sphere[j].cols++;

                events.pop();
                calculateCollision(i);
                calculateCollision(j);
                printf("BALLZIES of %d, timeInserted=%f, lastCollition=%f\n",
                       i, events.top().timeInserted, sphere[i].lastCollision );
            } else {
                sphere[i].q0 += (events.top().timeOccuring - sphere[i].t0) * sphere[i].speedVec;
                sphere[i].speedVec = sphere[i].newSpeedVec;
                sphere[i].t0 = events.top().timeOccuring;

                sphere[i].cols++;

                events.pop();
                calculateCollision(i);
                printf("WALLZIES of %d, timeInserted=%f, lastCollition=%f\n",
                       i, events.top().timeInserted, sphere[i].lastCollision );
            }
        }
        //std::vector<Sphere>::iterator it = sphereIterInit;
        //for(it; it != sphere.end();it++){
        //	position = it->q0 + (float)(elapsedTime - it->t0) * it->speedVec;
        //	if(abs(position.x)>0.96f || abs(position.y)>0.96f || abs(position.z)>0.96f){
        //		printf("WHAT THE F**K MOAR BUGS PLS!!!!!AAAAAAAAAAARRGGH\n");
        //	}
        //}


        minmin = (events.top().timeOccuring<minmin)?events.top().timeOccuring:minmin;
    }
}
Пример #5
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)];
	}
}
Пример #6
0
 // this 
 inline void scheduler_loop() {
     std::unique_ptr<Priority> pCurrentPrty;
     for (;;) {
         std::unique_lock<std::mutex> lock(queue_mutex);
         // wait for some task to get queued or for the atomic 
         // isActive flag to become inactive
         condition.wait(lock, [this, &pCurrentPrty] {
             if (!mTasks.empty() && 
                 pCurrentPrty && pCurrentPrty->getPriorityStr() != 
                 mTasks.top().getPriority().getPriorityStr() && 
                 pCurrentPrty->getPriorityStr().length() != 
                 mTasks.top().getPriority().getPriorityStr().length()) {
                 std::cout << "priority change" << std::endl;
             }
             return (!mTasks.empty() || !isActive.load());
         });
         // only exit when no more tasks on the queue
         if (!isActive.load() && mTasks.empty()) {
             return;
         }
         // update the top priority job that is currently running
         pCurrentPrty = std::make_unique<Priority>(mTasks.top().getPriority());
         // move next task off the priority queue
         auto nextTask(std::move(mTasks.top()));
         pCurrentPrty = std::make_unique<Priority>(nextTask.getPriority());
         // queue housekeeping
         mTasks.pop();
         // release the lock allowing new entries to be queued
         lock.unlock();
         // execute the task forwarding stored arguments with the call
         // this is the magic that works inside a thread pool
         // _Ret operator()(_Types... _Args) const 
         nextTask();
     }
 }
Пример #7
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;
}
Пример #8
0
	Node::Ptr pop() {
		if (queue.empty())
			return Node::Ptr();
		Node::Ptr result = queue.top();
		queue.pop();
		return result;
	}
Пример #9
0
/**
 * Recursively search the decision tree over the acting agents.
 *
 * TODO: I want a custom priority queue here, which can be quickly reset and copied
 */
float doSearch(
		WorldStateInterface* progressiveWorldState,
		std::priority_queue<AgentStateInterface*> agentQueue,
		int depth) {

	if (depth <= 0) {
		// TODO: evaluate the state
		return 0;
	}

	WorldStateInterface::SnapshotInterface* snapshot = progressiveWorldState->takeSnapshot();

	AgentStateInterface* actingAgent = agentQueue.top();
	agentQueue.pop();
	std::list<ActionInterface*> actions = actingAgent->getPossibleActions();
	float best = 0, score = 0;

	for (std::list<ActionInterface*>::iterator iter = actions.begin(); iter != actions.end(); ++iter) {
		(*iter)->doAction();
		score = doSearch(progressiveWorldState, agentQueue, depth - 1);
		progressiveWorldState->restoreShapshot(snapshot);

		if (score > best) {
			best = score;
		}
	}

	return best;
}
Пример #10
0
PLUGIN_EXPORT int PLUGIN_CALL
	AmxUnload(AMX * amx) 
{
	std::priority_queue<struct timer_s *, std::deque<struct timer_s *>, TimerCompare>
		cleaned;
	// Destroy all the timers for this mode.
	while (!gTimers.empty())
	{
		struct timer_s *
			next = gTimers.top();
		gTimers.pop();
		if (next->amx == amx)
		{
			// Ending, remove from the map also.
			gHandles.erase(next->id);
		}
		else
		{
			// Not ending, leave it be.
			cleaned.push(next);
		}
	}
	gTimers = cleaned;
	for (int i = 0; i != 17; ++i)
	{
		if (gAMXFiles[i] == amx)
		{
			gAMXFiles[i] = 0;
			break;
		}
	}
	return AMX_ERR_NONE;
}
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;
}
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;
}
Пример #13
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;
			}
Пример #14
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;
}
// preferences should be a member
wns::scheduler::ConnectionID
ProportionalFair::getNextConnection(SchedulerStatePtr schedulerState,
                                    std::priority_queue<UserPreference> preferences)
{
    wns::scheduler::ConnectionID next = -1;

    while (!preferences.empty())
    {
        int priority = schedulerState->currentState->getCurrentPriority();
        const float preference = preferences.top().first;
        const UserID user = preferences.top().second;
        MESSAGE_SINGLE(NORMAL, logger, "Selected user="******"Selected connection with CID="<<next);
            return next;
        }
        preferences.pop();
    }
    return next;
}
Пример #16
0
 inline T pop(void)
 {
     delay_mtx.lock();
     T ret(data.top().item);
     data.pop();
     delay_mtx.unlock();
     return ret;
 }
Пример #17
0
 void operator<<(std::priority_queue<_Tp,Range,Compare> lhs)
 {
         for(;!lhs.empty();){
                 std::cout<<lhs.top()<<token;
                 lhs.pop();
         }
         std::cout<<last_token<<std::flush;
 }
//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();
}
Пример #19
0
void PopTime()
{
    std::lock_guard<std::mutex> lock(MUTEX);
    QUEUE.pop();

    // notify waiting threads that a change in the QUEUE has occured
    CONDVAR.notify_all();
}
int main(){
	int n;
	while(scanf("%d",&n)!=EOF){
		int i;
		int flag1=1,flag2=1,flag3=1;
		while(!ty1.empty())ty1.pop();
		while(!ty2.empty())ty2.pop();
		while(!ty3.empty())ty3.pop();
		int order,x;
		for(i=1;i<=n;i++){
			scanf("%d%d",&order,&x);
			if(order==1){
				ty3.push(x);
				ty2.push(x);
				ty1.push(x);
				}
			else {
				if(flag3&&!ty3.empty()){
					if(ty3.top()==x)ty3.pop();
					else flag3=0;
					}
				else flag3=0;
				
				if(flag2&&!ty2.empty()){
					if(ty2.top()==x)ty2.pop();
					else flag2=0;
					}
				else flag2=0;
				
				if(flag1&&!ty1.empty()){
					if(ty1.front()==x)ty1.pop();
					else flag1=0;
					}
				else flag1=0;
				}
			}
		int sum=flag1+flag2+flag3;
		if(sum>=2)printf("not sure\n");
		else if(sum==0)printf("impossible\n");
		else if(flag1)printf("queue\n");
		else if(flag2)printf("priority queue\n");
		else printf("stack\n"); 
		}
	return 0;
	}
Пример #21
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));
    }
  }
}
Пример #22
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();
	}
}
Пример #23
0
int Merge(const int num) {
	int ret = 0;
	for (int i=0; i<num; i++) {
		ret += sands.top();
		sands.pop();
	}
	ans += ret;
	return ret;
}
Пример #24
0
	bool pop_front(T& data)
	{
		std::lock_guard<std::mutex> guard(mtx);
		if (pq.size() > 1)
		{
			data = pq.top();
			pq.pop();
			return true;
		}
		return false;
	};
Пример #25
0
// Output the Queue
void display(std::priority_queue<Node>& q){ // reverse
  std::vector<Node> v;
  v.reserve(K);
  while (!q.empty()){  
    v.push_back(q.top());
    q.pop();  
  } 
  for(int i=K;i>0;i--){
    PrintfNode(v[i-1]);
  }
}
Пример #26
0
void simulation::run () {

    while (! eventQueue.empty ()) {

        event * nextEvent = eventQueue.top ();
        eventQueue.pop ();
        time = nextEvent->time;
        nextEvent->processEvent ();
        delete nextEvent;
    }
}
Пример #27
0
int main()
{
	scanf( "%d", &N );
	REP(i, N)
	{
		int x;
		scanf( "%d", &x );
		pq.push(x);
		while (pq.size() > N / 2 + 1)
		      pq.pop();
	}
Пример #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;
	}
Пример #29
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();
     }
 }
Пример #30
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);
        }


}