Pagini recente » Cod sursa (job #2807687) | Cod sursa (job #2256945) | Monitorul de evaluare | Cod sursa (job #1130482) | Cod sursa (job #491214)
Cod sursa(job #491214)
#include<fstream>
#include<iostream>
#include<vector>
using namespace std;
template<typename T, class Compare, class Update>
class CHeap
{
private:
int size;
vector<int> vIndexes;
vector<T> vHeap;
Compare com;
Update upd;
inline void swap(const int first, const int second)
{
upd(vHeap,vIndexes,first,second);
T aux;
aux=vHeap[first];
vHeap[first]=vHeap[second];
vHeap[second]=aux;
}
void siftUp(int index)
{
int parent=(index-1-!(index%2))>>1;
while(parent>=0 && com(vHeap[index],vHeap[parent]))
{
swap(parent,index);
index=parent;
parent=(index-1-!(index%2))>>1;
}
}
void siftDown(int index)
{
int child1,child2;
bool ord=true;
child1=(index<<1)+1;
child2=(index+1)<<1;
while(ord && child1<size)
{
ord=false;
if(child1<size && child2<size)
{
if(com(vHeap[child1],vHeap[child2]))
{
if(com(vHeap[child1],vHeap[index]))
{
swap(child1,index);
index=child1;
ord=true;
}
}
else if(com(vHeap[child2],vHeap[index]))
{
swap(child2,index);
index=child2;
ord=true;
}
}
else if(child1<size)
{
if(com(vHeap[child1],vHeap[index]))
{
swap(child1,index);
index=child1;
ord=true;
}
}
child1=(index<<1)+1;
child2=(index+1)<<1;
}
}
public:
CHeap() : size(0)
{}
CHeap(const Compare& comm, const Update& updd) : size(0), com(comm), upd(updd)
{}
void insert(const T& val)
{
vHeap.push_back(val);
size++;
vIndexes.push_back(size-1);
siftUp(size-1);
}
void modify(const int pos, const T& val)
{
if(com(vHeap[pos],val))
vHeap[pos]=val;
else
vHeap[pos]=val;
siftUp(pos);
}
void remove(const int pos)
{
swap(pos,--size);
vHeap.pop_back();
siftDown(pos);
}
const T& getElement(const int pos) const
{
return vHeap[pos];
}
int getPos(const int time) const
{
return vIndexes[time];
}
void print()
{
for(unsigned int i=0; i<vHeap.size(); ++i)
{
cout<<"("<<vHeap[i].first<<" "<<vHeap[i].second<<") ";
}
cout<<endl;
}
};
struct Compare
{
bool operator() (const pair<int,int>& a, const pair<int,int>& b) const
{
return a.first<b.first;
}
};
struct Update
{
void operator() (const vector<pair<int,int> >& vHeap,
vector<int>& vIndexes,
const int first, const int second) const
{
vIndexes[vHeap[first].second]=second;
vIndexes[vHeap[second].second]=first;
}
};
int main()
{
int n,op,x,time=0;
fstream fin("heapuri.in", fstream::in);
fstream fout("heapuri.out", fstream::out);
Compare com;
Update upd;
CHeap<pair<int,int>,Compare,Update> heap(com,upd);
fin>>n;
/*for(int i=0; i<5; ++i)
heap.insert(make_pair(5-i,i));
heap.print();
heap.modify(3,make_pair(-1,0));
heap.print();
heap.remove(heap.getPos(0));
heap.print();
heap.remove(heap.getPos(3));
heap.print();*/
for(int i=0; i<n; ++i)
{
fin>>op;
switch(op)
{
case 1:
{
fin>>x;
heap.insert(make_pair(x,time++));
}; break;
case 2:
{
fin>>x;
heap.remove(heap.getPos(x-1));
}; break;
case 3:
{
fout<<heap.getElement(0).first<<"\n";
}; break;
}
}
fin.close();
fout.close();
return 0;
}