Pagini recente » Cod sursa (job #2392529) | Cod sursa (job #1225592) | Cod sursa (job #3138541) | Cod sursa (job #2285565) | Cod sursa (job #672981)
Cod sursa(job #672981)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
vector<int> position;
struct node
{
int value;
int order;
};
int insertions;
class Heap
{
vector<node> h;
int father(int node)
{
return node / 2;
}
int leftSon(int node)
{
return node * 2;
}
int rightSon(int node)
{
return node * 2 + 1;
}
void sift(int node)
{
int son;
do {
son = 0;
if( leftSon(node) <= size() )
{
son = leftSon(node);
if( rightSon(node) <= size() && h[ rightSon(node) ].value < h[ leftSon(node) ].value )
{
son = rightSon(node);
}
if( h[son].value < h[node].value )
{
swap(h[son], h[node]);
swap(position[ h[son].order ], position[ h[node].order ]);
node = son;
}
else
{
son = 0;
}
}
} while( son );
}
void percolate(int k)
{
node n = h[k];
while( (k > 1) && (h[ father(k) ].value > n.value ) )
{
swap( h[k], h[ father(k) ] );
swap( position[ h[ father(k) ].order ], position[ h[k].order ]);
k = father(k);
}
h[k] = n;
}
public:
Heap(int size)
{
h.reserve(size + 1);
//dummy values ( first used index: 1 )
h.push_back(node());
}
int size()
{
return h.size() - 1;
}
int getMin()
{
if( size() != 0 )
return h[1].value;
else
{
cout << "Empty heap" << endl;
exit(1);
}
}
void insert(int value)
{
node n;
n.value = value;
n.order = ++insertions;
h.push_back(n);
position.push_back( size() );
percolate( size() );
}
void removeByPosition(int node)
{
h[node] = h[ size() ];
h.pop_back();
if( (node > 1) && (h[node].value < h[ father(node) ].value) )
percolate(node);
else
sift(node);
}
int get(int i)
{
return h[i].value;
}
friend ostream& operator<<(ostream& out, Heap &h);
};
ostream& operator<< (ostream& out, Heap &h)
{
out << "Heap: " << endl;
for(int i = 1; i <= h.size(); ++i)
out << h.get(i) << " ";
out << endl << "========";
return out;
}
int main()
{
ifstream in("heapuri.in", ifstream::in);
ofstream out("heapuri.out");
int n;
Heap h(2048);
in >> n;
position.push_back(0); //dummy value
for(int i = 0; i < n; ++i)
{
int code, value;
in >> code;
switch(code)
{
case 1:
{
in >> value;
h.insert(value);
break;
}
case 2:
{
in >> value;
h.removeByPosition( position[value] );
break;
}
case 3:
{
out << h.getMin() << endl;
break;
}
}
}
return 0;
}