Pagini recente » Cod sursa (job #446878) | Cod sursa (job #324778) | Cod sursa (job #1500134) | Cod sursa (job #250904) | Cod sursa (job #2906559)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
vector<pair<int,int>> h; //perechi de forma valoare index_ordine_cronologica
vector<int> poz; //poz[i] = la ce pozitie in heap se afla al i + 1-lea element inserat ex, ppz[0] = 2
//primul element inserat se afla la pozitia 2 in heap
int N;
const int inf = 1<<30;
void heapifyUp(int index){
// int index = h.size() - 1; //pornesc de la ultima pozitie
int indexParinte = (index - 1) / 2;
while(indexParinte >= 0 && indexParinte < h.size())
{
if(h[indexParinte].first > h[index].first){
swap(h[indexParinte], h[index]);
swap(poz[h[indexParinte].second], poz[h[index].second]);
}
else
{
return;
}
index = indexParinte;
if(index == 0) return;
indexParinte = (index - 1) / 2;
}
}
void insertInHeap(int value, int &index){
h.push_back(make_pair(value, index));
poz.push_back(h.size() - 1);
heapifyUp(h.size() - 1);
index++;
}
void heapifyDown(int index){
int copilIndex = index * 2 + 1; //intai iau index-ul copilului stang
//verific daca nu are si copil drept
//+ daca nu exista o valoare mai mica in c drept decat in c stang
if(copilIndex < 0 || copilIndex >= h.size()) return;
if(copilIndex + 1 >= 0 && copilIndex + 1 <= h.size() - 1 && h[copilIndex+1].first < h[copilIndex].first)
copilIndex += 1;
while(copilIndex < h.size())
{
if(h[copilIndex].first < h[index].first){
swap(h[index], h[copilIndex]);
swap(poz[h[copilIndex].second], poz[h[index].second]);
}
index = copilIndex;
copilIndex = index * 2 + 1;
if(copilIndex < 0 || copilIndex >= h.size()) return;
if(copilIndex + 1 >= 0 && copilIndex + 1 <= h.size() - 1 && h[copilIndex+1].first < h[copilIndex].first)
copilIndex += 1;
}
}
void removeFromHeap(int index){
//poz al index-lea el in heap este poz[index]
//trb sa elimin el de pe poz poz[index-1] din heap
h[poz[index-1]].first = h[h.size()-1].first;
h.pop_back();
heapifyDown(poz[index-1]);
}
int main()
{
int indexCron = 0, cod, value;
fin>>N;
for(int i = 0; i < N; ++i){
fin>>cod;
if(cod == 1){
fin>>value;
insertInHeap(value, indexCron);
}
if(cod == 2){
fin>>value;
if(h.size() > 0) removeFromHeap(value);
}
if(cod == 3) fout<<h[0].first<<'\n';
}
// for(auto x: h)
// cout<<x.first<<"\n";
return 0;
}