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); } } } }
double getMedian(const std::priority_queue<double, std::vector<double>, std::greater<double> >& m, const std::priority_queue<double>& M){ if(m.size() > M.size()) // There are an odd number of observations return m.top(); else if(M.size() > m.size()) // There are an odd number of observations return M.top(); else // There are an even number of obersations return (m.top()+M.top())/2; }
//Maintains the size of the priority queue at the specified size bound with each push //For now this function is for priority queue that is in ascending order, top is smallest. //Returns result: 0 if not added, 1 if pushed without pop, 2 if pushed & popped int pushBoundedPriorityQueue(std::priority_queue<int, std::vector<int>, std::greater<int> > &pq, int element, long bound) { int result = 0; if(pq.size() < bound || element > pq.top()){ pq.push(element); result = 1; if(pq.size() > bound){ pq.pop(); result = 2; } } return result; }
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; }
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; }
double Median::getMedian(void) { size_t l = maxHeap1.size(); size_t m = minHeap2.size(); if (l == 0 && m == 0) { throw std::invalid_argument("No elements inserted yet"); } if (l - m == 0) { return (maxHeap1.top() + minHeap2.top()) / 2.0; } else { if (l > m) { return maxHeap1.top(); } else { return minHeap2.top(); } } }
//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; cout<<nodes.size(); while(check==0) check=expand(); }
// 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)); } } }
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(); } }
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; } }
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; };
int main() { scanf( "%d", &N ); REP(i, N) { int x; scanf( "%d", &x ); pq.push(x); while (pq.size() > N / 2 + 1) pq.pop(); }
// Helper function that searches the tree void search(Node* node, const T& target, int k, std::priority_queue<HeapItem>& heap) { if(node == NULL) return; // indicates that we're done here // Compute distance between target and current node ScalarType dist = distance(_items[node->index], target); // If current node within radius tau if(dist < _tau) { if(heap.size() == static_cast<size_t>(k)) heap.pop(); // remove furthest node from result list (if we already have k results) heap.push(HeapItem(node->index, dist)); // add current node to result list if(heap.size() == static_cast<size_t>(k)) _tau = heap.top().dist; // update value of tau (farthest point in result list) } // Return if we arrived at a leaf if(node->left == NULL && node->right == NULL) { return; } // If the target lies within the radius of ball if(dist < node->threshold) { if(dist - _tau <= node->threshold) { // if there can still be neighbors inside the ball, recursively search left child first search(node->left, target, k, heap); } if(dist + _tau >= node->threshold) { // if there can still be neighbors outside the ball, recursively search right child search(node->right, target, k, heap); } // If the target lies outsize the radius of the ball } else { if(dist + _tau >= node->threshold) { // if there can still be neighbors outside the ball, recursively search right child first search(node->right, target, k, heap); } if (dist - _tau <= node->threshold) { // if there can still be neighbors inside the ball, recursively search left child search(node->left, target, k, heap); } } }
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); } }
int main() { ll n; cin>>n; while(n>0){ while(pq.size()) pq.pop(); for (int i = 0; i < n; ++i) { ll x; cin>>x; pq.push(x); } ll ans=0; while(pq.size()!=1){ ll a=pq.top();pq.pop(); ll b=pq.top();pq.pop(); ans+=(a+b); pq.push(a+b); } cout<<ans<<endl; cin>>n; } return 0; }
bool contains(T data) { std::lock_guard<std::mutex> guard(mtx); if (pq.size() > 1) { std::vector<T> *queue_vector; //recast the priority queue to vector queue_vector = reinterpret_cast<std::vector<T> *>(&pq); for(typename std::vector<T>::iterator it = (*queue_vector).begin(); it != (*queue_vector).end(); it++) { if (data == *it) return true; } } return false; }
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; }
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; }
void AI::publishThreeComponentRHL(std::priority_queue < std::pair<double, cv::Point2d>, std::vector<std::pair<double, cv::Point2d> >, AI::CompareComponentsWithDeviation> largestThreeComponentQueue) { //create message robia::points_tuple message; if (largestThreeComponentQueue.size() != 3) { // Left Hand, Head, Right hand message.Rx = -1; message.Ry = -1; message.Hx = -1; message.Hy = -1; message.Lx = -1; message.Ly = -1; } else { std::vector<cv::Point2d> largestThreeComponentVector; while(!largestThreeComponentQueue.empty()) { largestThreeComponentVector.push_back(largestThreeComponentQueue.top().second); largestThreeComponentQueue.pop(); } std::sort(largestThreeComponentVector.begin(), largestThreeComponentVector.end(), comparePointsWithRespectToX); // Left Hand, Head, Right hand message.Rx = largestThreeComponentVector[0].x/LengthOfCamera; message.Ry = largestThreeComponentVector[0].y/HeightOfCamera; message.Hx = largestThreeComponentVector[1].x/LengthOfCamera; message.Hy = largestThreeComponentVector[1].y/HeightOfCamera; message.Lx = largestThreeComponentVector[2].x/LengthOfCamera; message.Ly = largestThreeComponentVector[2].y/HeightOfCamera; } // Publish three points to ROSTopic pubThreePointsPositions.publish(message); }
void runSaltBridgeMC( subSeq &_exposedPositions, map<string,map<string,map<int, map<string,map<string, double> > > > > &_sbScoreTable, System &_sys, Options &_opt, std::priority_queue< std::pair<saltBridgeResult,subSeq>, std::vector< std::pair<saltBridgeResult,subSeq> >, compareScores> &_mcData){ // WT score saltBridgeResult wt_sbresult = scoreSaltBridgePositions(_exposedPositions,_sbScoreTable,_sys); // Map to insure we don't fill priority queue with duplicates map<string,bool> mcDataMap; string possibleMutations = "KREDH"; RandomNumberGenerator rng; rng.setTimeBasedSeed(); MSLOUT.stream() << "RNG SEED: "<<rng.getSeed()<<endl; //MonteCarloManager MCMngr(_startingTemperature, _endingTemperature,_scheduleCycles, _scheduleShape, _maxRejectionsNumber, _convergedSteps, _convergedE); MonteCarloManager MCMngr(_opt.startMCtemp,_opt.endMCtemp,_opt.numMCcycles, MonteCarloManager::EXPONENTIAL,100,0,0.0); MCMngr.setRandomNumberGenerator(&rng); MCMngr.setEner(wt_sbresult.score); subSeq current = _exposedPositions; string wtSeq = _exposedPositions.seq; // TODO add options to Options opt; to take care of MC-related options..... get rid of hard-coded values. while (!MCMngr.getComplete()) { // Make change int mutIndex = rng.getRandomInt(0,possibleMutations.size()-1); int seqPosIndex = rng.getRandomInt(0,_exposedPositions.seq.size()-1); string mutAA = possibleMutations.substr(mutIndex,1); string previousAA = current.seq.substr(seqPosIndex,1); current.seq.replace(seqPosIndex,1,mutAA); // Eval saltBridgeResult sbResult = scoreSaltBridgePositions(current,_sbScoreTable,_sys); //MSLOUT.stream() << "SCORE: "<<score<<" wt: "<<wt_score<<endl; // MC test for Acceptance: if (MCMngr.accept(sbResult.score)){ //cout << "New SEQ: "<<current.seq<<" score: "<<score<<endl; //cout << "WT SEQ: "<<wtSeq<<" score: "<<wt_score<<endl; bool keepIt = false; map<string, bool>::iterator it; it = mcDataMap.find(sbResult.sbId); if (it == mcDataMap.end()){ mcDataMap[sbResult.sbId] = true; if (_mcData.size() >= _opt.numSequenceModels){ if (sbResult.score < _mcData.top().first.score){ // Remove highest score, then add _mcData.pop(); _mcData.push(pair<saltBridgeResult,subSeq>(sbResult,current)); keepIt = true; } } else { _mcData.push(pair<saltBridgeResult,subSeq>(sbResult,current)); keepIt = true; } } if (!keepIt){ current.seq.replace(seqPosIndex,1,previousAA); } } else { current.seq.replace(seqPosIndex,1,previousAA); } } MSLOUT.stream() << "MC Completed -> "<<MCMngr.getReasonCompleted()<<endl; }
size_t size() const { return queue.size(); }
void dijkstra_pq_thread(CSRGraph *g, int *dist, std::priority_queue<Priority_struct, std::vector<Priority_struct>, Compare_priority> &pq, int threadNum, std::mutex *dist_locks) { while(!pq.empty()) { queue_lock.lock(); if(pq.empty()) { queue_lock.unlock(); break; } Priority_struct temp_struct = pq.top(); int u = temp_struct.node_name; pq.pop(); printf("Popped\n"); for(int i=0; i< pq.size();i++){ printf(" %d", pq[i]); } printf("\n"); int udist = dist[u]; queue_lock.unlock(); std::vector<int> neighbors = CSRGraph_getNeighbors(g, u); int neighbor; for(neighbor=0;neighbor < neighbors.size(); neighbor++) { int v = neighbors[neighbor]; int uvdist = CSRGraph_getDistance(g, u, v); int alt = udist + uvdist; dist_locks[v].lock(); if(alt < dist[v]) { dist[v] = alt; dist_locks[v].unlock(); Priority_struct temp2; temp2.node_name=v; temp2.node_weight = uvdist; queue_lock.lock(); pq.push(temp2); printf("Pushed\n"); for(int i=0; i< pq.size();i++){ printf(" %d", pq[i]); } printf("\n"); queue_lock.unlock(); } else { dist_locks[v].unlock(); } } } //printf("Thread %d ended.\n", threadNum); }
inline size_t size(void) const { return data.size(); }
size_t size() const { std::lock_guard<std::mutex> guard(mtx); return pq.size(); };