Cod sursa(job #2439542)

Utilizator vlad.ulmeanu30Ulmeanu Vlad vlad.ulmeanu30 Data 16 iulie 2019 11:55:19
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <bits/stdc++.h>
#define maxn 500000

FILE *fin, *fout;

namespace prs
{
  const int DIM = (1<<17);
  char BUFF[DIM+5];
  int kbu = 0;
  void reset_ () { if ( prs::kbu == prs::DIM ) fread ( prs::BUFF, 1, prs::DIM, fin ), prs::kbu = 0; }
  void read_ ( int &nr )
  {
    nr = 0;
    while ( prs::BUFF[prs::kbu] < '0' || prs::BUFF[prs::kbu] > '9' ) { prs::kbu++; prs::reset_ (); }
    while ( prs::BUFF[prs::kbu] >= '0' && prs::BUFF[prs::kbu] <= '9' ) { nr = nr * 10 + prs::BUFF[prs::kbu++] - '0'; prs::reset_ (); }
  }
}

namespace ctl
{
  struct nod
  {
    int lson, rson, val, amt;
  };
  void add_val ( std::vector<int> &v, std::vector<ctl::nod> &g, int p, int x )
  {
    if (g[p].val == v[x]) { g[p].amt++; return; }
    if (g[p].val < v[x])
    {
      if (g[p].rson == 0) g[p].rson = x, g[x] = {0, 0, v[x], 1};
      else ctl::add_val (v, g, g[p].rson, x);
    }
    else
    {
      if (g[p].lson == 0) g[p].lson = x, g[x] = {0, 0, v[x], 1};
      else ctl::add_val (v, g, g[p].lson, x);
    }
  }
  void dfs ( std::vector<ctl::nod> &g, std::vector <int> &ans, int x )
  {
    if (g[x].lson != 0) ctl::dfs (g, ans, g[x].lson);
    for (int i = 0; i < g[x].amt; i++ ) ans.push_back (g[x].val);
    if (g[x].rson != 0) ctl::dfs (g, ans, g[x].rson);
  }
  void sort ( std::vector<int> &v )
  {
    int n = v.size();
    std::random_shuffle(v.begin(), v.end());
    v.push_back(0);
    int i;
    for ( i = n; i >= 1; i-- ) v[i] = v[i-1];
    std::vector <ctl::nod> g(n+1);
    g[1] = {0, 0, v[1], 1};
    for ( i = 2; i <= n; i++ ) ctl::add_val (v, g, 1, i);
    v.clear();
    ctl::dfs (g, v, 1);
  }
}

std::vector<int> v;

int main ()
{
  fin = fopen ( "algsort.in", "r" );
  fout = fopen ( "algsort.out", "w" );
  int n; prs::read_(n);
  int i, z;
  for ( i = 0; i < n; i++ ) prs::read_(z), v.push_back(z);
  ctl::sort (v);
  for (int z: v) fprintf ( fout, "%d ", z );
  return 0;
}