Cod sursa(job #2892531)

Utilizator Rares_StefanoiuRares Stefanoiu Rares_Stefanoiu Data 22 aprilie 2022 15:05:39
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include<iostream>
#include<vector>
#include<fstream>
using namespace std;
void coboara(int v[],int poz[], int poz_heap[], int n, int i)
{
    int min = i;
    int st = 2 * i + 1;
    int dr = 2 * i + 2;


    if (st < n and v[st] < v[min])
        min = st;


    if (dr < n and v[dr] < v[min])
        min = dr;

    if (min != i) {
        swap(v[i], v[min]);
        swap(poz[i], poz[min]);
        poz_heap[poz[i]] = i;
        poz_heap[poz[min]] = min;
        coboara(v,poz,poz_heap, n, min);
    }
}

void urca(int heap[],int poz[],int poz_heap[], int fiu) {
    if (fiu) {
        int tata = (fiu - 1) / 2;
        if (heap[tata] > heap[fiu])
        {
            swap(heap[tata], heap[fiu]);
            swap(poz[tata], poz[fiu]);
            poz_heap[poz[tata]] = tata;
            poz_heap[poz[fiu]] = fiu;
            urca(heap,poz,poz_heap, tata);
        }
    }
}
int n, i, x, c = 0, fiu, j, y, tata, p = 0;
int poz[200001], heap[200001], poz_heap[200001];
int main() {
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");
    f >> n;
    for (i = 1; i <= n; i++) {
        f >> x;
        if (x == 1) {
            f >> y;
            poz[c] = p;
            heap[c] = y;
            poz_heap[p] = c;
            fiu = c;
            urca(heap,poz,poz_heap ,fiu);
            c++;
            p++;

        }
        if (x == 2) {
            f >> y;
            /*for (j = 0; j <= c; j++)
                if (heap[j] == poz[y-1]) {
                    fiu = j;
                    break;
                }*/
            fiu = poz_heap[y-1];
            swap(heap[fiu] ,heap[--c]);
            swap(poz[fiu], poz[c]);
            poz_heap[poz[fiu]] = fiu;
            poz_heap[poz[c]] = c;
            if (heap[(fiu - 1) / 2] > heap[fiu])
                urca(heap,poz,poz_heap, fiu);
            else  
               coboara(heap,poz,poz_heap, c , fiu);
            
        }
        if (x == 3)
            g<< heap[0]<<"\n";

    }
        
    return 0;
}