Pagini recente » Cod sursa (job #2903376) | Cod sursa (job #1783714) | Cod sursa (job #639568) | Cod sursa (job #1297219) | Cod sursa (job #2743064)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
vector<int> poz;
vector<int> elem;
int find_elem(int x)
{
for(int i=0; i<elem.size(); i++)
if(elem[i] == x) return i;
return -1;
}
int father_of(int i)
{
if(i==0) return -1;
return (i-1)/2;
}
int left_child_of(int i)
{
return i*2+1;
}
int right_child_of(int i)
{
return i*2+2;
}
int get_minim(const vector<int> &heap)
{
return heap[0];
}
void insert_value(vector<int> &heap, int x)
{
heap.push_back(x);
elem.push_back(x);
int c = heap.size()-1, f = father_of(c);
poz.push_back(c);
while(f != -1 && heap[c] < heap[f])
{
int posc = find_elem(heap[c]);
int posf = find_elem(heap[f]);
swap(heap[c], heap[f]);
swap(poz[posc], poz[posf]);
c = f;
f = father_of(c);
}
}
void delete_value(vector<int> &heap, int i)
{
i--;
if(poz[i] != -1)
{
int f = heap.size()-1;
int posf = find_elem(heap[f]);
swap(heap[f], heap[poz[i]]);
swap(poz[posf], poz[i]);
heap.pop_back();
poz[i] = -1;
f = poz[posf];
int lc = left_child_of(f), rc = right_child_of(f);
while((lc < heap.size() || rc < heap.size()) && (heap[f] > heap[lc] || heap[f] > heap[rc]))
{
if(lc < heap.size() && heap[f] > heap[lc])
{
int posc = find_elem(heap[lc]);
int posf = find_elem(heap[f]);
swap(heap[lc], heap[f]);
swap(poz[posc], poz[posf]);
f = lc;
lc = left_child_of(f), rc = right_child_of(f);
}
else if(rc < heap.size() && heap[f] > heap[rc])
{
int posc = find_elem(heap[rc]);
int posf = find_elem(heap[f]);
swap(heap[rc], heap[f]);
swap(poz[posc], poz[posf]);
f = rc;
lc = left_child_of(f), rc = right_child_of(f);
}
else break;
}
}
}
int main()
{
vector<int> heap;
int n, op, x;
fin>>n;
for(int i=1; i<=n; i++)
{
fin>>op;
switch(op)
{
case 1:
{
fin>>x;
insert_value(heap, x);
break;
}
case 2:
{
fin>>x;
delete_value(heap, x);
break;
}
case 3:
{
fout<<get_minim(heap)<<"\n";
break;
}
default:
{
break;
}
}
}
}