Cod sursa(job #3313234)

Utilizator game_difficultyCalin Crangus game_difficulty Data 2 octombrie 2025 21:55:43
Problema Potrivirea sirurilor Scor 100
Compilator rs Status done
Runda Arhiva educationala Marime 2.35 kb
use std::fs::File;
#[allow(unused_imports)]
use std::io::{BufRead, BufReader, Read, Write};
#[allow(unused_imports)]
use std::{cmp::min, error::Error};

const FILE: &'static str = "strmatch";
const HASH_BASE: i64 = 256;
const HASH_MOD1: i64 = 1e9 as i64 + 7;
const HASH_MOD2: i64 = 1e7 as i64 + 1;

fn main() -> Result<(), Box<dyn Error>> {
    let mut fin = BufReader::new(File::open(format!("{}.in", FILE)).unwrap());
    let mut fout = File::create(format!("{}.out", FILE)).unwrap();

    //let mut debugfout = File::create("debug.out").unwrap();

    let mut a = String::new();
    let mut b = String::new();

    fin.read_line(&mut a)?;
    fin.read_line(&mut b)?;

    let a = a.trim().as_bytes();
    let m = a.len();
    let b = b.trim().as_bytes();
    let n = b.len();

    if m > n {
        write!(&mut fout, "0")?;
        return Ok(());
    }

    let mut a_hash1: i64 = 0;
    let mut a_hash2: i64 = 0;
    let mut b_hash1: i64 = 0;
    let mut b_hash2: i64 = 0;
    for i in 0..m {
        a_hash1 = (a_hash1 * HASH_BASE + a[i] as i64) % HASH_MOD1;
        a_hash2 = (a_hash2 * HASH_BASE + a[i] as i64) % HASH_MOD2;
        b_hash1 = (b_hash1 * HASH_BASE + b[i] as i64) % HASH_MOD1;
        b_hash2 = (b_hash2 * HASH_BASE + b[i] as i64) % HASH_MOD2;
    }
    let mut b_power1: i64 = 1;
    let mut b_power2: i64 = 1;
    for _i in 1..m {
        b_power1 = (b_power1 * HASH_BASE) % HASH_MOD1;
        b_power2 = (b_power2 * HASH_BASE) % HASH_MOD2;
    }

    let mut sz = 0;
    let mut ans = Vec::new();
    for i in 0..=n - m {
        if a_hash1 == b_hash1 && a_hash2 == b_hash2 {
            sz += 1;
            if sz <= 1000 {
                write!(&mut ans, "{} ", i.to_string())?;
            }
        }
        b_hash1 = b_hash1 - (b[i] as i64 * b_power1) % HASH_MOD1;
        b_hash2 = b_hash2 - (b[i] as i64 * b_power2) % HASH_MOD2;
        if b_hash1 < 0 {
            b_hash1 += HASH_MOD1;
        }
        if b_hash2 < 0 {
            b_hash2 += HASH_MOD2;
        }
        if i + m < b.len() {
            b_hash1 = (b_hash1 * HASH_BASE + b[i + m] as i64) % HASH_MOD1;
            b_hash2 = (b_hash2 * HASH_BASE + b[i + m] as i64) % HASH_MOD2;
        }
    }

    writeln!(&mut fout, "{}", sz)?;
    // for &x in &ans[0..(min(ans.len(), 1000))] {
    //     write!(&mut fout, "{} ", x)?;
    // }
    writeln!(&mut fout, "{}", String::from_utf8(ans)?)?;

    Ok(())
}