Cod sursa(job #2999094)

Utilizator popoiu.georgeGeorge Popoiu popoiu.george Data 10 martie 2023 15:01:17
Problema BFS - Parcurgere in latime Scor 100
Compilator rs Status done
Runda Arhiva educationala Marime 1.4 kb
use std::{error::Error, fs::File, io::{LineWriter, BufReader, BufRead, Write}, collections::VecDeque};
fn main() -> Result<(), Box<dyn Error>> {
    let file = File::open("bfs.in")?;
    let out_file = File::create("bfs.out")?;
    let mut writer = LineWriter::new(out_file);
    let reader = BufReader::new(file);
    let mut lines = reader.lines();
    let first_line = lines.next().unwrap().unwrap();
    let mut it = first_line.split_whitespace();
    let n: usize = it.next().unwrap().parse()?;
    it.next();
    let s: i32 = it.next().unwrap().parse()?;
    let mut LA: Vec<Vec<i32>> = Vec::with_capacity(n + 1);
    let mut C: Vec<i32> = Vec::with_capacity(n + 1);
    LA.resize(n+1, Vec::default());
    C.resize(n+1, -1);
    for line in lines {
        let line_s = line.unwrap();
        let mut it = line_s.split_whitespace();
        let a: usize = it.next().unwrap().parse()?;
        let b: i32 = it.next().unwrap().parse()?;
        (&mut LA[a]).push(b);
    }
    let mut Q: VecDeque<i32> = VecDeque::with_capacity(n + 1);
    Q.push_back(s);
    C[s as usize] = 0;
    while !Q.is_empty() {
        let a = Q.pop_front().unwrap();
        for b in &LA[a as usize] {
            if C[*b as usize] != -1 {
                continue;
            }
            C[*b as usize] = 1 + C[a as usize];
            Q.push_back(*b);
        }
    }
    for i in 1..n+1 {
        write!(writer, "{} ", C[i])?;
    }
    Ok(())
}