Mai intai trebuie sa te autentifici.
Cod sursa(job #2869866)
Utilizator | Data | 11 martie 2022 21:29:40 | |
---|---|---|---|
Problema | Heapuri | Scor | 10 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 2.04 kb |
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
long long heap[200001], valoriAdd[200001];
int L = 0;
int N;
inline int Minim()
{
return heap[1];
}
inline bool Smalller(int x, int y)
{
return heap[x] < heap[y];
}
inline bool Bigger(int x, int y)
{
return heap[x] > heap[y];
}
void Swap(int x, int y)
{
int aux;
aux = heap[x];
heap[x] = heap[y];
heap[y] = aux;
}
void UpHeap(int L)
{
int father = L / 2;
if(father && Smalller(L,father))
{
Swap(L,father);
UpHeap(father);
}
}
void DownHeap(int x)
{
if (x < L)
{
int leftSon = 0, rightSon = 0;
if(x * 2 <= L)
{
leftSon = x * 2;
}
if(x * 2 + 1 <= L)
{
rightSon = x * 2 + 1;
}
if(rightSon != 0 || leftSon != 0) {
if (Bigger(x,leftSon))
{
Swap(x,leftSon);
DownHeap(leftSon);
}
else if(Bigger(x,rightSon))
{
Swap(x,rightSon);
DownHeap(rightSon);
}
}
}
}
void Inserare(int x, int &L)
{
valoriAdd[L+1] = x;
heap[L+1] = x;
L++;
if(L > 1){
UpHeap(L);
}
}
void Stergere(int x)
{
int xEl;
xEl = valoriAdd[x];
for (int i = 1; i <= L; i++)
{
if(heap[i] == xEl)
{
xEl = i;
i = L + 1;
}
}
heap[xEl] = heap[L];
heap[L] = 0;
L--;
DownHeap(1);
UpHeap(xEl);
}
void Operatii()
{
int op;
int el;
in >> op;
if(op == 1)
{
in >> el;
Inserare(el,L);
}
else if(op == 2)
{
in >> el;
Stergere(el);
}
else if(op == 3)
{
out << Minim() << '\n';
}
}
int main()
{
in >> N;
for (int i = 0; i < N; i++)
{
Operatii();
}
return 0;
}