Cod sursa(job #2895646)

Utilizator Petrica81Simion Petrica Petrica81 Data 29 aprilie 2022 12:22:39
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream f ("heapuri.in");
ofstream g ("heapuri.out");
vector<pair<int,int>> heap;
vector<pair<int,int>> ordine;
int nrordine = 1;
void inserare(int x){
    heap.emplace_back(x,nrordine);
    int poz = heap.size()-1;
    while(heap[poz/2].first > heap[poz].first){
        ordine[heap[poz/2].second].second = poz;
        swap(heap[poz/2],heap[poz]);
        poz = poz/2;
    }
    ordine.emplace_back(x, poz);
    nrordine++;
}
void stergere(int x){
    int poz = ordine[x].second;
    swap(heap[poz], heap[heap.size()-1]);
    heap.pop_back();
    while(heap[poz/2].first > heap[poz].first){
        ordine[heap[poz/2].second].second = poz;
        swap(heap[poz/2],heap[poz]);
        poz = poz/2;
    }
    bool ok = false;
    while(!ok){
        if(poz*2+1 < heap.size() && (heap[poz*2].first < heap[poz].first || heap[poz*2+1].first < heap[poz].first)){
            if(heap[poz*2].first < heap[poz*2+1].first){
                swap(heap[poz],heap[poz*2]);
                swap(ordine[heap[poz].second].second, ordine[heap[poz*2].second].second);
                poz = poz*2;
            }
            else{
                swap(heap[poz],heap[poz*2+1]);
                swap(ordine[heap[poz].second].second, ordine[heap[poz*2+1].second].second);
                poz = poz*2+1;
            }
        }
        else if(poz*2 < heap.size() && heap[poz*2].first < heap[poz].first){
            ok = true;
            swap(heap[poz],heap[poz*2]);
            swap(ordine[heap[poz].second].second, ordine[heap[poz*2].second].second);
            poz = poz*2;
        }
        else ok = true;
    }
}
int main() {
    int nrpasi;
    f>>nrpasi;
    heap.emplace_back(0,0);
    ordine.emplace_back(0,0);
    while(nrpasi){
        int op, x;
        f>>op;
        if(op == 1){
            f>>x;
            inserare(x);
        }
        else if(op == 2){
            f>>x;
            stergere(x);
        }
        else if(op == 3){
            g<<heap[1].first<<'\n';
        }
        nrpasi--;
    }
    for(int i = 0; i < heap.size(); i++){
        cout<<heap[i].first<<" "<<heap[i].second<<'\n';
    }
    cout<<"\n\n\n";
    for(int i = 0; i < ordine.size(); i++){
        cout<<ordine[i].first<<" "<<ordine[i].second<<'\n';
    }
    return 0;
}