ListNode *mergeKLists(vector<ListNode *> &lists) { // wyuan; 10/11/2014; Maitain a min heap. Use make_heap in <algorithm> if(lists.empty()) return NULL; int size = lists.size(); // vector<node> heap(size); Which one is better? vector<node> heap; heap.reserve(size); for(int i = 0; i < size; i++) heap.push_back(node(lists[i])); make_heap(heap.begin(), heap.end(), greater<node>()); ListNode *head = new ListNode(0); // Init!!!!!! ListNode *pre = head; pop_heap(heap.begin(), heap.end(), greater<node>()); node minNode = heap.back(); heap.pop_back(); while(minNode.val != INT_MAX) { pre->next = minNode.from; pre = pre->next; ListNode *next = minNode.from->next; heap.push_back(node(next)); push_heap(heap.begin(), heap.end(), greater<node>()); pop_heap(heap.begin(), heap.end(), greater<node>()); minNode = heap.back(); heap.pop_back(); } ListNode *ret = head->next; delete head; return ret; }
void addNum(int num) { if (upper.size() == 0) { upper.push_back(num); } else if (upper.size() == lower.size()) { if (num > lower[0]) { upper.push_back(num); push_heap(upper.begin(), upper.end(), greater<int>()); } else { lower.push_back(num); push_heap(lower.begin(), lower.end()); int val = lower[0]; pop_heap(lower.begin(), lower.end()); lower.pop_back(); upper.push_back(val); push_heap(upper.begin(), upper.end(), greater<int>()); } } else { if (num > upper[0]) { upper.push_back(num); push_heap(upper.begin(), upper.end(), greater<int>()); int val = upper[0]; pop_heap(upper.begin(), upper.end(), greater<int>()); upper.pop_back(); lower.push_back(val); push_heap(lower.begin(), lower.end()); } else { lower.push_back(num); push_heap(lower.begin(), lower.end()); } } }
/* store the alpha values and build a beta_tree for the generator */ void gen_dirch_initialize(gen_dirch_param *gen, int numd, const double *alp) { int *heap; int heap_size; int leaf, internal; /* indexes of nodes in tree */ double *alpha; /* shorthand pointer for gen->alpha */ gen->num_dim = numd; /* allocate space for the alphas---both for the leaves and the * internal nodes */ gen->alpha = alpha = (double*)calloc(2*numd-1, sizeof(double)); assert(gen->alpha); /* allocate space for the internal nodes */ gen->betas = (gen_beta_param*) calloc(numd-1, sizeof(gen_beta_param)); assert(gen->betas); gen->left = (int*) calloc(numd-1, sizeof(int)); assert(gen->left); gen->right = (int*) calloc(numd-1, sizeof(int)); assert(gen->right); /* Build a "Huffman encoding" tree using a heap. * First, fill the heap array with the indexes of the leaves */ heap = (int*)calloc(numd, sizeof(int)); for (leaf=numd-1; leaf>=0; leaf--) { alpha[leaf] = alp[leaf]; heap[leaf] = leaf; } heapify(heap, alpha, numd); heap_size=numd; internal = 0; /* number of internal nodes created so far */ while(heap_size>=2) { gen->left[internal] = pop_heap(heap, alpha, &heap_size); gen->right[internal] = pop_heap(heap, alpha, &heap_size); gen_beta_initialize(&(gen->betas[internal]), alpha[gen->left[internal]], alpha[gen->right[internal]]); alpha[internal+numd] = alpha[gen->left[internal]] + alpha[gen->right[internal]]; push_heap(heap, alpha, &heap_size, internal+numd); internal++; } gen->root_index = internal+numd-1; assert(gen->root_index == 2*numd-2); free(heap); }
void Word2Vec::create_huffman_tree() { size_t vocab_size = vocab.size(); vector<Word *> heap = vocab; make_heap(heap.begin(), heap.end(), comp); for(size_t i = 0; i < vocab_size - 1; ++i) { pop_heap(heap.begin(), heap.end(), comp); Word *min_left = heap.back(); heap.pop_back(); pop_heap(heap.begin(), heap.end(), comp); Word *min_right = heap.back(); heap.pop_back(); Word *w = new Word(i + vocab_size, min_left->count + min_right->count, "", min_left, min_right); heap.push_back(w); push_heap(heap.begin(), heap.end(), comp); } //traverse huffman tree,get code list<tuple<Word *, vector<size_t>, vector<size_t>>> stack; stack.push_back(make_tuple(heap[0], vector<size_t>(), vector<size_t>())); while(!stack.empty()) { auto n = stack.back(); stack.pop_back(); Word *n_w = get<0>(n); if(n_w->index < vocab_size) { n_w->codes = get<1>(n); n_w->points = get<2>(n); } else { auto codes_left = get<1>(n); auto codes_right = codes_left; codes_left.push_back(0); codes_right.push_back(1); auto points = get<2>(n); points.emplace_back(n_w->index - vocab_size); stack.emplace_back(make_tuple(n_w->left, codes_left, points)); stack.emplace_back(make_tuple(n_w->right, codes_right, points)); } } }
bool Graph::pfs() { int v, j, ww, x; bool caled[MaxVertex]; int wt[MaxVertex]; vector<Node> myheap; memset(father, 0xff, sizeof(int)*V); memset(caled, 0, sizeof(bool)*V); memset(wt, 0xff, sizeof(int)*V); myheap.clear(); father[s] = s; myheap.push_back(Node(s, INT_MAX)); // assert(s != t); while(!myheap.empty()) { v = myheap[0].v; ww = myheap[0].wt; pop_heap(myheap.begin(), myheap.end(), cmp); myheap.pop_back(); if(caled[v]) continue; caled[v] = 1; for(j = 0; j < V; ++j) if(cap[v][j]>0 && !caled[j]) { x = ww<cap[v][j] ? ww : cap[v][j]; if(x <= wt[j]) continue; father[j] = v; if(j == t) return 1; wt[j] = x; myheap.push_back(Node(j, x)); push_heap(myheap.begin(), myheap.end(), cmp); } } return 0; }
int main () { unsigned int n, i; unsigned int x; double med; int v[250000/2+3]; i = 0; cin >> n; for(; i < n/2+1; ++i) cin >> v[i]; make_heap(v,v+n/2+1); for(; i < n; ++i){ cin >> v[n/2+1]; push_heap(v,v+n/2+2); pop_heap(v,v+n/2+2); } if (n % 2 != 0) med = v.back(); else { x = v.back(); v.pop_back(); med = (v.back()*0.5 + x*0.5); } cout << setiosflags (ios::fixed) << setprecision(1) << med << endl; return 0; }
const N PriorityQueue<N, Val>::minPrioirty() { //removes the top element of the queue. const N minnode = top(); pop_heap(nodetracker.begin(), nodetracker.end(), NodeComparator()); nodetracker.pop_back(); return minnode; }
void TimeScheduler::update(float time) { while(!schedule.empty() && schedule.front().wakeup_time < time) { HSQOBJECT thread_ref = schedule.front().thread_ref; sq_pushobject(global_vm, thread_ref); sq_getweakrefval(global_vm, -1); HSQUIRRELVM scheduled_vm; if(sq_gettype(global_vm, -1) == OT_THREAD && SQ_SUCCEEDED(sq_getthread(global_vm, -1, &scheduled_vm))) { if(SQ_FAILED(sq_wakeupvm(scheduled_vm, SQFalse, SQFalse, SQTrue))) { std::ostringstream msg; msg << "Couldn't wakeup scheduled squirrel VM: "; sq_getlasterror(scheduled_vm); if(sq_gettype(scheduled_vm, -1) != OT_STRING) { msg << "(no info)"; } else { const char* lasterr; sq_getstring(scheduled_vm, -1, &lasterr); msg << lasterr; } log_warning << msg.str() << std::endl; sq_pop(scheduled_vm, 1); } } sq_release(global_vm, &thread_ref); sq_pop(global_vm, 2); pop_heap(schedule.begin(), schedule.end()); schedule.pop_back(); } }
void CAstar::Astar(CAstarNode*& result) { CAstarNode s0(m_hgevStart,0,CalculateH(m_hgevStart),NULL); //open表中插入起点 m_vOpenList.push_back(s0); make_heap(m_vOpenList.begin(),m_vOpenList.end()); // CAstarNode* min; while(!m_vOpenList.empty()) { //pop出堆顶节点 pop_heap(m_vOpenList.begin(),m_vOpenList.end(),cmpAstarNode); result = new CAstarNode(m_vOpenList.back().m_hgevCoordinate,m_vOpenList.back().m_nG, m_vOpenList.back().m_nH, m_vOpenList.back().m_pParent); //若节点是目标节点,则返回 if(result->m_hgevCoordinate == m_hgevGoal) { // memcpy(result,&min,sizeof(CAstarNode)); return ; } m_vOpenList.pop_back(); // make_heap(m_vOpenList.begin(),m_vOpenList.end()); //扩展该节点 ExtendNode(result); // make_heap(m_vOpenList.begin(),m_vOpenList.end()); m_vClosedList.push_back(*result); } result = NULL; }
PWDB* clustering_ctg(PWDB *db, uint32_t min_overlap, float het) { PWDB *ret; ret = db; uint32_t i, j, p, q; PWcontig *poped; while ((poped = pop_heap(db->hp)) != NULL) { if (poped->overlap >= min_overlap && (poped->het - het <= 0)) { p = poped->id0; q = poped->id1; for (i = p; i != (ref_ctglist(ret->ctgv, i))->cls_id; i = (ref_ctglist(ret->ctgv, i))->cls_id) ref_ctglist(ret->ctgv, i)->cls_id = ref_ctglist(ret->ctgv, ref_ctglist(ret->ctgv, i)->cls_id)->cls_id; for (j = q; j != (ref_ctglist(ret->ctgv, j))->cls_id; j = (ref_ctglist(ret->ctgv, j))->cls_id) ref_ctglist(ret->ctgv, j)->cls_id = ref_ctglist(ret->ctgv, ref_ctglist(ret->ctgv, j)->cls_id)->cls_id; if (i == j) continue; if (ref_ctglist(ret->ctgv, i)->sz < ref_ctglist(ret->ctgv, j)->sz) { ref_ctglist(ret->ctgv, i)->cls_id = j; ref_ctglist(ret->ctgv, j)->sz += ref_ctglist(ret->ctgv, i)->sz; } else { ref_ctglist(ret->ctgv, j)->cls_id = i; ref_ctglist(ret->ctgv, i)->sz += ref_ctglist(ret->ctgv, j)->sz; } } } return ret; }
ListNode* mergeKLists(vector<ListNode*>& lists) { vector<ListNode *> minHeap; for (auto list: lists) { if (list != nullptr) { minHeap.push_back(list); } } make_heap(minHeap.begin(), minHeap.end(), compare); ListNode *res = new ListNode(-1); ListNode *cur = res; while (!minHeap.empty()) { pop_heap(minHeap.begin(), minHeap.end(), compare); ListNode *node = minHeap.back(); minHeap.pop_back(); cur->next = node; cur = cur->next; if (node->next) { minHeap.push_back(node->next); push_heap(minHeap.begin(), minHeap.end(), compare); } } return res->next; }
int solve(const IntVec& A, const IntVec& B, int k) { IntVec q(k); int n = 0; int NA = A.size() >= k ? k : A.size(); int NB = B.size() >= k ? k : B.size(); for (int i = 0; i < NA; ++i) { for (int j = 0; j < NB; ++j) { int s = A[i] + B[i]; if (n == k) { if (s < q[0]) { pop_heap(q.begin(), q.end()); q[n - 1] = A[i] + B[j]; push_heap(q.begin(), q.begin() + n); } } else { q[n++] = A[i] + B[j]; push_heap(q.begin(), q.begin() + n); } // cout << n << "," << q << endl; } } // cout << q << endl; return q[0]; }
//T: O(ElogV), M: theta(V + E) void dijkstra(vector<vector<Aresta> > &g, int r) { int n = g.size(); vector<Vertice> Q; d.clear(); d.resize(n, INT_MAX); vector<bool> cor(n, false); Q.push_back(r); d[r] = 0; cor[r] = true; while (!Q.empty()) { int u = Q[0]; //if(procurado == u) return; pop_heap(Q.begin(), Q.end(), comp); Q.pop_back(); for (int i = 0; i < g[u].size(); i++) { if (d[u] + g[u][i].p < d[g[u][i].v]) d[g[u][i].v] = d[u] + g[u][i].p; //relaxamento if (!cor[g[u][i].v]) { cor[g[u][i].v] = true; Q.push_back(g[u][i].v); } } make_heap(Q.begin(), Q.end(), comp); } }
void BBTreeTrain::pop() { pop_heap(nodes_.begin(), nodes_.end(), compare_); log_info("Popping node %d %f", nodes_.back()->id(), nodes_.back()->score()); // Going to pop the opt node //check_val(optNode_ != NULL, "ERROR: popping and optNode is not in the queue."); // if (nodes_.back() == optNode_) { // optNode_ = NULL; // numWrongAction_ = 0; // } else { // Stop it when it goes too far away if (optNode_) { if (nodes_.back() != optNode_) { ++numWrongAction_; debug("num wrong action: %d", numWrongAction_); debug("opt node: %d", optNode_->id()); if (numWrongAction_ > 100) { nodes_.pop_back(); optNode_->setScore(1000); make_heap(nodes_.begin(), nodes_.end(), compare_); assert(nodes_.front() == optNode_ && "Fail to promote optNode"); //pop_heap(nodes_.begin(), nodes_.end(), compare_); debug("promote opt node"); numWrongAction_ = 0; //optNode_ = NULL; return; } } else { optNode_ = NULL; } } nodes_.pop_back(); }
/** Retrieve the 10 most recent tweet ids in the user's news feed. Each item * in the news feed must be posted by users who the user followed or by the * user herself. Tweets must be ordered from most recent to least recent. */ vector<int> getNewsFeed(int userId) { vector<pair<Tweet *, Tweet *>> h; for (const int &u : following[userId]) { vector<Tweet> &t = tweets[u]; if (t.size() > 0) { h.emplace_back(t.data(), t.data() + t.size() - 1); } } auto &t = tweets[userId]; if (t.size() > 0) { h.emplace_back(t.data(), t.data() + t.size() - 1); } auto f = [](const pair<Tweet *, Tweet *> &x, const pair<Tweet *, Tweet *> &y) { return x.second->time > y.second->time; }; make_heap(h.begin(), h.end(), f); const int nums = 10; vector<int> result; result.reserve(nums); for (int i = 0; i < nums && !h.empty(); ++i) { pop_heap(h.begin(), h.end(), f); pair<Tweet *, Tweet *> &next = h.back(); result.push_back(next.second->id); if (next.first == next.second--) h.pop_back(); else push_heap(h.begin(), h.end(), f); } return result; }
void dijkstra (graph_t *g, int a, int b) { int i, j; a = a - 'a'; b = b - 'a'; for (i = 0; i < g->vertices_len; i++) { vertex_t *v = g->vertices[i]; v->dist = INT_MAX; v->prev = 0; v->visited = 0; } vertex_t *v = g->vertices[a]; v->dist = 0; heap_t *h = create_heap(g->vertices_len); push_heap(h, a, v->dist); while (h->len) { i = pop_heap(h); if (i == b) break; v = g->vertices[i]; v->visited = 1; for (j = 0; j < v->edges_len; j++) { edge_t *e = v->edges[j]; vertex_t *u = g->vertices[e->vertex]; if (!u->visited && v->dist + e->weight <= u->dist) { u->prev = i; u->dist = v->dist + e->weight; push_heap(h, e->vertex, u->dist); } } } }
ListNode *mergeKLists(vector<ListNode *> &lists) { if(lists.size() == 0) { return NULL; } vector<ListNode *> nodeHeap; for(int i = 0; i < lists.size(); i++) { // only push non-NULL node into vector if(lists[i] != NULL) { nodeHeap.push_back(lists[i]); } } make_heap(nodeHeap.begin(), nodeHeap.end(), cmpNode); ListNode *fakeHead = new ListNode(INT_MIN), *curr = fakeHead; while(!nodeHeap.empty()) { ListNode *tmp = nodeHeap.front(); curr->next = tmp; pop_heap(nodeHeap.begin(), nodeHeap.end(), cmpNode); // for the vector, also need to pop back // the poped elememt will move to the end of the vector nodeHeap.pop_back(); curr = curr->next; // only push non-NULL node into heap if(tmp->next != NULL) { nodeHeap.push_back(tmp->next); push_heap(nodeHeap.begin(), nodeHeap.end(), cmpNode); } } return fakeHead->next; }
void heap_sort(size_t n, int *array) { size_t i; make_heap(n, array); for (i = 0; i < n; ++i) pop_heap(n - i, array); }
Matrix *merge( Entry* buf, int *counts, int *offsets, int P, std::function<bool(const pair<int,Entry>, const pair<int,Entry>)> reverseSort ) { vector<pair<int,Entry> > next; int is[P]; for( int i = 0; i < P; i++ ) is[i] = 0; // initial population of the heap for( int i = 0; i < P; i++ ) if( counts[i] > is[i] ) { next.push_back( make_pair( i,buf[offsets[i]+is[i]] ) ); is[i]++; } make_heap(next.begin(), next.end(), reverseSort ); Matrix* ret = new Matrix; // put the first entry in the matrix if( !next.empty() ) { pop_heap(next.begin(), next.end(), reverseSort ); ret->push_back( next.back().second ); int i = next.back().first; if( counts[i] > is[i] ) { next.back().second = buf[offsets[i]+is[i]]; push_heap(next.begin(), next.end(), reverseSort ); is[i]++; } else { next.pop_back(); } } while( !next.empty() ) { pop_heap(next.begin(), next.end(), reverseSort ); if( ret->back().first.first == next.back().second.first.first && ret->back().first.second == next.back().second.first.second ) { ret->back().second += next.back().second.second; } else { ret->push_back( next.back().second ); } int i = next.back().first; if( counts[i] > is[i] ) { next.back().second = buf[offsets[i]+is[i]]; push_heap(next.begin(), next.end(), reverseSort ); is[i]++; } else { next.pop_back(); } } return ret; }
int findKthLargest(vector<int>& nums, int k) { make_heap(nums.begin(), nums.end()); for (int i = 1; i < k; ++i) { pop_heap(nums.begin(), nums.end()); nums.pop_back(); } return nums[0]; }
void sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { __STL_REQUIRES(_RandomAccessIterator, _Mutable_RandomAccessIterator); __STL_REQUIRES(typename iterator_traits<_RandomAccessIterator>::value_type, _LessThanComparable); while (__last - __first > 1) pop_heap(__first, __last--);//每次取出根节点元素,直到heap为空 }
T pop() { T temp = this->peek(); pop_heap(this->data->begin(),this->data->end(), comp); this->data->pop_back(); return temp; }
void TimerBase::heapPopMin() { ASSERT(this == timerHeap().first()); checkHeapIndex(); pop_heap(TimerHeapIterator(0), TimerHeapIterator(timerHeap().size())); checkHeapIndex(); ASSERT(this == timerHeap().last()); }
heap_entry_type pop() { // assert M_heap.size() > 0 heap_entry_type out = *(M_heap.begin()); pop_heap( M_heap.begin(), M_heap.end(), farther ); M_heap.pop_back(); return out; }
void sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { __STL_REQUIRES(_RandomAccessIterator, _Mutable_RandomAccessIterator); while (__last - __first > 1) pop_heap(__first, __last--, __comp); }
int findKthLargest(vector<int>& nums, int k) { make_heap(nums.begin(), nums.end()); while(k > 1) { pop_heap(nums.begin(), nums.end()); nums.pop_back(); k--; } return nums[0]; }
// Pop da heap, retorna uma truplafromfile, eh utilizado o cmp para verificar qual eh o menor termId que deve ser retirado. truplaFromFile Indexer::MyHeapPop() { truplaFromFile tempTrupla = truplaQueue.front(); //Essa operação irá mover o link de menor nível para o fim do vector. pop_heap(truplaQueue.begin(), truplaQueue.end(), cmp()); //Remove o último elemento do vector, o qual é a URL de menor nível; truplaQueue.pop_back(); // PriorityQueue.shrink_to_fit(); return tempTrupla; };
void TimerBase::heapPopMin() { ASSERT(this == timerHeap().first()); checkHeapIndex(); Vector<TimerBase*>& heap = timerHeap(); TimerBase** heapData = heap.data(); pop_heap(TimerHeapIterator(heapData), TimerHeapIterator(heapData + heap.size()), TimerHeapLessThanFunction()); checkHeapIndex(); ASSERT(this == timerHeap().last()); }
int main () { make_heap (numbers, numbers + 6, greater<int> ()); for (int i = 6; i >= 1; i--) { cout << numbers[0] << endl; pop_heap (numbers, numbers + i, greater<int> ()); } return 0; }
void max_heap_sort(int a[], int l) { int i; // 构造heap for (i = 1; i <= l; i++) push_heap(a, i); // 序列化 for (i = l; i > 0; i--) pop_heap(a, i); }