Advertisement
coloriot

HA_25

Sep 27th, 2024
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. // Решение K-го препятствия
  5.  
  6. using namespace std;
  7.  
  8. // Поиск абсолютного значения, чтобы не использовать cmath
  9. int my_abs(int x) {
  10.     return x >= 0 ? x : -x;
  11. }
  12.  
  13. class MaxHeap {
  14. private:
  15.     vector<int> heap;
  16.  
  17.     void siftUp(int idx) {
  18.         while (idx > 0) {
  19.             int parent = (idx - 1) / 2;
  20.             if (heap[parent] >= heap[idx]) break;
  21.             swap(heap[parent], heap[idx]);
  22.             idx = parent;
  23.         }
  24.     }
  25.  
  26.     void siftDown(int idx) {
  27.         int n = heap.size();
  28.         while (idx * 2 + 1 < n) {
  29.             int leftChild = idx * 2 + 1;
  30.             int rightChild = idx * 2 + 2;
  31.             int largest = idx;
  32.  
  33.             if (leftChild < n && heap[leftChild] > heap[largest]) {
  34.                 largest = leftChild;
  35.             }
  36.             if (rightChild < n && heap[rightChild] > heap[largest]) {
  37.                 largest = rightChild;
  38.             }
  39.             if (largest == idx) break;
  40.  
  41.             swap(heap[idx], heap[largest]);
  42.             idx = largest;
  43.         }
  44.     }
  45.  
  46. public:
  47.     MaxHeap() {}
  48.  
  49.     void push(int val) {
  50.         heap.push_back(val);
  51.         siftUp(heap.size() - 1);
  52.     }
  53.  
  54.     void pop() {
  55.         if (heap.empty()) return;
  56.         heap[0] = heap.back();
  57.         heap.pop_back();
  58.         siftDown(0);
  59.     }
  60.  
  61.     int top() {
  62.         if (!heap.empty()) return heap[0];
  63.         return -1;
  64.     }
  65.  
  66.     int size() {
  67.         return heap.size();
  68.     }
  69. };
  70.  
  71. int main() {
  72.     int n, k;
  73.     cin >> n >> k;
  74.  
  75.     MaxHeap maxHeap;
  76.     vector<int> results;
  77.  
  78.     for (int i = 0; i < n; ++i) {
  79.         int x, y;
  80.         cin >> x >> y;
  81.  
  82.         int dist = my_abs(x) + my_abs(y);
  83.         if (maxHeap.size() < k) {
  84.             maxHeap.push(dist);
  85.         } else if (dist < maxHeap.top()) {
  86.             maxHeap.pop();
  87.             maxHeap.push(dist);
  88.         }
  89.  
  90.         if (maxHeap.size() < k) {
  91.             results.push_back(-1);
  92.         } else {
  93.             results.push_back(maxHeap.top());
  94.         }
  95.     }
  96.  
  97.     for (int i = 0; i < results.size(); ++i) {
  98.         cout << results[i] << endl;
  99.     }
  100.  
  101.     return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement