Cod sursa(job #2955394)

Utilizator raileanu-alin-gabrielRaileanu Alin-Gabriel raileanu-alin-gabriel Data 16 decembrie 2022 21:46:12
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.59 kb
#include <fstream>
//MIN-HEAP
const int NMAX=200005;

using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

struct nod
{
    int cron, val;
};
nod h[NMAX];

void creare(nod [], int&);
void creare_comb(nod [], int&);
int extrage_min(nod [], int&);
void afisare(nod [], int);
void inserare(nod [], int&, int, int);
void combinare(nod [], int&, int);
void sterge(nod [], int&, int);

int n;
int pz[NMAX]; //pozitia pe care se afla in heap al x-lea element citit

int main()
{
    creare(h, n);
    //for(int i=1; i<=n; i++) fout<<pz[i]<<' ';
    //creare_comb(h, n);
    //afisare(h, n);
    return 0;
}

void inserare(nod h[], int& n, int x, int i)
{
    int poz=n+1, tpoz=poz/2;
    while(tpoz>0 && h[tpoz].val>x)
    {
        h[poz]=h[tpoz];
        pz[h[poz].cron]=poz;
        poz=tpoz;
        tpoz=poz/2;
    }
    h[poz]={i, x};
    pz[i]=poz;
    n++;
}

void sterge(nod h[], int& n, int x)
{
    h[pz[x]]=h[n--];
    combinare(h, n, pz[x]);
}

void combinare(nod h[], int& n, int i)
{
    //combin heapurile corecte cu radacinile 2i si 2i+1 cu nodul i
    int x=h[i].val, xp=h[i].cron, tata=i, fiu=2*i, bunic=i/2;
    //e fenta la radacina cum ar fi
    while(bunic!=0 && h[bunic].val>x)
    {
        h[tata]=h[bunic];
        pz[h[tata].cron]=tata;
        tata=bunic;
        bunic=tata/2;
    }
    while(fiu<=n)
    {
        //daca exista fiu drept si e mai mic
        if(fiu+1<=n && h[fiu+1].val<h[fiu].val) fiu++;
        if(h[fiu].val<x)
        {
            h[tata]=h[fiu];
            pz[h[tata].cron]=tata;
            tata=fiu;
            fiu=fiu*2;
        }
        else break;
    }
    h[tata]={xp, x};
    pz[xp]=tata;
}

/*int extrage_min(nod h[], int& n)
{
    int minim=h[1].val;
    h[1].val=h[n--].val;
    combinare(h, n, 1);
    return minim;
}*/

/*void creare_comb(nod h[], int& n)
{
    int i;
    fin>>n;
    for(i=1; i<=n; i++) fin>>h[i].val;
    for(i=n/2; i>0; i--) combinare(h, n, i);
}*/

void creare(nod h[], int& n)
{
    int i, q, x, op, nr=0, afis=0, gas=0;
    fin>>q; n=0;
    for(i=1; i<=q; i++)
    {
        fin>>op;
        if(op==1)
        {
            fin>>x; nr++;
            if(x==314) gas=nr;
            inserare(h, n, x, nr);
        }
        else if(op==2)
        {
            fin>>x;
            sterge(h, n, x);
        }
        else
        {
            afis++;
            fout<<h[1].val<<'\n';
        }
    }
}

void afisare(nod h[], int n)
{
    int i;
    for(i=1; i<=n; i++) fout<<h[i].val<<' ';
    fout<<'\n';
}