Cod sursa(job #2823992)

Utilizator mircea_007Mircea Rebengiuc mircea_007 Data 30 decembrie 2021 14:45:58
Problema Radix Sort Scor 30
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.8 kb
// This program was written on 30.12.2021
// for problem radixsort
// by Mircea Rebengiuc

#include <stdio.h>
#include <ctype.h>

#define MAXN 10000000
#define STEP 10
#define SIGMA 16 // vom lua numerele in baza 16
#define LSIGMA 4 // log2(sigma)
#define NUMSTEP 8 // 8 * 4 = 32 biti
#define NIL -1
#define MAXNCF 10

#define MAXBUF (128 * 1024)

int v[MAXN];
int ord[MAXN];

int list[SIGMA];
int next[MAXN];

FILE *fin, *fout;

char wbuf[MAXBUF];
int wbp = 0;

static inline void bputc( int ch ){
  wbuf[wbp] = ch;
  if( (wbp = ( (wbp + 1) & (MAXBUF - 1) )) == 0 )
    fwrite(wbuf, sizeof(char), MAXBUF, fout);
}

static inline void bflush(){
  fwrite(wbuf, sizeof(char), wbp, fout); 
}

static inline void fputint( int n ){
  char out[MAXNCF + 2] = "0000000000 ";
  int i = MAXNCF;
  
  if( n == 0 )
    i--;
  
  while( n ){
    out[--i] += (n % 10);
    n /= 10;
  }
  
  for( ; i <= MAXNCF ; i++ )
    bputc(out[i]);
}

int main(){
  fin  = fopen("radixsort.in",  "r");
  fout = fopen("radixsort.out", "w");
  
  int n, i, a, b, c, step, mask;
  
  fscanf(fin, "%d%d%d%d", &n, &a, &b, &c);
  
  v[0] = b;
  ord[0] = 0;
  for( i = 1 ; i < n ; i++ ){
    v[i] = (((long long)a) * v[i - 1] + b) % c;
    ord[i] = i;
  }
  
  mask = (1 << LSIGMA) - 1;
  for( step = 0 ; step < STEP ; step++ ){
    for( c = 0 ; c < SIGMA ; c++ )
      list[c] = NIL;
  
    for( i = 0 ; i < n ; i++ ){
      c = ((v[ord[i]] & mask) >> (step * LSIGMA));
      next[ord[i]] = list[c];
      list[c] = ord[i];
    }

    // sortare stabila (bucket sort)    
    a = n;
    for( c = SIGMA ; c-- ; ){
      i = list[c];
      while( i != NIL ){
        ord[--a] = i;
        i = next[i];
      }
    }
    
    mask <<= LSIGMA;
  }
  
  for( i = 0 ; i < n ; i += STEP )
    fputint(v[ord[i]]);
  bputc('\n');
  
  bflush();
  fclose(fin);
  fclose(fout);
  return 0;
}