Cod sursa(job #3147782)

Utilizator andreioneaAndrei Onea andreionea Data 27 august 2023 03:52:25
Problema Radix Sort Scor 100
Compilator rs Status done
Runda Arhiva educationala Marime 1.56 kb
#![allow(non_snake_case)]
#![allow(unused_variables)]
use std::fs;
use std::fs::File;
use std::io::BufWriter;
use std::io::prelude::*;

fn main(){
    let contents = fs::read_to_string("radixsort.in").expect("File empty!");
    let (N, ABC) = contents.split_once(" ").unwrap();
    let (A, BC) = ABC.split_once(" ").unwrap();
    let (B, C) = BC.split_once(" ").unwrap();
    let C = C.trim();
    let N = N.parse::<u32>().unwrap();
    let A = A.parse::<u32>().unwrap();
    let B = B.parse::<u32>().unwrap();
    let C = C.parse::<u32>().unwrap();

    let mut V: Vec<u32> = Vec::with_capacity(N as usize);
    V.push(B);
    for _ in 1..N {
        let x = (*V.last().unwrap() as usize * A as usize + B as usize) % C as usize;
        V.push(x as u32);
    }

    let mut U = vec![0u32; N as usize];
    for digit_idx in 0..4 {
        let mut offsets = vec![0usize; 256];
        let mut counts = vec![0usize; 256];
        V.iter().for_each(|x| {
            let digit = ((x >> digit_idx * 8) & 0xff) as usize;
            counts[digit] += 1;
        });
        for digit in 1..=255 {
            offsets[digit] = offsets[digit - 1] + counts[digit - 1];
        }
        V.iter().for_each(|x| {
            let digit = ((x >> digit_idx * 8) & 0xff) as usize;
            let new_idx = offsets[digit];
            offsets[digit] += 1;
            U[new_idx] = *x;
        });
        std::mem::swap(&mut U, &mut V);
    }
    let mut writer = BufWriter::new(File::create("radixsort.out").unwrap());
    V.iter().step_by(10).for_each(|x| {
        write!(writer,"{x} ").unwrap();
    });
}