大根堆/小根堆

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <random>

#include "util.h"

using namespace std;

struct Point {
  int x, y;
  // priority_queue<Point> 大根堆需要重载小于号
  bool operator<(const Point& rhs) const {
    if (x != rhs.x) return x < rhs.x;
    return y < rhs.y;
  }
  // priority_queue<Point, vector<Point>, greater<>> hp2; 小根堆需要重载大于号
  bool operator>(const Point& rhs) const {
    if (x != rhs.x) return x > rhs.x;
    return y > rhs.y;
  }
};

int main() {
  priority_queue<Point> hp1;
  priority_queue<Point, vector<Point>, greater<>> hp2;
  for (int i = 0; i < 10; i++) {
    int x = RandomGenerator::randNum(1, 10), y = RandomGenerator::randNum(1, 10);
    std::cout << x << ' ' << y << '\n';
    hp1.emplace(x, y);
    hp2.emplace(x, y);
  }
  // 大根堆
  while (!hp1.empty()) {
    auto tt = hp1.top();
    hp1.pop();
    std::cout << tt.x << ' ' << tt.y << '\n';
  }
  // 小根堆
  while (!hp2.empty()) {
    auto tt = hp2.top();
    hp2.pop();
    std::cout << tt.x << ' ' << tt.y << '\n';
  }
}

posted @ 2023-10-29 19:39  hacker_dvd  阅读(46)  评论(0)    收藏  举报