算法竞赛中rust的一种比较健壮的读入

以PAT 甲级1004为例:https://pintia.cn/problem-sets/994805342720868352/exam/problems/994805521431773184?type=7&page=0

关键部位

fn main() {
    let mut buf = String::new();
    while io::stdin().read_line(&mut buf).unwrap() > 0 {
        let line = buf.trim();
        if line.len() == 0 {
            continue;
        }
        let mut s = line.split_whitespace();
        let n: usize = s.next().unwrap().parse().unwrap();
        if 0 == n {
            break;
        }
        let m: usize = s.next().unwrap().parse().unwrap();
        work(n, m);
        buf.clear();
    }
}

这样遇到空行也不会panic。

在这里插入图片描述
注意有一组测试数据是用非空格或者多个空格隔开的,所以要用split_whitespace

ps: 还可以用BufReader加速stdin读取:https://seekstar.github.io/2021/11/17/rust用bufreader加速stdin读取/

完整代码:

use std::io;
use std::cmp;

fn dfs(mut cnt: &mut Vec<usize>, cur: usize, depth: usize, childs: &Vec<Vec<usize>>) -> usize {
    if childs[cur].is_empty() {
        cnt[depth] += 1;
        return depth + 1;
    }
    let mut mx = 0usize;
    for v in &childs[cur] {
        let v = *v;
        mx = cmp::max(mx, dfs(&mut cnt, v, depth + 1, &childs));
    }
    return mx;
}

fn work(n: usize, m: usize) {
    let mut childs = vec![Vec::new(); n + 1];
    for _i in 0..m {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        let mut s = input.trim().split_whitespace();
        let fa: usize = s.next().unwrap().parse().unwrap();
        let num: usize = s.next().unwrap().parse().unwrap();
        for _i in 0..num {
            let c: usize = s.next().unwrap().parse().unwrap();
            childs[fa].push(c);
        }
    }
    let mut cnt = vec![0usize; n + 10];
    let depth = dfs(&mut cnt, 1, 0, &childs);
    print!("{}", cnt[0]);
    for i in 1..depth {
        print!(" {}", cnt[i]);
    }
    println!();
}

fn main() {
    let mut buf = String::new();
    while io::stdin().read_line(&mut buf).unwrap() > 0 {
        let line = buf.trim();
        if line.len() == 0 {
            continue;
        }
        let mut s = line.split_whitespace();
        let n: usize = s.next().unwrap().parse().unwrap();
        if 0 == n {
            break;
        }
        let m: usize = s.next().unwrap().parse().unwrap();
        work(n, m);
        buf.clear();
    }
}
posted @ 2024-09-28 14:16  寻找繁星  阅读(2)  评论(0编辑  收藏  举报