Pagini recente » Cod sursa (job #3316001) | Cod sursa (job #3320438) | Cod sursa (job #3329300) | Cod sursa (job #3322514) | Cod sursa (job #3313224)
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_MOD: 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_hash: i64 = 0;
let mut b_hash: i64 = 0;
for i in 0..m {
a_hash = (a_hash * HASH_BASE + a[i] as i64) % HASH_MOD;
b_hash = (b_hash * HASH_BASE + b[i] as i64) % HASH_MOD;
}
let mut b_power: i64 = 1;
for _i in 1..m {
b_power = (b_power * HASH_BASE) % HASH_MOD;
}
let mut sz = 0;
let mut ans = Vec::new();
for i in 0..=n - m {
if a_hash == b_hash {
if a[..] == b[i..i + m] {
write!(&mut ans, "{} ", i.to_string())?;
sz += 1;
}
}
b_hash = b_hash - (b[i] as i64 * b_power) % HASH_MOD;
if b_hash < 0 {
b_hash += HASH_MOD
}
if i + m < b.len() {
b_hash = (b_hash * HASH_BASE + b[i + m] as i64) % HASH_MOD;
}
}
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(())
}