Pagini recente » Cod sursa (job #1927922) | Cod sursa (job #3215752) | Cod sursa (job #3270415) | Cod sursa (job #846373) | Cod sursa (job #2639231)
use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
const INPUT: &'static str = "sortaret.in";
const OUTPUT: &'static str = "sortaret.out";
fn main() -> std::io::Result<()> {
let input = BufReader::new(File::open(INPUT)?);
let mut output = BufWriter::new(
OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(OUTPUT)?,
);
let mut lines = input.lines().into_iter().map(|line| {
let data = line.unwrap();
let mut line = data
.split_whitespace()
.map(|number| number.parse::<usize>().unwrap());
(line.next().unwrap()-1, line.next().unwrap()-1)
});
let (n, _) = lines.next().unwrap();
let mut counts = vec![0; n+1];
let mut graph = vec![vec![]; n+1];
for (x, y) in lines.into_iter() {
graph[x].push(y);
counts[y] += 1;
}
let mut fringe: Vec<_> = counts
.iter()
.enumerate()
.filter(|&(_, &n)| n == 0)
.map(|(i, _)| i)
.collect();
while let Some(x) = fringe.pop() {
writeln!(&mut output, "{}", x+1)?;
for &y in &graph[x] {
match counts[y] {
0 => panic!("{}->{} is part of a circular dependency", x, y),
1 => {
counts[y] = 0;
fringe.push(y)
}
n => counts[y] = n - 1,
}
}
}
Ok(())
}