Cod sursa(job #1042382)

Utilizator bghimisFMI Ghimis Bogdan bghimis Data 26 noiembrie 2013 22:48:03
Problema Sortare prin comparare Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>
#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 idx / 2;
  return -1;
}

int get_min()
{
  return heap[0];
}

void push_heap(int val)
{
  heap.push_back(val);
  int idx = heap.size() - 1;

  for (int i = father(idx); i >= 0; i = father(i))
    if (heap[i] > val)
      {
	int tmp = heap[i];
	heap[i] = val;
	heap[idx] = tmp;
	
	idx = i;
      }
    else
      break;
}

void pop_heap()
{
  if (heap.size() == 0)
    return;

  heap[0] = heap[heap.size() - 1];
  heap.pop_back();

  if (heap.size() == 2)
    {
      if (heap[0] > heap[1])
	{
	  int tmp = heap[0];
	  heap[0] = heap[1];
	  heap[1] = tmp;
	}

      return;
    }

  for (int idx = 0; idx < (int)(heap.size() / 2); )
    {
      int left_son  = idx * 2 + 1;
      int right_son = idx * 2 + 2;

      if (heap[idx] < heap[left_son] &&
	  heap[idx] < heap[right_son])
	break;

      if (heap[left_son] < heap[right_son])
	{
	  swap (heap[idx], heap[left_son]);
	  idx = left_son;
	}
      else 
	{
	  swap (heap[idx], heap[right_son]);
	  idx = right_son;
	}
    }
}

int main()
{
  in >> n;
  for (int i = 0; i < n; ++i)
    in >> v[i];

  for (int i = 0; i < n; ++i)
    push_heap (v[i]);

  for (int i = 0; i < n; ++i)
    {
      out << get_min() << " ";
      pop_heap();
    }

  return 0;
}