Pagini recente » Cod sursa (job #2195241) | Cod sursa (job #389011) | Cod sursa (job #414392) | Cod sursa (job #485486) | Cod sursa (job #1041994)
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream in ("algsort.in");
ofstream out("algsort.out");
int n;
int v[500001];
vector<int> heap;
int father (int idx)
{
if (idx == 0) return -1;
return idx / 2;
}
int minim ()
{
return heap[0];
}
void pop_heap()
{
if (heap.size() <= 1)
return;
heap[0] = heap[heap.size() - 1];
heap.pop_back();
for (int i = 0; ;)
{
if ( i * 2 + 2 > heap.size() - 1 )
break;
int fiu_stg = heap[i * 2 + 1];
int fiu_dr = heap[i * 2 + 2];
if (heap[i] < fiu_stg && heap[i] < fiu_dr)
break;
if (fiu_stg < fiu_dr)
{
swap(heap[i], heap[i * 2 + 1]);
i = i * 2 + 1;
}
else
{
swap(heap[i], heap[i * 2 + 2]);
i = i * 2 + 2;
}
}
/*
for (int i = 0; i < heap.size(); ++i)
cout << heap[i] << " ";
cout << "\n";
*/
}
void push_heap (int val)
{
heap.push_back(val);
int poz = heap.size() - 1;
for (int i = heap.size() - 1; i >= 0; i = father(i))
if (val < heap[i])
{
int aux = heap[i];
heap[i] = val;
heap[poz] = aux;
poz = i;
}
/*
for (int i = 0; i < heap.size(); ++i)
cout << heap[i] << " ";
cout << "\n";
*/
}
int main()
{
in >> n;
for (int i = 1; i <= n; ++i)
in >> v[i];
for (int i = 1; i <= n; ++i)
push_heap (v[i]);
for (int i = 1; i < n - 1; ++i)
{
out << minim() << " ";
pop_heap();
}
if (heap[0] > heap[1])
out << heap[1] << " " << heap[0];
else
out << heap[0] << " " << heap[1];
}