Pagini recente » Cod sursa (job #1684413) | Cod sursa (job #243560) | Cod sursa (job #1160925) | Cod sursa (job #603214) | Cod sursa (job #1729448)
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
#define MAX_HEAP_SIZE 200010
int heap [MAX_HEAP_SIZE], pos [MAX_HEAP_SIZE], crono[MAX_HEAP_SIZE], c=1, n, op, x, nr;
//bla
void sift(int * h, int i)
{
int k, j=0;
k=i;
while(j!=k)
{
j=k;
if((2*j<=nr ) && (h[2*j] < h[k]))
k=2*j;
if((2*j<nr) && (h[2*j+1]< h[k]))
k=2*j+1;
swap(h[j], h[k]);
swap(crono[j], crono[k]);
pos[crono[j]]=j;
pos[crono[k]]=k;
}
}
void percolate(int * h, int i)
{
int k, j=0;
k=i;
while(j!=k)
{
j=k;
if((j>1) && (h[j/2]>h[k]))
k=j/2;
swap(h[j], h[k]);
swap(crono[j], crono[k]);
pos[crono[j]]=j;
pos[crono[k]]=k;
}
}
int find_min(int *h)
{
return h[1];
}
void delete_max(int * h)
{
h[1]=h[nr];
//--nr
sift(h, 1);
}
void insert_heap(int * h, int val)
{
h[nr]=val;
//pos[nr]=nr;
crono[nr]=c;
++c;
percolate(h, nr);
}
void alter_heap(int * h, int i, int val)
{
int aux;
aux = h[i];
h[i]=val;
if (val > aux )
sift(h, i);
else
percolate(h, i);
}
int main ()
{
int i;
ifstream in ("heapuri.in");
ofstream out ("heapuri.out");
in>>n;
//memset(heap, 1000000001, MAX_HEAP_SIZE);
for (i=0;i<n;++i)
{
in>>op;
if(op==1)
{
in>>x;
++nr;
insert_heap(heap, x);
}
else if (op==2)
{
in>>x;
alter_heap(heap, pos[x], heap[nr]);
--nr;
//delete
}
else
{
out<<find_min(heap);
out<<"\n";
}
cout<<"Heapul cu "<<nr<<" elem: ";
for(int j=1;j<=nr;++j)
cout<<heap[j]<<" ";
cout<<endl;
for(int j=1;j<=nr;++j)
cout<<crono[j]<<" ";
cout<<endl;
for(int j=1;j<=n;++j)
cout<<pos[j]<<" ";
cout<<"\n\n";
}
in.close();
out.close();
return 0;
}