Cod sursa(job #2954984)

Utilizator Razvan48Capatina Razvan Nicolae Razvan48 Data 15 decembrie 2022 21:44:25
Problema Radix Sort Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
#include <fstream>
#include <vector>

using namespace std;

const int NMAX = 10000000;
const int HASH = 10; ///Putem sorta dupa cifre si in alte baze. Aici folosim baza 10.

int n;
int v[1 + NMAX];

vector<int> small;
vector<int> cifre[HASH];

void sortAux(int putereHash)
{
    small.clear();
    for (int i = 0; i < HASH; i++)
        cifre[i].clear();

    for (int i = 1; i <= n; i++)
    {
        if (v[i] < putereHash)
            small.emplace_back(v[i]);
        else
        {
            if (putereHash == 0)
                cifre[v[i] % HASH].emplace_back(v[i]);
            else
                cifre[v[i] / putereHash % HASH].emplace_back(v[i]);
        }
    }

    int n = 0;

    for (int i = 0; i < small.size(); i++)
    {
        n++;
        v[n] = small[i];
    }
    for (int i = 0; i < HASH; i++)
    {
        for (int j = 0; j < cifre[i].size(); j++)
        {
            n++;
            v[n] = cifre[i][j];
        }
    }
}

void radixSort()
{
    int maxim = -1;

    for (int i = 1; i <= n; i++)
        maxim = max(maxim, v[i]);

    int nrSortari = 1;
    int putereHash = 1;

    while (putereHash * HASH <= maxim)
    {
        putereHash *= HASH;
        nrSortari++;
    }

    putereHash = 0;

    for (int i = 1; i <= nrSortari; i++)
    {
        sortAux(putereHash);

        if (putereHash == 0)
            putereHash = HASH;
        else
            putereHash *= HASH;
    }
}

int main()
{
    ios_base::sync_with_stdio(false);

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

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

    v[1] = b;

    for (int i = 2; i <= n; i++)
        v[i] = (1ll * a * v[i - 1] + b) % c;

    radixSort();

    for (int i = 1; i <= n; i += 10)
        out << v[i] << ' ';
    out << '\n';

    in.close();
    out.close();

    return 0;
}