fn calc(index: usize, parents: &Vec) -> usize { parents.iter().filter(|&p| *p < index).count() } fn dfs(index: usize, children: &mut Vec>, parents: &mut Vec, result: &mut usize) { if children[index].is_empty() { *result += calc(index, parents); } while let Some(child) = children[index].pop() { parents.push(index); dfs(child, children, parents, result); parents.pop(); *result += calc(index, parents); } } fn main() { let mut n = String::new(); std::io::stdin().read_line(&mut n).ok(); let n: usize = n.trim().parse().unwrap(); let mut a = String::new(); std::io::stdin().read_line(&mut a).ok(); let mut children: Vec> = vec![vec![]; n]; a.trim().split_whitespace().map(|s| s.parse::().unwrap()).enumerate().for_each(|pair| { let current = pair.0 + 1; children[pair.1].push(current); }); let mut result: usize = 0; let mut parents: Vec = vec![]; dfs(0, &mut children, &mut parents, &mut result); println!("{}", result); }