以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();
, m);
work(n.clear();
buf}
}
这样遇到空行也不会panic。
注意有一组测试数据是用非空格或者多个空格隔开的,所以要用split_whitespace
。
ps: 还可以用BufReader加速stdin读取:https://seekstar.github.io/2021/11/17/rust%E7%94%A8bufreader%E5%8A%A0%E9%80%9Fstdin%E8%AF%BB%E5%8F%96/
完整代码:
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() {
+= 1;
cnt[depth] return depth + 1;
}
let mut mx = 0usize;
for v in &childs[cur] {
let v = *v;
= cmp::max(mx, dfs(&mut cnt, v, depth + 1, &childs));
mx }
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();
.push(c);
childs[fa]}
}
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();
, m);
work(n.clear();
buf}
}