Cod sursa(job #2907815)

Utilizator NefelibataAnton Marius Alexandru Nefelibata Data 31 mai 2022 17:40:32
Problema Heapuri cu reuniune Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

void print(vector<int> &v)
{
    for (long unsigned int i = 0; i < v.size(); ++i) {
        cout<<v[i]<<" ";
    }
    cout << "\n";
}
void swap(int *x, int *y)
{
    int t = *y;
    *y = *x;
    *x = t;
}
void heapify(vector<int> &v, int i)
{
    int maxx = i;
    long unsigned int l = 2 * i + 1;
    long unsigned int r = 2 * i + 2;
    if (l < v.size() && v[l] > v[maxx]) {
        maxx = l;
    }
    if (r < v.size() && v[r] > v[maxx]) {
        maxx = r;
    }
    if (maxx != i)
    {
        swap(&v[i], &v[maxx]);
        heapify(v, maxx);
    }
}
void push(vector<int> &v, int x)
{
    v.push_back(x);
    if (v.size() == 0) {
        return;
    } else {
        for (int i = v.size() - 1; i >= 0; --i)
        {
          heapify(v, i);
        }
    }
}
int pop(vector<int> &v)
{
    int x = v.front();
    swap(&v[0], &v[v.size() - 1]);
    v.pop_back();
    for (int i = v.size() / 2 - 1; i >= 0; --i) {
        heapify(v, i);
    }
    return x;
}
void merge_heap(vector<int> &a, vector<int> &b) {
    while (!b.empty()) {
        int x = pop(b);
        push(a, x);
    }
}

int main()
{
    ifstream f("mergeheap.in");
    ofstream o("mergeheap.out");
    int n, q;
    f>>n>>q;

    vector<int> v[n+5];
    for (int i = 0; i < q; ++i) {
        int x, y, z;
        f>>x;
        if (x == 1) {
            f>>y>>z;
            push(v[y], z);
        } else if (x == 2) {
            f>>y;
            o<<pop(v[y])<<"\n";
        } else {
            f>>y>>z;
            merge_heap(v[y], v[z]);
        }
    }
}