void RunOperation(char operation, const std::vector<std::string>& arguments, MinHeap<T>& heap, std::ostream& file) { if(operation == 'I') { auto value = ToInt(arguments[1]); heap.Insert(value); } else if(operation == 'D') { auto value = ToInt(arguments[1]); heap.Delete(value); } else if(operation == 'C') { auto oldValue = ToInt(arguments[1]); auto newValue = ToInt(arguments[2]); heap.Change(oldValue, newValue); } else if(operation == 'P') { heap.PrintPostOrder(file); file << std::endl; } }
void pushPopTest() { MinHeap minHeap; std::vector<Pipe> data; data.push_back(std::make_pair(9, 1.0)); data.push_back(std::make_pair(8, 2.0)); data.push_back(std::make_pair(7, 3.0)); data.push_back(std::make_pair(6, 4.0)); data.push_back(std::make_pair(5, 5.0)); data.push_back(std::make_pair(4, 6.0)); data.push_back(std::make_pair(3, 7.0)); data.push_back(std::make_pair(2, 8.0)); data.push_back(std::make_pair(1, 9.0)); std::random_shuffle(data.begin(), data.end()); for (auto const& pipe : data) minHeap.push(pipe); int sum = 0; int last = INT_MAX; while (!minHeap.empty()) { const auto& pipe = minHeap.top(); sum += pipe.first; if (pipe.first > last) throw std::runtime_error("The output of the heap is not in the right order."); last = pipe.first; minHeap.pop(); } if (sum != 45) throw std::runtime_error("The sum of the heap output is incorrect."); }
float handleQuery(float prev,int next,MaxHeap& maxheap,MinHeap& minheap){ if(next>prev){ if(minheap.n>maxheap.n){ maxheap.insert(minheap.extractMin()); } minheap.insert(next); }else{ if(maxheap.n>minheap.n){ minheap.insert(maxheap.extractMax()); } maxheap.insert(next); } if((maxheap.n+minheap.n)%2==0){ float l = maxheap.a[0]; float r = minheap.a[0]; return (l+r)/2; }else{ if(maxheap.n>minheap.n) return maxheap.a[0]; return minheap.a[0]; } }
void dijkstra(int gf, int gc) { MinHeap H; init(H); while(not H.empty()) { Node current = H.top(); H.pop(); if(current.f == gf and current.c == gc) return; visited[current.f][current.c] = true; for (int i = 0; i < 4; ++i) { int nf = current.f + dx[i]; int nc = current.c + dy[i]; if ((nf >= 0 and nf < N) and (nc >= 0 and nc < M) and not visited[nf][nc]) { if(range[nf][nc] > maze[nf][nc] + range[current.f][current.c]) { range[nf][nc] = maze[nf][nc] + range[current.f][current.c]; H.push(Node(nf, nc, range[nf][nc])); } } } } }
bool test_minheap() { srand(time(NULL)); MinHeap<long long> minheap; int lim = 1000; minheap.insert(12);minheap.insert(15);minheap.insert(11);minheap.insert(1);minheap.insert(12); if(DEBUG)printf("heap find (15) = %s\n",minheap.find(15)?"TRUE":"FALSE"); for(long long i = 0; i < lim; i++) { minheap.insert(rand() % lim + (rand() < (RAND_MAX/8)?-lim/10:lim)); } if(DEBUG) { printf("First 15 of 1000 sorted is = ["); for(long long i = 0; i < 15; i++) { printf("%lld,", minheap.remove_min()); } printf("...]\n"); printf("get nth = %lld\n", minheap.get_nth(15)); } MinHeap<int> heap2; for(int i = 0; i < 1000; i ++) { heap2.insert(i); while(heap2.size()>50)heap2.remove_min(); } return true; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ if( nrhs!=4 ) mexErrMsgTxt("This function requires 3 arguments\n"); if( !mxIsNumeric(prhs[0]) ) mexErrMsgTxt("parameter 1 missing!\n"); if( !mxIsNumeric(prhs[1]) ) mexErrMsgTxt("parameter 2 missing!\n"); if( !mxIsNumeric(prhs[2]) ) mexErrMsgTxt("parameter 3 missing!\n"); if( !mxIsNumeric(prhs[3]) ) mexErrMsgTxt("parameter 3 missing!\n"); // retrieve the heap MinHeap<double>* heap; retrieve_heap( prhs[0], heap); // retrieve the parameters int index; retrieve_index( prhs[1], index ); double key1; retrieve_cost( prhs[2], key1); double key2; retrieve_cost( prhs[3], key2); // push in the PQ try{ heap->push( key1, key2, index-1 ); } catch( InvalidKeyIncreaseException exc ){ return; } // return control to matlab return; }
vector<int> closestKValues(TreeNode* root, double target, int k) { dfs(root, target); vector<int> retval; while (!mheap.empty() && retval.size() < k) { Cand cand = mheap.top(); mheap.pop(); retval.push_back(cand.second); } return retval; }
void heapSortUsingMinHeap(T arr[], int n){ MinHeap<T> minheap = MinHeap<T>(n); for( int i = 0 ; i < n ; i ++ ) minheap.insert(arr[i]); for( int i = 0 ; i < n ; i ++ ) arr[i] = minheap.extractMin(); }
int main() { int array[] = {10, 4, 5, 6, 9, 1, 7}; MinHeap *minHeap = new MinHeap(array, 6); /* * General heap functions */ cout << "Min: " << minHeap->get_min() << endl; return 0; }
void heapSortDesc(int array[], int arrLength) { MinHeap h = buildMinHeap(array, arrLength); int temp = h.size; for(int i = arrLength-1; i > 0; i--) { swap(&array[0], &array[i]); h.size -= 1; h.heapify(0); } h.size = temp; h.printHeap(); }
int main() { MinHeap<int> minHeap; MaxHeap<int> maxHeap; minHeap.push(10); minHeap.push(5); minHeap.push(12); minHeap.push(3); minHeap.push(4); maxHeap.push(10); maxHeap.push(5); maxHeap.push(12); maxHeap.push(3); maxHeap.push(4); while ( !minHeap.empty()) { std::cout << minHeap.top() << " "; minHeap.pop(); } std::cout << std::endl; while ( !maxHeap.empty()) { std::cout << maxHeap.top() << " "; maxHeap.pop(); } std::cout << std::endl; }
int dijkstra(int src,int ddest) { int dist[V]; mH.init(V); for(int i=0;i<V;i++) dist[i]=INT_MAX; dist[src] = 0; mH.decreaseKey(src, dist[src]); while (mH.getsize()>0) { mH.extractMin(); int u = mH.getminv(); dist[u]=mH.getmindist(); if(u==ddest) return dist[u]; listnode* tt = graph[u]; while (tt != NULL) { int v = tt->dest; if (mH.ispresent(v) && dist[u]!=INT_MAX && (tt->cost + dist[u])<(dist[v])) { dist[v] = (dist[u]+tt->cost); mH.decreaseKey(v, dist[v]); } tt = tt->next; } } return dist[ddest]; }
int main(int argc,char*argv[]) { if(argc !=3) { cout<<"Error Incorrect Syntax"<<endl; } else { string inputFile = argv[1]; string outputFile = argv[2]; MinHeap minHeap; ifstream in; int noOfArgs = 0,jobId,priority,duration; string fileLine; in.open(inputFile.c_str()); in >> noOfArgs; //dout<<" total args is "<<noOfArgs<<endl; //while (!in.eof()) { for(int i=0;i<noOfArgs;i++) { in >>jobId>>priority>>duration; //cout<<" arg "<<jobId<<" "<<priority<<" "<<duration<<endl; //cout<<"insertingggggggg......"<<endl; //dout<<" i is "<< HeapNode *heapNode = new HeapNode(jobId,priority,duration); minHeap.insertHeapNode(heapNode); //dout<<" heap is ==="<<endl; //preorder(); //dout<<" heap print over"<<endl; } //} cout<<"Insert over"<<endl; minHeap.debug_image("debug_after_insert"); ofstream myfile; myfile.open (outputFile.c_str()); if(!in.eof()) { char ch; in>>ch; if(ch == 'P'){ string str = minHeap.preorderString(); cout<<"preorderString is "<< str<<endl; myfile << str<<"\n"; } } string hs = heapSort(minHeap); myfile << hs; myfile.close(); in.close(); //dout<<"At last"<<endl; //preorder(); }
void dfs(TreeNode* root, double target) { if (root == NULL) return; double mydiff = absDiff(root->val, target); mheap.push(make_pair(mydiff, root->val)); dfs(root->left, target); dfs(root->right, target); }
/* Creates the Huffman tree reusing the given HuffmanNodes. nodes: an array of HuffmanNode* length: the length of nodes array returns: the pointer to the root of the huffman tree */ HuffmanNode *genHuffmanTree(HuffmanNode **nodes, int length) { MinHeap min = MinHeap(nodes, length);//create the array with minHeap constructor while (min.heapSize > 1)//it will run until the array has size one { HuffmanNode *L, *R;//we make the nodes for left and right L = min.extractMin();//we extract the min from the heap and assign it to left R = min.extractMin();//we do the same for the right HuffmanNode *internal = new HuffmanNode(L->frequency + R->frequency, L, R);//we create an internal node with the sum of the frequency left and right. //we also assign left and right to be child of internal min.insert(internal);//we insert the internal node back into the heap } return min.extractMin();//we extract the min but since we only got one element left in the array, this should be the root. }
void RetManager::retrieval(unsigned retNum) { retDocID = new unsigned[retNum]; retDocScore = new float[retNum]; BlockManager *BM = new BlockManager(r,num,retNum); int i,l,n; while((curDoc = findNextDoc())!=MaxNum) { for(i=0;i<num;i++) if(r[i].curDocID<curDoc) r[i].curDocID = moveToDoc(i,curDoc); BM->putDoc(curDoc,r); } const float okapiK1=1.2; const float okapiB=0.2; BlockNode ** blockList = BM->getBlockList(); vector<pair<unsigned,unsigned*> >::iterator it; for(i=0;i<BM->getBlockNum();i++) { n=blockList[i]->termScores.size(); int theSize = blockList[i]->content->record.size(); if(theSize+retN>retNum) theSize = retNum-retN; if(theSize==0) continue; topDocs = new MinHeap(theSize); for(it=blockList[i]->content->record.begin();it!=blockList[i]->content->record.end();it++) { unsigned* theTF = it->second; float score = 0; float docLength = theIndex -> getDocLength(it->first); for(l=0;l<n;l++) { float tf = theTF[l]; float weight = ((okapiK1+1.0)*tf) / (okapiK1*(1.0-okapiB+okapiB*docLength/theIndex->docLengthAvg)+tf); score+=weight*blockList[i]->termScores[l]; } if(score > topDocs->smallest) topDocs->push(it->first,score); evalCounter++; } for(l=retN+theSize-1;l>=retN;l--) { retDocID[l] = topDocs->pop(retDocScore[l]); } retN+=theSize; delete(topDocs); } delete(BM); }
string heapSort(MinHeap minHeap){ ostringstream oss(""); HeapNode*ptr = minHeap.extractMin(); while(ptr !=NULL) { oss<<ptr->getJobId(); oss<<" "; oss<<ptr->getPriority(); oss<<" "; oss<<ptr->getDuration(); oss<<" "; oss<<endl; ptr = minHeap.extractMin(); } cout<<"heap sort over"<<endl; cout <<oss.str()<<endl; return oss.str(); }
double findMedian() { /* Three cases: since abs(max_heap_.size() - min_heap_.size()) <= 1 denote x as min(max_heap_.size() - min_heap_.size()) 1) size x and x means even elements so it just the average of max of first heap and min of second heap 2) size x + 1 and x means odd elements so the max of the first heap is the median element 3) size x and x + 1 means odd elements so the min of the second heap is the median element */ if (max_heap_.size() == min_heap_.size()) { return (double)(max_heap_.top() + min_heap_.top()) / 2.0; } else if (max_heap_.size() > min_heap_.size()) { return max_heap_.top(); } else { return min_heap_.top(); } }
int lessMoney(Arr& data) { int cost = 0; MinHeap result; for (auto e : data) result.push(e); while (result.size() != 1) { auto tmp = result.top(); result.pop(); tmp += result.top(); result.pop(); result.push(tmp); } return result.top(); }
void RetManager::retrieval(unsigned retNum) { retDocID = new unsigned[retNum]; retDocScore = new float[retNum]; topDocs = new MinHeap(retNum); DecisionTree *DT = new DecisionTree(r,num,retNum); while((curDoc = findNextDoc())!=MaxNum) { DT->putDoc(curDoc,r); //float score = grade(); //if(score > topDocs->smallest) topDocs->push(curDoc,score); } int i,l,n; const float okapiK1=1.2; const float okapiB=0.2; DecisionTreeNode **blockList = DT->getBlockList(); vector<pair<unsigned,unsigned*> >::iterator it; for(i=0;i<DT->getBlockNum();i++) { n=blockList[i]->termScores.size(); for(it=blockList[i]->content->record.begin();it!=blockList[i]->content->record.end();it++) { unsigned* theTF=it->second; float score=0; float docLength = theIndex -> getDocLength(it->first); for(l=0;l<n;l++) { float tf = theTF[l]; float weight = ((okapiK1+1.0)*tf) / (okapiK1*(1.0-okapiB+okapiB*docLength/theIndex->docLengthAvg)+tf); score+=weight*blockList[i]->termScores[l]; } if(score > topDocs->smallest) topDocs->push(it->first,score); evalCounter++; } } retN = topDocs->n; for(i=retN-1;i>=0;i--) { retDocID[i] = topDocs->pop(retDocScore[i]); } delete(topDocs); delete(DT); }
int main() { int ar[]={56,34,90,23,18,100,89,10,45,78,65}; int n = sizeof(ar)/sizeof(ar[0]); MinHeap<int> mh; for(int i = 0;i<n;++i) { mh.Insert(ar[i]); } int x; while(mh.Remove(x)) { std::cout << x <<" "; } std::cout << std::endl; return 0; }
void init(MinHeap &H) { H.push(Node(0, 0, maze[0][0])); for (int i = 0; i < MAX; ++i) { memset(visited[i], false, sizeof(visited[i])); fill(range[i], range[i] + MAX, INF); } range[0][0] = maze[0][0]; }
Graph<T>& Graph<T>::Prim( int key ) { assert( Adjacent.size() > 0 ); MinHeap<int> Heap; int V; for( int i = 0; i < Adjacent[key].size(); i++ ) { for( int j = 0; j < Adjacent[key][i].first->Neighbors.size(); j++ ) { V++; } } Graph<T> MST; Node<T>* current = Adjacent[key][0].first; for( int i = 0; i < Adjacent[key].size(); i++ ) { if( !current->visited ) { current->visited = true; MST.AddNode( current ); for( int j = 0; j < current->Neighbors.size(); j++ ) { Heap.push( current->Neighbors[j].second ); } int min = Heap.top(); for( int j = 0; j < current->Neighbors.size(); j++ ) { if( min == current->Neighbors[j].second ) { //MST.AddNode( current->Neighbors[j].first, min ); current = current->Neighbors[j].first; break; } } while( !Heap.empty() ) { Heap.pop(); } } } return &MST; }
int* minimumSpanningTree() { int* parents = new int[size]; bool* seen = new bool[size]; int* weights = new int[size]; MinHeap* q = new MinHeap(); for (size_t i = 0; i < size; i ++) { parents[i] = 0; weights[i] = MAX_INT; seen[i] = false; } weights[0] = 0; parents[0] = -1; q->insert(0, 0); for (size_t count = 1 ; count < size; count++) { int minIndex = q->extractMin(); seen[minIndex] = true; for(size_t i = 0; i < size; i++) { int edgeCost = getEdge(minIndex, i); if (edgeCost <= 0 || seen[i]) { continue; } if (edgeCost < weights[i]) { weights[i] = edgeCost; q->insertOrDecrease(i, edgeCost); parents[i] = minIndex; } } } for (size_t i = 1; i < size; i++) { cout << i << " - " << parents[i] << " (" << weights[i] << ")" << endl; } delete[] weights; delete[] seen; delete q; return parents; }
DoubleLinkedList<GraphNode *> Dijkstra(GraphNode *Start, GraphNode * End) { Map<GraphNode *, DijkstraHelperNode *> NodeHelperMap; DoubleLinkedList<DijkstraHelperNode *> Visited; MinHeap<DijkstraHelperNode *> OpenHeap; DijkstraHelperNode *NewHelper = new DijkstraHelperNode(); NewHelper->m_Node = Start; NewHelper->m_Cost = 0; NodeHelperMap.Insert(Start, NewHelper); OpenHeap.Insert(NewHelper); while(!OpenHeap.IsEmpty()) { DijkstraHelperNode *CurrentHelperNode = OpenHeap.PopTop(); assert(CurrentHelperNode != NULL); GraphNode *CurrentGraphNode = CurrentHelperNode->m_Node; assert(CurrentGraphNode != NULL); DoubleLinkedList<GraphEdge *> *CurrendEdges = CurrentGraphNode->GetEdges(); DoubleListNode<GraphEdge *> *CurrentEdge = CurrentEdges.GetHead(); while(CurrentEdge != NULL) { GraphNode *OtherNode = CurrentEdge->m_End; if(OtherNode == CurrentGraphNode) { OtherNode = CurrentEdge->m_Start; } assert(OtherNode != CurrentGraphNode); DijkstraHelperNode *NodeHelper = NodeHelperMap.GetValue(OtherNode); if(NodeHelper == NULL) { NodeHelper = new DijkstraHelperNode(); NodeHelper->m_Node = OtherNode; NodeHelperMap.Insert(OtherNode, NodeHelper); OpenHeap.Insert(NodeHelper); } int CostToNode = CurrentHelperNode->m_Cost + CurrentEdge->m_Cost; if(CostToNode < NodeHelper->m_Cost) { NodeHelper->m_Cost = CostToNode; NodeHelper->m_Previous = CurrentGraphNode; OpenHeap.Update(NodeHelper); } if(OtherNode == End) { break; } } } DoubleLinkedList<GraphNode *> Path; DijkstraHelperNode *EndHelper = NodeHelperMap.GetValue(End); if(EndHelper != NULL) { DijkstraHelperNode *CurrentHelper = EndHelper; while(CurrentHelper != NULL) { Path.AddFront(CurrentHelper->m_Node); CurrentHelper = CurrentHelper->m_Previous; } } }
unsigned int min_distance(const AdjacencyList& graph) { vector<unsigned int> distances(graph.size(), infinity); MinHeap cut; distances[0] = 0; cut.push(make_pair(0, 0)); while (!cut.empty()) { unsigned int closest = cut.top().second; unsigned int to_closest = cut.top().first; cut.pop(); if (distances[closest] < to_closest) { continue; } for (unsigned int i = 0; i < graph[closest].size(); ++i) { unsigned int adjacent = graph[closest][i].first; unsigned int distance = graph[closest][i].second; if (distances[adjacent] > to_closest + distance) { distances[adjacent] = to_closest + distance; cut.push(make_pair(distances[adjacent], adjacent)); } } } return distances.back(); }
HuffmanTree::HuffmanTree() { MinHeap<HufTreeNodePtr> M; int calcu[26]={0};//0->a HufTreeNode *p; HufTreeNodePtr ptr; char c[100]; cout<<"请输入以#结尾的一串小写英文序列"<<endl; cin>>c; int i=0; while (c[i]!='#') { calcu[c[i]-'a']++; i++; } for (int i=0;i<26;i++) { if (calcu[i]==0) continue; cout<<calcu[i]<<' '<<(char)('a'+i)<<endl;///////////////////////////////// p=new HufTreeNode(calcu[i],'a'+i); ptr.p=p; M.Put(ptr); } HufTreeNodePtr ptra,ptrb; while (M.Length()>1) { ptrb=M.Remove(); ptra=M.Remove(); ptr.p=new HufTreeNode(ptra.p->weight+ptrb.p->weight); ptr.p->leftChild=ptra.p; ptr.p->rightChild=ptrb.p; M.Put(ptr); } root=M.Front().p; }
int MedianMaintenance(MaxHeap<int>& heapLow, MinHeap<int>& heapHigh, int elem) { if(heapLow.size() == heapHigh.size()) { if(heapLow.size()) { if(elem > heapHigh.get_min()) { heapHigh.insert(elem); heapLow.insert(heapHigh.extract_min()); } else heapLow.insert(elem); } else heapLow.insert(elem); } else { if(elem < heapLow.get_max()) { heapLow.insert(elem); heapHigh.insert(heapLow.extract_max()); } else heapHigh.insert(elem); } return heapLow.get_max(); }
ListNode *mergeKLists(vector<ListNode *> &lists) { if( lists.size() < 1 ) return NULL; MinHeap minHeap; for( int i = 0; i < lists.size(); ++i ) { if( lists[i] != NULL ) minHeap.push( lists[i] ); } if( minHeap.size() == 0 ) return NULL; ListNode* head = minHeap.top(); ListNode* curr = head; minHeap.pop(); while( minHeap.size() ) { if( curr->next ) minHeap.push(curr->next); curr->next = minHeap.top(); curr = curr->next; minHeap.pop(); } return head; }
int main() { MaxHeap<int> mh; mh.Push(3); mh.Push(4); mh.Push(8); mh.Push(1); mh.Push(9); for (int i = 0; i < mh.Size(); ++i) { std::cout << mh[i] << " "; } std::cout << std::endl; std::cout << "==========" << std::endl; std::cout << mh.Pop() << std::endl; for (int i = 0; i < mh.Size(); ++i) { std::cout << mh[i] << " "; } std::cout << std::endl; std::cout << "==========" << std::endl; MinHeap<int> minH; minH.Push(3); minH.Push(4); minH.Push(8); minH.Push(1); minH.Push(9); for (int i = 0; i < minH.Size(); ++i) { std::cout << minH[i] << " "; } std::cout << std::endl; std::cout << minH.Pop() << std::endl; for (int i = 0; i < minH.Size(); ++i) { std::cout << minH[i] << " "; } std::cout << std::endl; std::cout << "---" << std::endl; std::cout << re(3, 4) << std::endl; std::vector<int> A{3, 6, 5}; A.pop_back(); for (auto &it : A) { std::cout << it << std::endl; } std::cout << A.front() << "," << A.size() << std::endl; return 0; }