跳到正文

算法·理论

堆

ouyanglei约 14 分钟
原文
文章信息与版本

文章信息

发布
2025年6月1日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 14 分钟

版本

  1. v1当前
C++
// 堆排序 Heap Sort P1177
#include <iostream>
using namespace std;
#define MAXN 100002

int arr[MAXN];

// 调整以root为根的子树为大顶堆(n为堆的大小)
void heapify(int arr[], int n, int root) {
  int largest = root;
  int left = 2 * root, right = 2 * root + 1;
  
  if (left <= n && arr[left] > arr[largest]) 
    largest = left;
  if (right <= n && arr[right] > arr[largest])
    largest = right;
  
  if (largest != root) {
    swap(arr[root], arr[largest]);
    heapify(arr, n, largest); // 递归调整被交换的子树
  }
}

void heap_sort(int arr[], int n) {
  // 构建初始大顶堆(从最后一个非叶子节点开始)
  for (int i = n/2; i >= 1; i--)
    heapify(arr, n, i);
  
  // 堆顶元素与末尾交换,交换后的末尾元素就绪
  for (int i = n; i > 1; i--) {
    swap(arr[1], arr[i]);  // 堆顶与末尾交换
    heapify(arr, i-1, 1);  // 调整剩余元素为堆
  }
}

int main() {
  int n; cin >> n;
  for (int i= 1; i <= n; i++) {
    cin >> arr[i];
  }
  heap_sort(arr, n);
  for (int i = 1; i <= n; i++) cout << arr[i] << " ";
  return 0;
}

C++
// P3378
#include <iostream>
#include <queue>
using namespace std;

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  int n; cin >> n;
  priority_queue<int,vector<int>,greater<int>> min_heap;
  while (n--) {
    int op; cin >> op;
    switch(op) {
    case 1:
      int x; cin >> x;
      min_heap.push(x);
      break;
    case 2:
      cout << min_heap.top() << endl;
      break;
    case 3:
      min_heap.pop();
    }
  }
  return 0;
}

C++
// P1090 [NOIP 2004 提高组] 合并果子
#include <iostream>
#include <queue>
using namespace std;

int main() {
  int n; cin >> n;
  
  // 将全部果子压入最小堆
  priority_queue<int, vector<int>, greater<int>> min_heap;  // 最小堆(小根堆)
  while (n--) {
    int val; cin >> val;
    min_heap.push(val);  // 初始化堆:O(n) 时间
  }
  
  long long ans = 0;  // 防止整数溢出(重要!)
  while (min_heap.size() > 1) {  // 直到只剩一堆
    int a = min_heap.top(); min_heap.pop();
    int b = min_heap.top(); min_heap.pop();
    
    ans += a + b; 
    min_heap.push(a + b);  // 将新堆放回堆中
  }
  
  cout << ans;
  return 0;
}

C++
// P1168 中位数
#include <iostream>
#include <queue>
using namespace std;

int main() {
  int n; cin >> n;
  
  // 定义两个堆:大根堆存较小的一半,小根堆存较大的一半
  priority_queue<int> max_heap;  // 默认最大堆
  priority_queue<int, vector<int>, greater<int>> min_heap;  // 最小堆
  
  for (int i = 1; i <= n; ++i) {  // 注意从 1 开始计数
    int x; cin >> x;
    
    // 插入规则
    if (max_heap.empty() || x <= max_heap.top()) {
      max_heap.push(x);
    } else {
      min_heap.push(x);
    }
    
    // 平衡调整(关键步骤)
    // 情况1:大根堆元素过多
    if (max_heap.size() > min_heap.size() + 1) {
      min_heap.push(max_heap.top());
      max_heap.pop();
    }
    // 情况2:小根堆元素反超
    if (min_heap.size() > max_heap.size()) {
      max_heap.push(min_heap.top());
      min_heap.pop();
    }
    
    // 奇数步输出中位数
    if (i % 2 == 1) {
      cout << max_heap.top() << endl;
    }
  }
  return 0;
}

C++
// P2278
#include <iostream>
#include <queue>
using namespace std;

// 进程结构体:id为进程号,arrive_time为到达时间,exec_time为执行时长,priority为优先级
struct Process {
  int id, arrive_time, exec_time, priority;
  // 优先队列排序规则:优先级高的在前,同优先级则到达时间早的在前
  bool operator < (const Process &other) const {
    if (priority == other.priority) 
      return arrive_time > other.arrive_time;  // 小顶堆(到达时间早的优先)
    return priority < other.priority;  // 大顶堆(优先级高的优先)
  }
};

