Pagini recente » Cod sursa (job #1122871) | Cod sursa (job #1314025) | Cod sursa (job #2066697) | Cod sursa (job #437813) | Cod sursa (job #2422461)
#include <fstream>
#include <vector>
#include <string>
using namespace std;
struct Node {
unsigned value;
unsigned index;
};
string const inFile = "heapuri.in";
string const outFile = "heapuri.out";
ifstream Read(inFile);
ofstream Write(outFile);
void InsertDownTop(vector<Node> &nodes, vector<unsigned> &indices, unsigned nodeIndex) {
unsigned parentIndex;
while (nodeIndex > 0) {
parentIndex = (nodeIndex - 1) >> 1;
if (nodes[nodeIndex].value < nodes[parentIndex].value) {
swap(indices[nodes[nodeIndex].index], indices[nodes[parentIndex].index]);
swap(nodes[nodeIndex], nodes[parentIndex]);
nodeIndex = parentIndex;
}
else {
break;
}
}
}
void InsertTopDown(vector<Node> &nodes, vector<unsigned> &indices, unsigned nodeIndex) {
unsigned leftChildIndex;
unsigned rightChildIndex;
unsigned biggestChildIndex = nodeIndex;
do {
leftChildIndex = (nodeIndex << 1) + 1;
rightChildIndex = (nodeIndex << 1) + 2;
if (leftChildIndex < nodes.size())
if (nodes[biggestChildIndex].value > nodes[leftChildIndex].value) {
biggestChildIndex = leftChildIndex;
}
if (rightChildIndex < nodes.size())
if (nodes[biggestChildIndex].value > nodes[rightChildIndex].value) {
biggestChildIndex = rightChildIndex;
}
if (biggestChildIndex != nodeIndex) {
swap(indices[nodes[nodeIndex].index], indices[nodes[biggestChildIndex].index]);
swap(nodes[nodeIndex], nodes[biggestChildIndex]);
nodeIndex = biggestChildIndex;
}
} while (biggestChildIndex != nodeIndex);
}
void Add(vector<Node> &nodes, vector<unsigned> &indices) {
unsigned value;
Read >> value;
nodes.push_back(Node());
nodes.back().value = value;
nodes.back().index = indices.size();
indices.push_back(nodes.size() - 1);
InsertDownTop(nodes, indices, nodes.size() - 1);
}
void Delete(vector<Node> &nodes, vector<unsigned> &indices) {
unsigned index;
Read >> index;
--index;
indices[nodes.back().index] = indices[index];
swap(nodes[indices[index]], nodes.back());
nodes.pop_back();
InsertDownTop(nodes, indices, indices[index]);
InsertTopDown(nodes, indices, indices[index]);
}
unsigned GetMin(vector<Node> const &nodes) {
return nodes[0].value;
}
int main() {
unsigned n;
unsigned code;
vector<Node> nodes;
vector<unsigned> indices;
Read >> n;
for (unsigned i = 0; i < n; ++i) {
Read >> code;
if (code == 1) {
Add(nodes, indices);
}
else if (code == 2) {
Delete(nodes, indices);
}
else if (code == 3) {
Write << GetMin(nodes) << '\n';
}
}
return 0;
}