Ejemplo n.º 1
0
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;
}
double greedyKnapsack(knapsack &k){
	MaxHeap<float, int>* heap = new MaxHeap<float, int>(&compare);
	for(int counter = 0; counter < k.getNumObjects(); counter++){
		double key = (double) k.getValue(counter) / k.getCost(counter);
		heap->add(key, counter);
	}
	while(! heap->empty()){
		int next = heap->extractMaxHeapMaximum();
		if(k.getCost(next) + k.getCurrentCost() <= k.getCostBound()){
			k.select(next);
		}
	}
	return k.getCurrentValue();
}
  void addNum(int num) {
    if (max_heap_.empty()) {
      max_heap_.push(num);
    } else {
      if (num > max_heap_.top()) {
        min_heap_.push(num);
      } else {
        max_heap_.push(num);
      }

      // Maintain abs(max_heap_.size() - min_heap_.size()) <= 1
      if (max_heap_.size() > min_heap_.size() + 1) {  // max_heap_ too large
        min_heap_.push(max_heap_.top());
        max_heap_.pop();
      } else if (min_heap_.size() >
                 max_heap_.size() + 1) {  // min_heap_ too large
        max_heap_.push(min_heap_.top());
        min_heap_.pop();
      }
    }
  }