package main import ( "bufio" "fmt" "os" "strconv" ) func configure(scanner *bufio.Scanner) { scanner.Split(bufio.ScanWords) scanner.Buffer(make([]byte, 1000005), 1000005) } func getNextString(scanner *bufio.Scanner) string { scanned := scanner.Scan() if !scanned { panic("scan failed") } return scanner.Text() } func getNextInt(scanner *bufio.Scanner) int { i, _ := strconv.Atoi(getNextString(scanner)) return i } func getNextInt64(scanner *bufio.Scanner) int64 { i, _ := strconv.ParseInt(getNextString(scanner), 10, 64) return i } func getNextFloat64(scanner *bufio.Scanner) float64 { i, _ := strconv.ParseFloat(getNextString(scanner), 64) return i } func main() { fp := os.Stdin wfp := os.Stdout extra := 0 if os.Getenv("I") == "IronMan" { fp, _ = os.Open(os.Getenv("END_GAME")) extra = 100 } scanner := bufio.NewScanner(fp) configure(scanner) writer := bufio.NewWriter(wfp) defer func() { r := recover() if r != nil { fmt.Fprintln(writer, r) } writer.Flush() }() solve(scanner, writer) for i := 0; i < extra; i++ { fmt.Fprintln(writer, "-----------------------------------") solve(scanner, writer) } } func solve(scanner *bufio.Scanner, writer *bufio.Writer) { n := getNextInt(scanner) g := newGraph(n) for i := 1; i < n; i++ { a := getNextInt(scanner) g.appendEdge(a, i, i-1) } g.seg = newSegment(n) g.dfs(0, -1) var ans int for i := 0; i < n; i++ { ans += g.v[i].c } fmt.Fprintln(writer, ans) } type vertex struct { c int } type edge struct { to, id int } type graph struct { v []vertex e [][]edge seg segment } func newGraph(n int) graph { return graph{ v: make([]vertex, n), e: make([][]edge, n), } } func (g *graph) appendEdge(from, to, id int) { g.e[from] = append(g.e[from], edge{ to: to, id: id, }) } func (g *graph) dfs(i, p int) { g.v[i].c = g.seg.query(0, i, 0, g.seg.add) g.seg.update(i, 1, g.seg.add) for _, e := range g.e[i] { if e.to == p { continue } g.dfs(e.to, i) } g.seg.update(i, 0, g.seg.add) } type segment [][]int func newSegment(n int) segment { seg := make(segment, 0) for n > 1 { seg = append(seg, make([]int, n)) n = (n + 1) >> 1 } seg = append(seg, make([]int, 1)) return seg } func (seg segment) update(i int, v int, f func(int, int) int) { seg[0][i] = v for h := 1; h < len(seg); h++ { i >>= 1 if i<<1+1 < len(seg[h-1]) { seg[h][i] = f(seg[h-1][i<<1], seg[h-1][i<<1+1]) } else { seg[h][i] = seg[h-1][i<<1] } } } func (seg segment) query(l, r int, s int, f func(int, int) int) int { for h := 0; h < len(seg) && l < r; h++ { if l&1 == 1 { s = f(s, seg[h][l]) l++ } l >>= 1 if r&1 == 1 { s = f(s, seg[h][r-1]) } r >>= 1 } return s } func (seg segment) add(x, y int) int { return x + y } func (seg segment) min(x, y int) int { if x < y { return x } return y } func (seg segment) max(x, y int) int { return -seg.min(-x, -y) }