Cod sursa(job #1028061)

Utilizator Teodor94Teodor Plop Teodor94 Data 13 noiembrie 2013 16:59:43
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <cstdio>
#include <cmath>
#include <algorithm>

using namespace std;

#define MAX_N 500000
#define MAX_M 800
#define INF 0x3f3f3f3f

struct alg {
    int val, pos;
};

int v[MAX_N];
alg ans[MAX_M];

void read( FILE *fin, int &n ) {
    fscanf( fin, "%d", &n );
    for ( int i = 0; i < n; ++i )
        fscanf( fin, "%d", &v[i] );
}

void init( int n, int len, int m ) {
    for ( int i = 0; i <= m; ++i ) {
        ans[i].val = v[i * len];
        ans[i].pos = i * len;
        for ( int j = i * len + 1; j < min( n, ( i + 1 ) * len ); ++j )
            if ( ans[i].val > v[j] ) {
                ans[i].val = v[j];
                ans[i].pos = j;
            }
    }
}

void update( int p, int n, int len, int m ) {
    v[p] = INF;

    int i = p / len;
    ans[i].val = v[i * len];
    ans[i].pos = i * len;
    for ( int j = i * len + 1; j < min( n, ( i + 1 ) * len ); ++j )
    if ( ans[i].val > v[j] ) {
        ans[i].val = v[j];
        ans[i].pos = j;
    }
}

void write( FILE *fout, int n, int len, int m ) {
    int p = 0, res = ans[0].val;
    for ( int i = 1; i < m; ++i )
        if ( ans[i].val < res )
            p = i;
    fprintf( fout, "%d ", ans[p].val );
    update( ans[p].pos, n, len, m );
}

void scrie( int m ) {
    for ( int i = 0; i < m; ++i )
        printf( "%d ", ans[i] );
    printf( "\n" );
}

int main() {
    FILE *fin, *fout;

    fin = fopen( "algsort.in", "r" );
    int n;
    read( fin, n );
    fclose( fin );

    int len = sqrt( n );
    int m = n / len;
    if ( n % len )
        ++m;

    init( n, len, m );

    //scrie( m );

    fout = fopen( "algsort.out", "w" );
    for ( int i = 0; i < n; ++i ) {
        write( fout, n, len, m );
        //scrie( m );
    }
    fclose( fout );
}