Pagini recente » Cod sursa (job #3240478) | Cod sursa (job #2757475) | Cod sursa (job #2825250) | Cod sursa (job #1403717) | Cod sursa (job #672897)
Cod sursa(job #672897)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
class Heap
{
vector<int> h;
int father(int node)
{
return node / 2;
}
int leftSon(int node)
{
return node * 2;
}
int rightSon(int node)
{
return node * 2 + 1;
}
void swift(int node)
{
int son;
do {
son = 0;
if( leftSon(node) <= size() )
{
son = leftSon(node);
if( rightSon(node) <= size() && h[ rightSon(node) ] < h[ leftSon(node) ] )
{
son = rightSon(node);
}
if( h[son] < h[node] )
{
swap(h[son], h[node]);
node = son;
}
else
{
son = 0;
}
}
} while( son );
}
void percolate(int node)
{
int value = h[node];
while( (node > 1) && (h[ father(node) ] > value ) )
{
h[ node ] = h[ father(node) ];
node = father(node);
}
h[node] = value;
}
public:
Heap(int size)
{
h.reserve(size + 1);
h.push_back(0);
}
int size()
{
return h.size() - 1;
}
int getMin()
{
if( size() != 0 )
return h[1];
else
{
cout << "Empty heap" << endl;
exit(1);
}
}
void insert(int value)
{
h.push_back(value);
percolate( size() );
}
void removeByPosition(int node)
{
h[node] = h[ size() ];
h.pop_back();
if( (node > 1) && (h[node] < h[ father(node) ]) )
percolate(node);
else
swift(node);
}
void removeByValue(int value)
{
int pos = distance(h.begin(), find(h.begin(), h.end(), value) );
removeByPosition(pos);
}
int get(int i)
{
return h[i];
}
void print()
{
for(int i = 1; i <= size(); ++i)
cout << h[i] << " ";
cout << endl;
}
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(100);
vector<int> position;
in >> n;
for(int i = 0; i < n; ++i)
{
int code, value;
in >> code;
switch(code)
{
case 1:
{
in >> value;
h.insert(value);
position.push_back(value);
break;
}
case 2:
{
in >> value;
h.removeByValue( position[value - 1] );
break;
}
case 3:
{
out << h.getMin() << endl;
break;
}
}
}
return 0;
}