Cod sursa(job #2642706)

Utilizator lucametehauDart Monkey lucametehau Data 16 august 2020 20:10:50
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <cstdio>
#include <vector>

using namespace std;

const int DIM = (1 << 17);

int n;

int v[500005], tmp[500005], cnt[256], nr[256];

char nxt() {
  static char buff[DIM];
  static int bp = DIM;
  if(bp == DIM) {
    fread(buff, 1, DIM, stdin);
    bp = 0;
  }
  return buff[bp++];
}

void read(int &x) {
  static char ch;
  x = 0;
  do {
    ch = nxt();
  } while(ch < '0' || '9' < ch);
  do {
    x = x * 10 + ch - '0';
    ch = nxt();
  } while(ch >= '0' && '9' >= ch);
}

int main() {
  freopen("algsort.in", "r", stdin);
  freopen("algsort.out", "w", stdout);
  read(n);
  for(int i = 1; i <= n; i++)
    read(v[i]);
  for(int j = 0, msk = 255; j < 32; j += 8, msk <<= 8) {
    for(int i = 1; i <= n; i++)
      cnt[(v[i] & msk) >> j]++;
    for(int i = 1; i < 256; i++)
      cnt[i] += cnt[i - 1];
    for(int i = 1; i <= n; i++) {
      int k = ((v[i] & msk) >> j);
      nr[k]++;
      tmp[(k > 0 ? cnt[k - 1] : 0) + nr[k]] = v[i];
    }
    for(int i = 1; i <= n; i++)
      v[i] = tmp[i];
    for(int i = 0; i < 256; i++)
      cnt[i] = nr[i] = 0;
  }
  for(int i = 1; i <= n; i++)
    printf("%d ", v[i]);
  return 0;
}