Cod sursa(job #2922004)

Utilizator tzancauraganuTzanca Uraganu tzancauraganu Data 2 septembrie 2022 19:47:03
Problema Radix Sort Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <cassert>
#include <cstring>
#include <set>
#include <unordered_map>
#include <memory>
#include <deque>
#include <queue>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <sstream>
#include <bitset>
 
using namespace std;


ifstream f("radixsort.in");
ofstream g("radixsort.out");

const unsigned int BITS = 255;
unsigned int N;

void sort(const unsigned int p, const unsigned int b, const unsigned int e, unsigned int v[], unsigned int vcopy[]) {
    if (e - b <= 2) {
        if (b + 1 < e && v[b + 1] < v[b])
            swap(v[b], v[b + 1]);
        vcopy[b] = v[b];
        if (b + 1 < e)
            vcopy[b + 1] = v[b + 1];
        return;
    }
    const unsigned int mask = BITS << p;
    unsigned int cnt[BITS + 1];

    memset(cnt, 0, sizeof(cnt));
    for (unsigned int i = b; i < e; i++) {
        //g << v[i] << ' ';
        ++cnt[(v[i] & mask) >> p];
    }
    //g << '\n';

    unsigned int ptr[BITS + 1];
    ptr[0] = b;
    for (unsigned int c = 1; c <= BITS; c++) {
        ptr[c] = ptr[c - 1] + cnt[c - 1];
        //g << "(" << ptr[c] << "; " << cnt[c] << ") ";
    }
    //g << '\n';
    
    for (unsigned int i = b; i < e; i++) {
        const unsigned int c = (v[i] & mask) >> p;
        //assert(ptr[c] >= b && ptr[c] < e);
        //assert(ptr[c] >= 0 && ptr[c] < N);
        vcopy[ptr[c]++] = v[i];
    }
    //g << '\n';

    if (p < 8)
        return;
    
    for (unsigned int c = 0; c <= BITS; c++)
        if (cnt[c] > 0) {
            sort(p - 8, ptr[c] - cnt[c], ptr[c], vcopy, v);
        }
}
 
int main() {
    unsigned int A, B, C;

    f >> N >> A >> B >> C;
    unsigned int v[N], vcopy[N];
    v[0] = B;
    for (unsigned int i = 1; i < N; ++i) {
        v[i] = (1ULL * A * v[i - 1] + B) % C;
    }

    sort(24, 0, N, v, vcopy);

    stringstream s;
    for (unsigned int i = 0; i < N; i += 10)
        s << v[i] << ' ';
    s << '\n';

    g << s.str();
 
    f.close();
    g.close();
    return 0;
}