Cod sursa(job #2624864)

Utilizator CraniXortDumitrescul Eduard CraniXort Data 5 iunie 2020 15:58:52
Problema Interclasari Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.17 kb
#include <bits/stdc++.h>

std::ifstream fin ("interclasari.in");
std::ofstream fout ("interclasari.out");

class MinHeap{

std::pair <int, int> *heap;
int size;

public:
    MinHeap (){
        heap = new std::pair <int, int>[25];
        size = 0;
    }

    void insert (int val, int ind){
        heap[size] = {val, ind};
        propagateUp (size);
        size ++;
    }

    void propagateUp (int node){
        int parent = (node - 1) / 2;
        if (node == 0)
            return;
        if (heap[parent].first > heap[node].first){
            std::swap (heap[parent], heap[node]);
            propagateUp (parent);
        }
    }

    void erase (){
        size --;
        std::swap (heap[0], heap[size]);
        propagateDown (0);
    }

    void propagateDown (int node){
        int left = 2 * node + 1;
        int right = 2 * node + 2;
        int next = node;
        if (left < size and heap[left].first < heap[next].first)
            next = left;
        if (right < size and heap[right].first < heap[next].first)
            next = right;

        if (next != node){
            std::swap (heap[node], heap[next]);
            propagateDown (next);
        }
    }

    std::pair <int, int> findMin (){
        return heap[0];
    }

    bool empty(){
        return size == 0;
    }
};

int main()
{
    int n, number, i, val, total=0;
    fin >> n;
    std::deque <int> arr[n];
    for (i=0; i<n; i++){
        fin >> number;
        total += number;
        while (number --){
            fin >> val;
            arr[i].push_back (val);
        }
    }

    MinHeap heap;

    for (i=0; i<n; i++){
        if (arr[i].empty() == false){
            heap.insert (arr[i].front(), i);
        arr[i].pop_front();
        }
    }

    fout << total << '\n';

    std::pair <int, int> ans;
    while (heap.empty() == false){
        ans = heap.findMin();
        heap.erase();
        fout << ans.first << ' ';
        if (arr[ans.second].empty() == false){
            heap.insert (arr[ans.second].front(), ans.second);
            arr[ans.second].pop_front();
        }
    }

    return 0;
}