Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 1
- #include <iostream>
- #include <vector>
- using namespace std;
- int n;
- vector<int> v;
- void make_piramyde(int root, int b) {
- int child;
- while (root * 2 <= b) {
- if (root * 2 == b || v[root * 2 + 1] < v[root * 2])
- child = root * 2;
- else
- child = root * 2 + 1;
- if (v[root] < v[child]) {
- swap(v[root], v[child]);
- root = child;
- } else
- break;
- }
- }
- int main() {
- cin >> n;
- v.resize(n);
- for (int i = 0; i < n; i++)
- cin >> v[i];
- for (int i = n / 2; i >= 0; i--)
- make_piramyde(i, n - 1);
- for (int i = n - 1; i >= 1; i--) {
- swap(v[0], v[i]);
- make_piramyde(0, i - 1);
- }
- for (int i = 0; i < n; i++)
- cout << v[i] << ' ';
- }
- //2
- #include <iostream>
- #include <vector>
- using namespace std;
- int n;
- vector<int> heap;
- int t, command;
- void heapify(int i) {
- int l = 2 * i + 1, r = 2 * i + 2;
- if (r < n && heap[i] < heap[r]) {
- swap(heap[i], heap[r]);
- heapify(r);
- }
- if (l < n && heap[i] < heap[l]) {
- swap(heap[i], heap[l]);
- heapify(l);
- }
- }
- int main() {
- cin >> t;
- heap.resize(1000000);
- n = 0;
- for (int i = 0; i < t; i++) {
- cin >> command;
- if (command == 0) {
- int value, current = n, pred = (n - 1) / 2;
- cin >> value;
- heap[current] = value;
- while (pred >= 0 && current > 0) {
- if (heap[current] > heap[pred])
- swap(heap[current], heap[pred]);
- current = pred;
- pred = (current - 1) / 2;
- }
- n++;
- } else {
- cout << heap[0] << endl;
- n--;
- heap[0] = heap[n];
- heapify(0);
- }
- }
- }
Add Comment
Please, Sign In to add comment