Cod sursa(job #3353964)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 12 mai 2026 22:25:32
Problema Radix Sort Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 10000000;

int v[NMAX + 1];
int val[NMAX + 1];
int nxt[NMAX + 1];

int head[10], last[10];
int nodeCnt;

void push(int bucket, int x) {
    ++nodeCnt;
    val[nodeCnt] = x;
    nxt[nodeCnt] = 0;

    if (head[bucket] == 0) {
        head[bucket] = last[bucket] = nodeCnt;
    } else {
        nxt[last[bucket]] = nodeCnt;
        last[bucket] = nodeCnt;
    }
}

bool empty(int bucket) {
    return head[bucket] == 0;
}

int front(int bucket) {
    return val[head[bucket]];
}

void pop(int bucket) {
    head[bucket] = nxt[head[bucket]];

    if (head[bucket] == 0) {
        last[bucket] = 0;
    }
}

int nrc(int x) {
    if (x == 0) return 1;

    int res = 0;
    while (x > 0) {
        res++;
        x /= 10;
    }
    return res;
}

int main() {
    ifstream cin("radixsort.in");
    ofstream cout("radixsort.out");

    int n, a, b, c;
    cin >> n >> a >> b >> c;

    int pasi = 0;

    v[1] = b;
    pasi = max(pasi, nrc(v[1]));

    for (int i = 2; i <= n; i++) {
        v[i] = (1LL * a * v[i - 1] + b) % c;
        pasi = max(pasi, nrc(v[i]));
    }

    int p = 1;

    for (int step = 1; step <= pasi; step++) {
        for (int i = 0; i <= 9; i++) {
            head[i] = last[i] = 0;
        }

        nodeCnt = 0;

        for (int j = 1; j <= n; j++) {
            int digit = (v[j] / p) % 10;
            push(digit, v[j]);
        }

        int nr = 0;

        for (int digit = 0; digit <= 9; digit++) {
            while (!empty(digit)) {
                v[++nr] = front(digit);
                pop(digit);
            }
        }

        p *= 10;
    }

    for (int i = 1; i <= n; i += 10) {
        cout << v[i] << ' ';
    }

    return 0;
}