int main() {
  priority_queue<Process> ready_queue;  // 就绪队列(按优先级排序)
  long long current_time = 0;  // 当前系统时间
  
  Process current_process;
  while (cin >> current_process.id >> current_process.arrive_time
         >> current_process.exec_time >> current_process.priority) {
    // 处理所有能在当前进程到达前完成的进程
    while (!ready_queue.empty() && 
      current_time + ready_queue.top().exec_time <= current_process.arrive_time) {
      Process top_process = ready_queue.top(); ready_queue.pop();
      current_time += top_process.exec_time;
      cout << top_process.id << ' ' << current_time << endl;
    }
    
    // 若队列非空,说明当前有未完成的进程,需要竞争
    if (!ready_queue.empty()) {
      // 将当前正在运行的进程加入就绪队列,参与竞争
      Process running_process = ready_queue.top(); ready_queue.pop();
      running_process.exec_time -= (current_process.arrive_time - current_time);
      ready_queue.push(running_process);
    }
    
    // 将当前到达的进程加入就绪队列,参与竞争
    ready_queue.push(current_process);
    current_time = current_process.arrive_time;
  }
  
  // 处理所有剩余未完成的进程
  while (!ready_queue.empty()) {
    Process remaining_process = ready_queue.top(); ready_queue.pop();
    current_time += remaining_process.exec_time;
    cout << remaining_process.id << ' ' << current_time << endl;
  }
  return 0;
}

C++
// P1923 【深基9.例4】求第 k 小的数
#include <iostream>
#include <queue>
using namespace std;

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  int n, k; cin >> n >> k;
  
  priority_queue<int> max_heap; // 最大堆,堆顶是当前第k小的数
  for (int i = 0; i < n; i++) {
    int x; cin >> x;
    if (max_heap.size() <= k) {
      max_heap.push(x);
    } else if (x < max_heap.top()) {
      max_heap.pop();
      max_heap.push(x);
    }
  }
  cout << max_heap.top() << endl;
  return 0;
}

C++
// P1801 黑匣子
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
#define MAXN 200002

int add[MAXN], get[MAXN];

int main() {
  int m, n, k = 1;
  cin >> m >> n;
  
  priority_queue<int> max_heap;  // 存储前k小元素(最大堆)
  priority_queue<int, vector<int>, greater<int>> min_heap;  // 存储剩余元素
  
  for (int i = 1; i <= m; ++i) cin >> add[i];
  for (int i = 1; i <= n; ++i) cin >> get[i];
  
  int add_ptr = 1, get_ptr = 1;  // 双指针处理操作序列
  
  while (get_ptr <= n) {
    // 执行插入操作直到到达当前查询点
    while (add_ptr <= m && add_ptr <= get[get_ptr]) {
      int x = add[add_ptr++];
      
      // 插入规则:若x可加入前k小候选区
      if (max_heap.empty() || x <= max_heap.top()) {
        max_heap.push(x);
      } else {
        min_heap.push(x);
      }
      
      // 调整:保证max_heap大小不超过当前k
      while (max_heap.size() > k) {
        min_heap.push(max_heap.top());
        max_heap.pop();
      }
    }
    
    // 调整到max_heap大小恰好为k
    while (max_heap.size() < k) {
      max_heap.push(min_heap.top());
      min_heap.pop();
    }
    
    // 输出结果并更新k
    cout << max_heap.top() << endl;
    k++; get_ptr++;
  }
  
  return 0;
}

C++
// P1631
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define MAXN 100002

int arr[MAXN], brr[MAXN];

struct Node {
  int i;    // A的索引
  int j;    // B的索引
  int sum;  // A[i] + B[j]
  bool operator > (const Node& oth) const { 
    return sum > oth.sum;  // 最小堆
  }
};

int main() {
  int n; cin >> n;
  for (int i = 1; i <= n; i++) cin >> arr[i];
  for (int i = 1; i <= n; i++) cin >> brr[i];
  
  priority_queue<Node, vector<Node>, greater<Node>> min_heap;
  
  // 初始化:每个A[i] + B[1]
  for (int i = 1; i <= n; i++) {
    min_heap.push(Node({i,1,arr[i]+brr[1]}));
  }
  
  // 取出 n 次
  for (int cnt = 1; cnt <= n; cnt++) {
    Node cur = min_heap.top(); min_heap.pop();
    cout << cur.sum << " ";
    
    // 将A[i]与B的下一个元素相加
    if (cur.j+1 <= n) {
      min_heap.push(Node({cur.i, cur.j+1, arr[cur.i]+brr[cur.j+1]}));
    }
  }
  return 0;
}

原文