← Home
```go
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

func readInt(in *bufio.Reader) int {
	n := 0
	c, err := in.ReadByte()
	for err == nil && c <= ' ' {
		c, err = in.ReadByte()
	}
	if err != nil {
		return 0
	}
	for err == nil && c > ' ' {
		n = n*10 + int(c-'0')
		c, err = in.ReadByte()
	}
	return n
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	n := readInt(in)
	m := readInt(in)

	adj := make([][]int, n+1)
	up := make([][20]int, n+1)
	depth := make([]int, n+1)

	for i := 2; i <= n; i++ {
		p := readInt(in)
		up[i][0] = p
		depth[i] = depth[p] + 1
		adj[p] = append(adj[p], i)
		for j := 1; j < 20; j++ {
			up[i][j] = up[up[i][j-1]][j-1]
		}
	}

	tin := make([]int, n+1)
	tout := make([]int, n+1)
	timer := 0

	var dfs func(v int)
	dfs = func(v int) {
		timer++
		tin[v] = timer
		for _, u := range adj[v] {
			dfs(u)
		}
		tout[v] = timer
	}
	dfs(1)

	isAncestor := func(u, v int) bool {
		return tin[u] <= tin[v] && tout[u] >= tout[v]
	}

	getChildAncestor := func(x, y int) int {
		curr := y
		for i := 19; i >= 0; i-- {
			if depth[curr]-(1<<i) > depth[x] {
				curr = up[curr][i]
			}
		}
		return curr
	}

	type Player struct {
		x, y, top, typ int
	}
	players := make([]Player, 0, m)

	for i := 0; i < m; i++ {
		x := readInt(in)
		y := readInt(in)

		if x == up[y][0] || y == up[x][0] {
			fmt.Fprintln(out, "-1")
			return
		}

		if isAncestor(y, x) {
			x, y = y, x
		}

		if isAncestor(x, y) {
			ux := getChildAncestor(x, y)
			players = append(players, Player{x, y, ux, 1})
		} else {
			players = append(players, Player{x, y, 1, 2})
		}
	}

	sort.Slice(players, func(i, j int) bool {
		return depth[players[i].top] > depth[players[j].top]
	})

	bit := make([]int, n+2)
	add := func(idx, val int) {
		for ; idx <= n; idx += idx & -idx {
			bit[idx] += val
		}
	}
	query := func(idx int) int {
		sum := 0
		for ; idx > 0; idx -= idx & -idx {
			sum += bit[idx]
		}
		return sum
	}
	queryRange := func(l, r int) int {
		if l > r {
			return 0
		}
		return query(r) - query(l-1)
	}

	ans := 0
	for _, p := range players {
		hit := false
		if p.typ == 1 {
			cntUx := queryRange(tin[p.top], tout[p.top])
			cntY := queryRange(tin[p.y], tout[p.y])
			if cntUx-cntY > 0 {
				hit = true
			}
		} else {
			cntT := queryRange(1, n)
			cntX := queryRange(tin[p.x], tout[p.x])
			cntY := queryRange(tin[p.y], tout[p.y])
			if cntT-cntX-cntY > 0 {
				hit = true
			}
		}
		if !hit {
			ans++
			add(tin[p.top], 1)
		}
	}

	fmt.Fprintln(out, ans)
}
```