Mitya has a rooted tree with $n$ vertices indexed from $1$ to $n$, where the root has index $1$. Each vertex $v$ initially had an integer number $a_v \ge 0$ written on it. For every vertex $v$ Mitya has computed $s_v$: the sum of all values written on the vertices on the path from vertex $v$ to the root, as well as $h_v$ — the depth of vertex $v$, which denotes the number of vertices on the path from vertex $v$ to the root. Clearly, $s_1=a_1$ and $h_1=1$.

Then Mitya erased all numbers $a_v$, and by accident he also erased all values $s_v$ for vertices with even depth (vertices with even $h_v$). Your task is to restore the values $a_v$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $a_v$ for all vertices in the tree.


-----Input-----

The first line contains one integer $n$ — the number of vertices in the tree ($2 \le n \le 10^5$). The following line contains integers $p_2$, $p_3$, ... $p_n$, where $p_i$ stands for the parent of vertex with index $i$ in the tree ($1 \le p_i < i$). The last line contains integer values $s_1$, $s_2$, ..., $s_n$ ($-1 \le s_v \le 10^9$), where erased values are replaced by $-1$.


-----Output-----

Output one integer — the minimum total sum of all values $a_v$ in the original tree, or $-1$ if such tree does not exist.


-----Examples-----
Input
5
1 1 1 1
1 -1 -1 -1 -1

Output
1

Input
5
1 2 3 1
1 -1 2 -1 -1

Output
2

Input
3
1 2
2 -1 1

Output
-1

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Greedy algorithms

Tree algorithms

Graph traversal

Constructive algorithms


Solutions:
from collections import deque

class Graph(object):

	def __init__(self, n, d):
		self.n = n
		self.graph = [[] for i in range(n)]
		self.parent = [-1 for i in range(n)]
		self.directed = d

	def addEdge(self, x, y):
		self.graph[x].append(y)
		if not self.directed:
			self.graph[y].append(x)

	def bfs(self, root):
		self.parent = [-1 for i in range(self.n)]
		queue = [root]
		queue = deque(queue)
		vis = [0] * self.n
		ans = 0
		while len(queue) != 0:
			element = queue.popleft()
			vis[element] = 1
			if self.parent[element] != -1 and s[element] != -1:
				if s[self.parent[self.parent[element]]] > s[element]:
					return False
			flag = 0
			for i in self.graph[element]:
				if vis[i] == 0:
					flag = 1
					queue.append(i)
					self.parent[i] = element
		return True

	def dfs(self, root, ans):
		stack = [root]
		vis = [0] * self.n
		stack2 = []
		while len(stack) != 0:
			element = stack.pop()
			if vis[element]:
				continue
			vis[element] = 1
			stack2.append(element)
			for i in self.graph[element]:
				if vis[i] == 0:
					self.parent[i] = element
					stack.append(i)
		while len(stack2) != 0:
			element = stack2.pop()
			m = 10 ** 18
			if s[element] == -1:
				for i in self.graph[element]:
					if i != self.parent[element]:
						m = min(m, ans[i])
				if m == 10 ** 18:
					m = 0
					ans[element] = 0
				else:
					ans[element] = m
			for i in self.graph[element]:
				if i != self.parent[element]:
					ans[i] = max(ans[i] - ans[element], 0)
		return ans

	def shortestpath(self, source, dest):
		self.bfs(source)
		path = [dest]
		while self.parent[path[-1]] != -1:
			path.append(parent[path[-1]])
		return path[::-1]

	def ifcycle(self):
		self.bfs(0)
		queue = [0]
		vis = [0] * n
		queue = deque(queue)
		while len(queue) != 0:
			element = queue.popleft()
			vis[element] = 1
			for i in graph[element]:
				if vis[i] == 1 and i != parent[element]:
					return True
				if vis[i] == 0:
					queue.append(i)
					vis[i] = 1
		return False

	def reroot(self, root, ans):
		stack = [root]
		vis = [0] * n
		while len(stack) != 0:
			e = stack[-1]
			if vis[e]:
				stack.pop()
				continue
			vis[e] = 1
			for i in graph[e]:
				if not vis[e]:
					stack.append(i)
			if self.parent[e] == -1:
				continue
n = int(input())
g = Graph(n, False)
p = list(map(int, input().split()))
s = list(map(int, input().split()))
for i in range(len(p)):
	g.addEdge(i + 1, p[i] - 1)
if not g.bfs(0):
	print(-1)
	exit()
s = g.dfs(0, s)
print(sum(s))


n = int(input())
parents = ['None'] + list(map(int, input().rstrip().split()))
weights = list(map(int, input().rstrip().split()))
children = [[] for i in range(0, n)]
weightvalue = [0] * n
weightvalue[0] = weights[0]
for i in range(1, n):
	k = parents[i]
	children[k - 1].append(i + 1)
check = 0
for i in range(1, n):
	if weights[i] == -1:
		if not children[i] == []:
			childweights = []
			for c in children[i]:
				childweights.append(weights[c - 1])
			m = min(childweights)
		else:
			m = weights[parents[i] - 1]
		if m < weights[parents[i] - 1]:
			check = -1
		else:
			weightvalue[i] = m - weights[parents[i] - 1]
			weights[i] = weights[parents[i] - 1] + weightvalue[i]
	elif weights[i] - weights[parents[i] - 1] < 0:
		check = -1
	else:
		weightvalue[i] = weights[i] - weights[parents[i] - 1]
if check == -1:
	print(-1)
else:
	print(sum(weightvalue))


from collections import deque
n = int(input())
graph = {i: set() for i in range(1, n + 1)}
P = list(map(int, input().split()))
S = [0] + list(map(int, input().split()))
for i in range(n - 1):
	graph[P[i]].add(i + 2)
Q = deque([1])
used = [0] * (n + 1)
ans = S[1]
kek = {1: S[1]}
used[1] = 1
while Q:
	v = Q.popleft()
	for u in graph[v]:
		if used[u] == 0:
			used[u] = 1
			Q.append(u)
			if S[u] != -1:
				if kek[v] > S[u]:
					print(-1)
					exit(0)
				ans += S[u] - kek[v]
				kek[u] = S[u]
			else:
				sos = set()
				for u2 in graph[u]:
					sos.add(S[u2])
				if sos:
					x = min(sos)
					if kek[v] <= x:
						ans += x - kek[v]
						kek[u] = x
					else:
						print(-1)
						exit(0)
print(ans)


n = int(input())
P = [-1] + [int(a) - 1 for a in input().split()]
S = [int(a) for a in input().split()]
T = [s for s in S]
for i in range(1, n):
	if S[P[i]] < 0:
		if T[P[i]] < 0:
			T[P[i]] = S[i]
		else:
			T[P[i]] = min(T[P[i]], S[i])
for i in range(1, n):
	if T[i] < 0:
		T[i] = T[P[i]]
S = [t for t in T]
ans = S[0]
for i in range(1, n):
	if S[i] < S[P[i]]:
		print(-1)
		break
	else:
		ans += S[i] - S[P[i]]
else:
	print(ans)


class Node:

	def __init__(self):
		self.curV = None
		self.totV = None
		self.children = []
		self.parent = None
N = int(input())
relations = list(map(int, input().split()))
totValues = list(map(int, input().split()))
allNodes = []
for n in range(N + 1):
	node = Node()
	allNodes.append(node)
for i in range(len(relations)):
	allNodes[relations[i]].children.append(i + 2)
	allNodes[i + 2].parent = relations[i]
for i in range(0, len(totValues)):
	allNodes[i + 1].totV = totValues[i]
allNodes[1].curV = totValues[0]
allNodes[0].curV = 0
curChildren = allNodes[1].children.copy()
isFine = True
while curChildren != [] and isFine:
	newChildren = []
	for c in curChildren:
		child = allNodes[c]
		if child.totV == -1:
			if child.children != []:
				curMin = allNodes[child.children[0]].totV
				for grandC in child.children:
					curMin = min(allNodes[grandC].totV, curMin)
				if curMin < allNodes[child.parent].totV:
					isFine = False
					break
				child.totV = curMin
				child.curV = child.totV - allNodes[child.parent].totV
				newChildren += child.children
			else:
				child.totV = allNodes[child.parent].totV
				child.curV = 0
		elif child.totV < allNodes[child.parent].totV:
			isFine = False
			break
		else:
			child.curV = -allNodes[child.parent].totV + child.totV
			newChildren += child.children
	curChildren = newChildren.copy()
if isFine:
	ans = 0
	for a in allNodes:
		ans += a.curV
	print(ans)
else:
	print(-1)


n = int(input())
p = list(map(int, input().split()))
c = {}
for i in range(0, n - 1):
	if p[i] in c:
		c[p[i]].append(i + 2)
	else:
		c[p[i]] = [i + 2]
x = dict(zip(range(2, n + 1), p))
s = [0] + list(map(int, input().split()))
a = [0] + [s[1]] + [0] * (n - 1)
stack = [1]
succ = True
while stack:
	p = stack.pop()
	if p in c:
		if s[p] != -1:
			if p != 1:
				a[p] = s[p] - s[x[p]]
		else:
			mn = 99999999999999
			for m in c[p]:
				if s[m] - s[x[p]] < mn:
					mn = s[m] - s[x[p]]
			if not succ:
				break
			if mn < 0:
				succ = False
				break
			else:
				a[p] = mn
				s[p] = s[x[p]] + mn
		for child in c[p]:
			stack.append(child)
	elif s[p] != -1:
		a[p] = s[p] - s[x[p]]
	else:
		a[p] = 0
		s[p] = s[x[p]]
if succ:
	print(sum(a))
else:
	print('-1')


n = int(input())
pa = {}
li = [0] + [0] + list(map(int, input().split()))
for i in range(2, n + 1):
	pa[i] = li[i]
d = pa.copy()
l2 = [0] + list(map(int, input().split()))
l1 = l2[:]
for i in range(2, n + 1):
	if l2[i] != -1 and l2[pa[i]] == -1:
		if l1[pa[i]] == -1:
			l1[pa[i]] = l2[i]
		else:
			l1[pa[i]] = min(l1[pa[i]], l2[i])
su = l1[1]
for i in range(2, n + 1):
	if l1[i] != -1:
		t = l1[i] - l1[pa[i]]
		if t < 0:
			print('-1')
			exit()
		su += t
print(su)


import sys
import math, bisect
sys.setrecursionlimit(10 ** 6)
from itertools import groupby, accumulate
from heapq import heapify, heappop, heappush
from collections import deque, Counter, defaultdict

def I():
	return int(sys.stdin.readline())

def neo():
	return map(int, sys.stdin.readline().split())

def Neo():
	return list(map(int, sys.stdin.readline().split()))
n = I()
parents = [0] + Neo()
values = Neo()
sv = values[:]
for i in range(1, n):
	if values[i] != -1:
		par = parents[i] - 1
		if sv[par] == -1:
			sv[par] = values[i]
		else:
			sv[par] = min(sv[par], values[i])
out = sv[0]
works = True
for i in range(1, n):
	if sv[i] != -1:
		a_val = sv[i] - sv[parents[i] - 1]
		if a_val >= 0:
			out += a_val
		else:
			works = False
			break
if works:
	print(out)
else:
	print(-1)


import sys

def getAndParseInt(num=1):
	string = sys.stdin.readline().strip()
	if num == 1:
		return int(string)
	else:
		return [int(part) for part in string.split()]

def getAndParseString(num=1, delim=' '):
	string = sys.stdin.readline().strip()
	if num == 1:
		return string
	else:
		return [part for part in string.split(delim)]
n = getAndParseInt()
parents = getAndParseInt(2)
sums = getAndParseInt(2)
pc_list = [[0, []] for i in range(n)]
a_list = [0] * n
a_list[0] = sums[0]
for (vertex, parent) in enumerate(parents):
	pc_list[vertex + 1][0] = parent - 1
	pc_list[parent - 1][1].append(vertex + 1)
stack = [(0, 0)]
invalid = False
while stack and (not invalid):
	(cur_vertex, child_num) = stack.pop()
	parent = pc_list[cur_vertex][0]
	cur_list = pc_list[cur_vertex][1]
	if not cur_list and sums[cur_vertex] == -1:
		a_list[cur_vertex] = 0
	elif sums[cur_vertex] == -1 and child_num == 0:
		min_sum = min([sums[child] for child in cur_list])
		if min_sum < sums[parent]:
			invalid = True
			break
		else:
			a_list[cur_vertex] = min_sum - sums[parent]
	elif sums[cur_vertex] != -1 and cur_vertex != 0 and (child_num == 0):
		grandparent = pc_list[parent][0]
		a_list[cur_vertex] = sums[cur_vertex] - a_list[parent]
		a_list[cur_vertex] += -sums[grandparent]
	if child_num < len(cur_list):
		stack.append((cur_vertex, child_num + 1))
		stack.append((cur_list[child_num], 0))
if invalid:
	print(-1)
else:
	print(sum(a_list))


from collections import deque

def main():
	n = int(input())
	p = list(map(int, input().split()))
	s = list(map(int, input().split()))
	s.insert(0, 0)
	a = [0] * len(s)
	a[1] = s[1]
	(child_dict, parent_dict) = ({}, {})
	for i in range(len(p)):
		if p[i] not in child_dict:
			child_dict[p[i]] = []
		child_dict[p[i]].append(i + 2)
		parent_dict[i + 2] = p[i]
	q = deque()
	q.append(1)
	while q:
		node = q.popleft()
		if s[node] == -1:
			if node not in child_dict or not child_dict[node]:
				s[node] = s[parent_dict[node]]
			else:
				s[node] = s[child_dict[node][0]]
				for x in child_dict[node]:
					s[node] = min(s[node], s[x])
		if node in child_dict:
			for x in child_dict[node]:
				q.append(x)
	for i in range(2, n + 1):
		a[i] = s[i] - s[parent_dict[i]]
		if a[i] < 0:
			print(-1)
			return
	print(sum(a))
main()


n = int(input())
parents = [0] + list(map(int, input().split()))
values = list(map(int, input().split()))
sv = values[:]
for i in range(1, n):
	if values[i] != -1:
		par = parents[i] - 1
		if sv[par] == -1:
			sv[par] = values[i]
		else:
			sv[par] = min(sv[par], values[i])
out = sv[0]
works = True
for i in range(1, n):
	if sv[i] != -1:
		a_val = sv[i] - sv[parents[i] - 1]
		if a_val >= 0:
			out += a_val
		else:
			works = False
			break
if works:
	print(out)
else:
	print(-1)


n = int(input())
L = [int(x) - 1 for x in input().split()]
V = [int(x) for x in input().split()]
G = []
DG = []
VD = []
VU = []
for i in range(n):
	G.append([])
	DG.append([])
	VD.append([])
	VU.append([])
for i in range(n - 1):
	DG[L[i]].append(i + 1)
	G[i + 1].append(L[i])
	G[L[i]].append(i + 1)
for i in range(n):
	for j in DG[i]:
		if V[j] != -1:
			VD[i].append(V[j])
for i in range(1, n):
	if V[L[i - 1]] != -1:
		VU[i].append(V[L[i - 1]])
depth = [0] * n
values = [0] * n
s = V[0]
depth[0] = 1
q = DG[0][:]
values[0] = V[0]
bad = False
while q:
	v = q.pop()
	q.extend(DG[v])
	depth[v] = 1 - depth[L[v - 1]]
	if depth[v] == 1:
		values[v] = V[v]
		s += values[v] - values[L[v - 1]]
		if values[v] - values[L[v - 1]] < 0:
			bad = True
	elif len(DG[v]) == 0:
		values[v] = 0
	else:
		values[v] = min((V[i] for i in DG[v]))
		s += values[v] - values[L[v - 1]]
		if values[v] - values[L[v - 1]] < 0:
			bad = True
if bad:
	print(-1)
else:
	print(s)


from collections import deque
import pdb
from math import *

def rI():
	return [int(i) for i in input().split()]
n = rI()[0]
p = [0, 0] + rI()
s = [0] + rI()
dat = [[] for i in range(n + 1)]
vis = [False for i in range(n + 1)]
a = [-1 for i in range(n + 1)]
a[1] = s[1]
a[0] = 0
for i in range(2, n + 1):
	dat[p[i]].append(i)
que = deque()
que.append(1)
for i in range(1, n + 1):
	if len(dat[i]) == 0:
		a[i] = 0
while len(que) != 0:
	c = que.popleft()
	vis[c] = True
	for i in dat[c]:
		if vis[i] is False:
			que.append(i)
	if s[c] != -1:
		continue
	if a[c] == -1:
		mn = 999999999999
		for i in dat[c]:
			if vis[i] is False:
				mn = min(s[i], mn)
		a[c] = mn - s[p[c]]
		if a[c] < 0:
			print(-1)
			exit()
		s[c] = s[p[c]] + a[c]
for i in range(2, n + 1):
	if s[i] == -1:
		a[i] = 0
	else:
		a[i] = s[i] - s[p[i]]
print(sum(a))


from collections import defaultdict, deque
n = int(input())
adj = [[] for _ in range(n)]
v = [0] * n
l = list(map(int, input().split()))
for (i, f) in enumerate(l):
	adj[f - 1].append(i + 1)
s = list(map(int, input().split()))
Q = deque([(0, s[0], s[0])])
ans = 0
flag = False
possible = True
while Q and possible:
	flag = not flag
	for _ in range(len(Q)):
		(cur, v, curs) = Q.popleft()
		if v < 0:
			possible = False
			ans = -1
			break
		ans += v
		if flag:
			for i in adj[cur]:
				if len(adj[i]) <= 1:
					Q.append((i, 0, curs))
				else:
					temp = min([s[k] for k in adj[i]])
					Q.append((i, temp - curs, temp))
		else:
			for i in adj[cur]:
				Q.append((i, s[i] - curs, s[i]))
print(ans)


import sys, bisect
input = sys.stdin.buffer.readline
n = int(input())
par = [-1] + list(map(int, input().split()))
ch = [[] for i in range(n)]
for i in range(1, n):
	par[i] -= 1
	ch[par[i]].append(i)
s = list(map(int, input().split()))
val = [0] * n
val[0] = s[0]
eve = [False] * n
tank = [0]
while tank:
	v = tank.pop()
	if s[v] == -1:
		eve[v] = True
		s[v] = s[par[v]]
	elif v != 0:
		val[v] = s[v] - s[par[v]]
		if val[v] < 0:
			print(-1)
			exit()
	for e in ch[v]:
		tank.append(e)
for i in range(n):
	if eve[i] and len(ch[i]) > 0:
		mi = val[ch[i][0]]
		for e in ch[i]:
			if mi > val[e]:
				mi = val[e]
		val[i] = mi
		for e in ch[i]:
			val[e] -= mi
print(sum(val))


from collections import *
n = int(input())
p = [0, 0] + list(map(int, input().split()))
s = [0] + list(map(int, input().split()))
g = defaultdict(list)
for i in range(2, len(p)):
	g[p[i]].append(i)
sum = s[1]
a = [0] + [0 for i in range(n)]
q = deque()
q.append(1)
while len(q) > 0:
	cur = q.popleft()
	for ch in g[cur]:
		q.append(ch)
	if cur == 1:
		continue
	elif s[cur] == -1:
		if len(g[cur]) > 0:
			a[cur] = min([s[val] for val in g[cur]]) - s[p[cur]]
			s[cur] = s[p[cur]] + a[cur]
			sum += a[cur]
			if a[cur] < 0:
				print(-1)
				exit(0)
	else:
		a[cur] = s[cur] - s[p[cur]]
		sum += a[cur]
print(sum)


n = int(input())
p = [0, 0] + list(map(int, input().split()))
s = [0] + list(map(int, input().split()))
for i in range(2, n + 1):
	if s[i] != -1 and (s[p[i]] == -1 or s[p[i]] > s[i]):
		s[p[i]] = s[i]
a = s[:]
for i in range(2, n + 1):
	if s[i] != -1:
		c = s[i] - s[p[i]]
		if c < 0:
			print(-1)
			exit()
		a[i] = c
	else:
		a[i] = 0
print(sum(a))


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict, deque
from math import inf

def main():
	n = int(input())
	parent = [0, 0] + list(map(int, input().split()))
	s = [0] + list(map(int, input().split()))
	ans = [-1] * (n + 1)
	graph = defaultdict(list)
	for i in range(2, n + 1):
		graph[parent[i]].append(i)
	q = deque([1])
	while q:
		z = q.popleft()
		if s[z] == -1:
			zz = inf
			for item in graph[z]:
				if s[item] != -1:
					zz = min(zz, s[item])
			if zz == inf:
				ans[z] = 0
				s[z] = s[parent[z]]
			else:
				ans[z] = zz - s[parent[z]]
				s[z] = zz
		else:
			ans[z] = s[z] - s[parent[z]]
		if ans[z] < 0:
			print(-1)
			exit()
		for item in graph[z]:
			q.append(item)
	print(sum(ans[1:]))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


n = int(input())
p = list(map(int, input().split()))
s = list(map(int, input().split()))

def solve():
	a = [None] * (n + 1)
	a[1] = s[0]
	for i in range(2, n + 1):
		if s[i - 1] == -1:
			continue
		parent = p[i - 2]
		parent_parent = p[parent - 2]
		if s[i - 1] < s[parent_parent - 1]:
			return -1
		new_value = s[i - 1] - s[parent_parent - 1]
		a[parent] = min(a[parent] if a[parent] is not None else float('inf'), new_value)
	for i in range(2, n + 1):
		if s[i - 1] == -1:
			continue
		parent = p[i - 2]
		parent_parent = p[parent - 2]
		a[i] = s[i - 1] - s[parent_parent - 1] - a[parent]
	return sum(filter(None, a))
print(solve())


from collections import *
n = int(input())
fa = [0, 0] + [int(i) for i in input().split()]
s = [0] + [int(i) for i in input().split()]
g = [[] for i in range(n + 1)]
for x in range(2, len(fa)):
	g[fa[x]].append(x)
sub = [0] * (n + 1)
q = deque([1])
rcr = []
while q:
	x = q.popleft()
	rcr.append(x)
	for y in g[x]:
		q.append(y)
rcr.reverse()
inf = int(10000000000.0)
s1 = [inf if i == -1 else i for i in s]
for x in rcr:
	sub[x] = s1[x]
	if g[x]:
		sub[x] = min(sub[x], min([sub[y] for y in g[x]]))
dp = [0] * (n + 1)
a = [0] * (n + 1)
q = deque(g[1])
a[1] = s[1] if s[1] != -1 else 0
dp[1] = a[1]
ans = a[1]
ok = 1
while q:
	x = q.popleft()
	if sub[x] == inf:
		a[x] = 0
	elif s[x] == -1:
		a[x] = sub[x] - dp[fa[x]]
	else:
		a[x] = s[x] - dp[fa[x]]
	if a[x] < 0:
		ok = 0
		break
	dp[x] = dp[fa[x]] + a[x]
	ans += a[x]
	for y in g[x]:
		q.append(y)
print(ans) if ok else print(-1)


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
from collections import deque
n = int(input())
l = list(map(int, input().split()))
s = list(map(int, input().split()))
graph = {i: set() for i in range(1, n + 1)}
for i in range(n - 1):
	graph[l[i]].add(i + 2)
level = [[] for i in range(n + 2)]
stack = [[1, 1]]
flag = 1
while stack:
	(x, y) = stack.pop()
	level[y].append(x)
	for i in graph[x]:
		stack.append([i, y + 1])
ans = [0 for i in range(n + 2)]
ans[1] = s[0]
for i in range(1, n + 1):
	if i % 2 == 0:
		for j in level[i]:
			papa = s[l[j - 2] - 1]
			if len(graph[j]) == 0:
				s[j - 1] = papa
				ans[j] = 0
			else:
				mi = float('infinity')
				for k in graph[j]:
					mi = min(mi, s[k - 1])
					if s[k - 1] < papa:
						flag = 0
						break
				ans[j] = mi - papa
				s[j - 1] = papa + ans[j]
	elif i > 1:
		for j in level[i]:
			papa = s[l[j - 2] - 1]
			ans[j] = s[j - 1] - papa
if flag == 0:
	print(-1)
else:
	print(sum(ans))


n = int(input())
p = list(map(int, input().split()))
ps = set(p)
s = list(map(int, input().split()))
ok = True
for i in range(1, n + 1):
	if not i in ps:
		if s[i - 1] == -1:
			m = s[p[i - 2] - 1]
		else:
			m = s[i - 1]
		j = i
		while j != 1:
			if m < s[j - 1]:
				ok = False
				break
			if s[j - 1] != -1:
				m = s[j - 1]
			j = p[j - 2]
		if m < s[0]:
			ok = False
	if not ok:
		break
if ok:
	sp = [-1] * n
	for i in range(n - 1):
		if sp[p[i] - 1] == -1:
			sp[p[i] - 1] = [i + 2]
		else:
			sp[p[i] - 1].append(i + 2)
	a = [0] * n
	a[0] = s[0]
	for i in range(1, n + 1):
		if s[i - 1] == -1 and sp[i - 1] != -1:
			m = s[sp[i - 1][0] - 1] - s[p[i - 2] - 1]
			for j in sp[i - 1]:
				m = min(m, s[j - 1] - s[p[i - 2] - 1])
			a[i - 1] = m
	for i in range(2, n + 1):
		if s[i - 1] != -1:
			a[i - 1] = s[i - 1] - s[p[p[i - 2] - 2] - 1] - a[p[i - 2] - 1]
	print(sum(a))
else:
	print(-1)


n = int(input())
p = [0, 0] + list(map(int, input().split()))
s = [0] + list(map(int, input().split()))
ht = [0] * (n + 1)
ht[1] = 1
from collections import defaultdict, deque
gr = defaultdict(list)
for i in range(2, n + 1):
	gr[p[i]].append(i)
q = deque()
q.append([1, -1])
while q:
	(x, pr) = q.popleft()
	for i in gr[x]:
		if i != pr:
			ht[i] = ht[x] + 1
			q.append([i, x])
a = [0] * (n + 1)
a[1] = s[1]
q.append([1, -1])
while q:
	(x, pr) = q.popleft()
	for ch in gr[x]:
		q.append([ch, x])
	if ht[x] % 2 == 0:
		mn = float('inf')
		for i in gr[x]:
			mn = min(mn, s[i] - s[p[x]])
		if mn != float('inf'):
			a[x] = mn
		for i in gr[x]:
			a[i] = s[i] - s[p[x]] - mn
tf = True
for i in a:
	if i < 0:
		tf = False
		break
if tf:
	print(sum(a))
else:
	print(-1)


def solve():
	n = int(input())
	p = list(map(int, input().split(' ')))
	s = list(map(int, input().split(' ')))
	MAX_VAL = 10 ** 9 + 2
	v_child = [None] * n
	for (i, p_i) in enumerate(p):
		idx = i + 1
		if v_child[p_i - 1]:
			v_child[p_i - 1].append(idx)
		else:
			v_child[p_i - 1] = [idx]

	def fill_s(v_idx, parent_s):
		if s[v_idx] == -1 and v_idx != 0:
			s_for_ch = parent_s
		else:
			s_for_ch = s[v_idx]
		if v_child[v_idx]:
			min_ch_s = MAX_VAL
			for ch_idx in v_child[v_idx]:
				ch_s = fill_s(ch_idx, s_for_ch)
				if 0 <= ch_s < min_ch_s:
					min_ch_s = ch_s
			if s[v_idx] == -1:
				if min_ch_s != MAX_VAL:
					s[v_idx] = min_ch_s
				else:
					s[v_idx] = s_for_ch
			elif s[v_idx] > min_ch_s:
				raise ValueError('')
		elif s[v_idx] == -1 and v_idx != 0:
			s[v_idx] = parent_s
		return s[v_idx]

	def get_a(v_idx):
		p_idx = p[v_idx - 1] - 1
		if s[v_idx] == -1:
			if v_idx == 0 or s[p_idx] == -1:
				return 0
			s[v_idx] = s[p_idx]
		a = s[v_idx]
		if v_child[v_idx]:
			for ch_idx in v_child[v_idx]:
				ch_a = get_a(ch_idx)
				if ch_a < 0:
					raise ValueError('')
				a += ch_a
		if v_idx > 0:
			a -= s[p_idx]
		return a
	try:
		fill_s(0, 0)
		print(get_a(0))
	except Exception as e:
		print(-1)
from sys import setrecursionlimit
setrecursionlimit(2 * 10 ** 5)
import threading
threading.stack_size(10 ** 8)
t = threading.Thread(target=solve)
t.start()
t.join()


import sys
import io, os
import math
gcd = math.gcd
ceil = math.ceil
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
mod1 = 10 ** 9 + 7
mod2 = 998244353

def strinp(testcases):
	k = 5
	if testcases == -1 or testcases == 1:
		k = 1
	f = str(input())
	f = f[2:len(f) - k]
	return f

def alp(a):
	return ord(a) - ord('a')

def main():
	n = int(input())
	graph = [[] for i in range(n)]
	par = list(map(int, input().split()))
	for i in range(n - 1):
		graph[par[i] - 1].append(i + 1)
	arr = list(map(int, input().split()))
	ans = [-1] * n
	ans[0] = arr[0]
	stk = []
	curr = 0
	nvis = [True] * n
	level = [1] * n
	level[0] = [1, 0]
	while True:
		nxt = -1
		temp = len(graph[curr])
		for i in range(temp - 1, -1, -1):
			if nvis[graph[curr][i]]:
				nxt = graph[curr][i]
				break
			else:
				graph[curr].pop()
		if stk != []:
			level[curr] = [level[stk[-1]][0] + 1, curr]
		if nxt != -1:
			stk.append(curr)
			nvis[curr] = False
			curr = nxt
		else:
			if curr == 0:
				break
			nvis[curr] = False
			curr = stk[-1]
			stk.pop(-1)
	level.sort()
	graph = [[] for i in range(n)]
	for i in range(n - 1):
		graph[par[i] - 1].append(i + 1)
	trig = False
	for i in range(n):
		if level[i][0] % 2 == 0:
			node = level[i][1]
			s1 = arr[par[node - 1] - 1]
			temp = len(graph[node])
			if temp == 0:
				ans[node] = 0
				continue
			mi = 10 ** 18
			for j in range(temp):
				s2 = arr[graph[node][j]]
				if s1 > s2:
					trig = True
					break
				else:
					mi = min(mi, s2 - s1)
			if trig:
				break
			ans[node] = mi
			for j in range(temp):
				s2 = arr[graph[node][j]]
				ans[graph[node][j]] = s2 - s1 - ans[node]
	if trig:
		print(-1)
	else:
		print(sum(ans))
main()


import sys
n = int(input())
p = list(map(int, input().split()))
s = list(map(int, input().split()))
children = []
for i in range(n):
	children.append([])
for i in range(n - 1):
	children[p[i] - 1].append(i + 1)
a = [-1] * n
a[0] = s[0]
for i in range(1, n):
	if s[i] == -1:
		if not children[i]:
			s[i] = s[p[i - 1] - 1]
		else:
			k = 10 ** 10
			for j in children[i]:
				k = min(k, s[j])
			s[i] = k
ans = a[0]
for i in range(1, n):
	if s[p[i - 1] - 1] > s[i]:
		print(-1)
		sys.exit()
	ans += s[i] - s[p[i - 1] - 1]
print(ans)


import math, sys, bisect, heapq, os
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
from functools import lru_cache
int1 = lambda x: int(x) - 1

def input():
	return sys.stdin.readline().rstrip('\r\n')
aj = lambda : list(map(int, input().split()))

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])

def solve():
	G = defaultdict(list)

	def addEdge(a, b):
		G[a].append(b)
	(n,) = aj()
	p = aj()
	p = [-1] + p
	s = aj()
	if -1 not in s:
		print(sum(s))
		exit(0)
	if s.count(0) + s.count(-1) == n:
		print(0)
		exit(0)
	mark = {}
	for i in range(n):
		if s[i] != -1:
			mark[i + 1] = s[i]

	def ddfs(node):
		st = deque()
		st.append(node)
		order = []
		while st:
			x = st.pop()
			order.append(x)
			for c in G.get(x, []):
				st.append(c)
		for z in range(n - 1, -1, -1):
			v = order[z]
			for nv in G.get(v, []):
				if nv != p[v - 1]:
					if s[v - 1] > mark.get(nv, float('inf')):
						print(-1)
						exit(0)
					mark[v] = min(mark.get(nv, float('inf')), mark.get(v, float('inf')))
	for (ii, i) in enumerate(p):
		addEdge(i, ii + 1)
	ddfs(1)
	ans = mark[1]
	for (ii, i) in enumerate(p):
		if ii == 0:
			continue
		if mark.get(ii + 1, float('inf')) != float('inf') and mark.get(i, float('inf')) != float('inf'):
			ans += abs(mark[ii + 1] - mark[i])
	print(ans)
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
solve()


from collections import defaultdict
n = int(input())
p = list(map(int, input().split()))
s = list(map(int, input().split()))
(clds, pars) = (defaultdict(list), [0] * (n + 1))
for i in range(n - 1):
	(cur, par) = (i + 2, p[i])
	clds[p[i]].append(cur)
	pars[cur] = par
(ans, ok) = (s[0], True)
(i, q) = (0, [1])
while i < len(q):
	cur = q[i]
	i += 1
	par_v = s[pars[cur] - 1]
	if cur in clds:
		(mmin, summ, k) = (float('inf'), 0, 0)
		for item in clds[cur]:
			mmin = min(mmin, s[item - 1])
			summ += s[item - 1]
			k += 1
			q.append(item)
		if s[cur - 1] != -1:
			continue
		if mmin < par_v:
			ok = False
			break
		ans -= par_v
		ans += summ - (k - 1) * mmin
if ok:
	print(ans)
else:
	print(-1)


from collections import defaultdict, deque
n = int(input())
p = list(map(int, input().split(' ')))
s = list(map(int, input().split(' ')))
a = [-1 for _ in range(n)]
c = defaultdict(list)
for (i, e) in enumerate(p):
	c[e].append(i + 2)
p = [1] + p
q = [1]
flag = 0
while q:
	elem = q.pop(0)
	q += c[elem]
	if elem == 1:
		a[elem - 1] = s[elem - 1]
	elif s[elem - 1] == -1:
		min_val = 0 if not c[elem] else min([s[x - 1] for x in c[elem]])
		a[elem - 1] = 0 if not c[elem] else min_val - s[p[elem - 1] - 1]
		s[elem - 1] = min_val
	else:
		if s[elem - 1] < s[p[p[elem - 1] - 1] - 1]:
			print('-1')
			q = deque([])
			flag = -1
			break
		a[elem - 1] = s[elem - 1] - s[p[elem - 1] - 1]
if flag == 0:
	print(sum(a))


n = int(input())
parents = list(map(int, input().split(' ')))
S = list(map(int, input().split(' ')))
children = [[] for i in range(n)]
for (i, parent) in enumerate(parents):
	children[parent - 1].append(i + 2)
A = S[:]
for i in range(1, len(A)):
	if A[i] != -1:
		A[i] -= S[parents[parents[i - 1] - 2] - 1]
		if A[i] < 0:
			print(-1)
			exit(0)
for i in range(1, len(A)):
	if A[i] == -1:
		if len(children[i]) == 0:
			A[i] = 0
		else:
			A[i] = min([A[j - 1] for j in children[i]])
		for j in children[i]:
			A[j - 1] -= A[i]
print(sum(A))


from collections import deque

def solve(p, s):
	children = {}
	parents = {}
	for (i, e) in enumerate(p):
		if e not in children:
			children[e] = []
		children[e].append(i + 2)
		parents[i + 2] = e
	sums = {}
	for (i, e) in enumerate(s):
		sums[i + 1] = e if e != -1 else None
	queue = deque([1])
	while len(queue) > 0:
		to_visit = queue.popleft()
		if to_visit in children:
			for child in children[to_visit]:
				queue.append(child)
		if sums[to_visit] is None:
			parent = sums[parents[to_visit]]
			if to_visit in children:
				min_child = min(map(lambda x: sums[x], children[to_visit]))
				if min_child - parent < 0:
					return -1
				sums[to_visit] = min_child
			else:
				sums[to_visit] = parent
	result = 0
	for key in sums:
		if key in parents:
			result += sums[key] - sums[parents[key]]
		else:
			result += sums[key]
	return result
n = int(input())
p = map(int, input().split())
s = map(int, input().split())
print(solve(p, s))


import sys
n = int(sys.stdin.readline().strip())
p = [0] + list(map(int, sys.stdin.readline().strip().split()))
s = list(map(int, sys.stdin.readline().strip().split()))
a = [s[0]] + [-1] * (n - 1)
children = [-1] * n
v = True
for i in range(1, n):
	parent = p[i] - 1
	if children[parent] == -1:
		children[parent] = []
	children[parent].append(i)
for i in range(0, n):
	if s[i] == -1:
		if children[i] == -1:
			s[i] = s[p[i] - 1]
			a[i] = 0
		else:
			m = s[children[i][0]]
			for j in children[i]:
				m = min([m, s[j]])
			M = s[p[i] - 1]
			a[i] = m - M
			s[i] = m
			if M > m:
				v = False
for i in range(0, n):
	if a[i] == -1:
		a[i] = s[i] - s[p[i] - 1]
		if a[i] < 0:
			v = False
if v == False:
	print(-1)
else:
	print(sum(a))


from sys import setrecursionlimit
setrecursionlimit(10000000)
import threading
threading.stack_size(67108864)

def main():
	n = int(input())
	a = list(map(int, input().split()))
	s = list(map(int, input().split()))
	u = []
	inf = 10 ** 9 + 1
	for i in range(n):
		u.append([])
	for i in range(n - 1):
		u[a[i] - 1].append(i + 1)
	a = [0] * n
	a[0] = s[0]
	use = [0] * n

	def dfs(v, p, pp):
		use[v] = 1
		if s[v] != -1 and pp != -1:
			s[p] = min(s[p], s[v])
		elif s[v] == -1 and len(u[v]) != 0:
			s[v] = inf
		elif s[v] == -1 and p != -1:
			s[v] = s[p]
		for i in u[v]:
			if use[i] == 0:
				dfs(i, v, p)
	dfs(0, -1, -1)

	def dfs1(v, p):
		if p != -1:
			a[v] = s[v] - s[p]
		for i in u[v]:
			dfs1(i, v)
	dfs1(0, -1)
	for i in range(n):
		if a[i] < 0:
			print(-1)
			exit()
	print(sum(a))
thread = threading.Thread(target=main)
thread.start()
thread.join()


import sys
n = int(input())
sys.setrecursionlimit(100 * 1000 + 100)
ch = [[] for _ in range(n)]
for (i, x) in enumerate(map(int, input().split(' ')), start=1):
	ch[x - 1].append(i)
s = list(map(int, input().split(' ')))
ans = 0

def dfs(v, buf):
	global ans
	while True:
		m = min((s[c] for c in ch[v]), default=buf) if s[v] == -1 else s[v]
		if m < buf:
			ans = -1
		if ans == -1:
			return
		ans += m - buf
		if len(ch[v]) == 1:
			v = ch[v][0]
			buf = m
			continue
		else:
			for c in ch[v]:
				dfs(c, m)
			break
dfs(0, 0)
print(ans)


n = int(input())
p = list(map(int, input().split()))
s = list(map(int, input().split()))
a = [0] * n
a[0] = s[0]
g = [[] for _ in range(n + 1)]
for i in range(n - 1):
	g[p[i]].append(i + 2)
for i in range(1, n):
	if s[i] == -1:
		if len(g[i + 1]) == 0:
			s[i] = s[p[i - 1] - 1]
		else:
			m = s[g[i + 1][0] - 1]
			for j in g[i + 1]:
				m = min(m, s[j - 1])
			s[i] = m
	if s[i] < s[p[i - 1] - 1]:
		print(-1)
		exit(0)
	else:
		a[i] = s[i] - s[p[i - 1] - 1]
print(sum(a))


n = int(input())

class Tree:
	height = 1

	def __init__(self, parent=None):
		self.nodes = []
		self.s = -1
		self.a = -1
		self.parent = parent
		if parent:
			self.height = parent.height + 1
			parent.nodes.append(self)
trs = [Tree()]
for i in map(int, input().split()):
	trs.append(Tree(trs[i - 1]))
for (i, s) in enumerate(map(int, input().split())):
	trs[i].s = s
trs.sort(key=lambda x: x.height)
trs[0].a = trs[0].s
res = trs[0].a
try:
	for t in trs[1:]:
		if t.s == -1:
			t.a = min(map(lambda x: x.s - t.parent.s, t.nodes), default=0)
			t.s = t.a + t.parent.s
		else:
			t.a = t.s - t.parent.s
		if t.a < 0:
			raise
		res += t.a
	print(res)
except:
	print(-1)


import collections
import sys

def read_arr():
	return map(int, input().split())
n = int(input())
parent = read_arr()
s = list(read_arr())
adjl = [[] for _ in range(n)]
for (i, p) in enumerate(parent):
	adjl[p - 1].append(i + 1)
Q = collections.deque()
Q.append((0, 0))
min_sum = 0
while Q:
	(root, curr_sum) = Q.pop()
	if s[root] != -1:
		av = s[root] - curr_sum
	else:
		if len(adjl[root]) > 0:
			min_s = min(map(lambda c: s[c], adjl[root]))
			av = min_s - curr_sum
		else:
			av = 0
		if av < 0:
			print(-1)
			sys.exit()
	min_sum += av
	for child in adjl[root]:
		Q.append((child, curr_sum + av))
print(min_sum)


n = int(input())
p = list(map(int, input().split()))
s = list(map(int, input().split()))
for i in range(len(p)):
	p[i] = p[i] - 1
p.insert(0, -1)
c = pow(10, 9) + 5
mina = [c for i in range(n)]
for i in range(1, n):
	if s[i] >= 0 and s[p[i]] < 0:
		mina[p[i]] = min(mina[p[i]], s[i])
for i in range(n):
	if s[i] < 0:
		if mina[i] == c:
			s[i] = s[p[i]]
		else:
			s[i] = mina[i]
ans = s[0]
flag = 0
for i in range(1, n):
	if s[i] < s[p[i]]:
		flag = 1
		print(-1)
		break
	ans += s[i] - s[p[i]]
if flag == 0:
	print(ans)


n = int(input())
p = list(map(int, input().split()))
s = list(map(int, input().split()))
tr = [[] for i in range(n + 1)]
for i in range(n - 1):
	tr[p[i]].append(i + 2)
st = [(1, 1)]
vis = [0] * (n + 1)
a = [0] * (n + 1)
a[1] = s[0]
vis[1] = 1
while st:
	(x, h) = st.pop()
	for i in tr[x]:
		if vis[i] == 0:
			if h % 2 == 0 and s[i - 1] == -1:
				exit(print(-1))
			elif h % 2 == 0:
				st.append((i, h + 1))
				a[i] = s[i - 1] - s[p[i - 2] - 1]
				if a[i] < 0:
					exit(print(-1))
			else:
				st.append((i, h + 1))
				m = 10000000000.0
				for j in tr[i]:
					m = min(m, s[j - 1])
				if len(tr[i]) == 0:
					m = s[p[i - 2] - 1]
				a[i] = m - s[p[i - 2] - 1]
				if a[i] < 0:
					exit(print(-1))
				s[i - 1] = s[p[i - 2] - 1] + a[i]
			vis[i] = 1
print(sum(a))


from collections import defaultdict, deque

def read_nums():
	return [int(x) for x in input().split()]

def main():
	(n,) = read_nums()
	graph = defaultdict(list)
	index = 2
	for parent in read_nums():
		graph[parent].append(index)
		index += 1
	index = 1
	vertex_values = {}
	for s in read_nums():
		vertex_values[index] = s
		index += 1
	output = {}
	if vertex_values[1] == -1:
		output[1] = 0
	else:
		output[1] = vertex_values[1]
	d = deque()
	for ch in graph[1]:
		d.appendleft((ch, output[1]))
	while len(d) > 0:
		(vertex, parent_sum) = d.pop()
		s = vertex_values[vertex]
		if s == -1:
			if len(graph[vertex]) == 0:
				output[vertex] = 0
			else:
				children_values = [vertex_values[ch] for ch in graph[vertex]]
				if any(map(lambda x: x < parent_sum, children_values)):
					print(-1)
					exit(0)
				else:
					output[vertex] = min(children_values) - parent_sum
		elif s < parent_sum:
			print(-1)
			exit(0)
		else:
			output[vertex] = s - parent_sum
		children = graph[vertex]
		for ch in children:
			d.appendleft((ch, parent_sum + output[vertex]))
	print(sum(output.values()))
main()


def core():
	n = int(input())
	p = [None, None] + [int(x) for x in input().split()]
	s = [None] + [int(x) for x in input().split()]
	ip = [[] for _ in range(n + 1)]
	for i in range(2, n + 1):
		ip[p[i]].append(i)
	a = [None, s[1]]
	for i in range(2, n + 1):
		if s[i] == -1:
			if ip[i]:
				s[i] = min((s[j] for j in ip[i]))
			else:
				s[i] = s[p[i]]
		a.append(s[i] - s[p[i]])
		if a[-1] < 0:
			return -1
	return sum(a[1:])
print(core())


from collections import deque, defaultdict
n = int(input())
g = defaultdict(list)
a = list(map(int, input().split()))
for i in range(n - 1):
	g[a[i]].append(i + 2)
	g[i + 2].append(a[i])
s = list(map(int, input().split()))
visited = [False] * (n + 1)
q = deque()
q.append(1)
visited[1] = True
val = [0] * (n + 1)
val[1] = s[0]
while len(q) > 0:
	v = q.popleft()
	b = []
	for i in g[v]:
		if not visited[i]:
			if s[v - 1] == -1:
				b.append(s[i - 1])
			elif v > 1:
				val[v] = s[v - 1] - s[g[v][0] - 1]
			q.append(i)
			visited[i] = True
	if b != [] and (not all([x >= s[g[v][0] - 1] for x in b])):
		print(-1)
		return
	elif b != []:
		val[v] = min(b) - s[g[v][0] - 1]
		s[v - 1] = val[v] + s[g[v][0] - 1]
	elif s[v - 1] != -1 and v > 1:
		val[v] = s[v - 1] - s[g[v][0] - 1]
print(sum(val))


def read(type=1):
	if type:
		file = open('input.dat', 'r')
		n = int(file.readline())
		line = list(map(int, file.readline().split()))
		line1 = list(map(int, file.readline().split()))
		file.close()
	else:
		n = int(input().strip())
		line = list(map(int, input().strip().split()))
		line1 = list(map(int, input().strip().split()))
	return (n, line, line1)

def solve():
	mins = [v[0]]
	kids = [-1 for i in range(n)]
	sol = v[0]
	for i in range(1, n):
		if v[i] != -1 and v[i] < mins[p[i - 1] - 1]:
			return -1
		mins.append(max(mins[p[i - 1] - 1], v[i]))
		if mins[i] < kids[p[i - 1] - 1] or kids[p[i - 1] - 1] == -1:
			kids[p[i - 1] - 1] = mins[i]
	for i in range(1, n):
		if kids[i] > mins[i]:
			mins[i] = kids[i]
		sol += mins[i] - mins[p[i - 1] - 1]
	return sol
(n, p, v) = read(0)
sol = solve()
print(sol)


from itertools import combinations
from sys import stdin
import math

def listIn():
	return list(map(int, stdin.readline().strip().split()))

def stringIn():
	return [x for x in stdin.readline().split()]

def intIn():
	return int(stdin.readline())

def ncr(n, k):
	res = 1
	c = [0] * (k + 1)
	c[0] = 1
	for i in range(1, n + 1):
		for j in range(min(i, k), 0, -1):
			c[j] = (c[j] + c[j - 1]) % MOD
	return c[k]
n = intIn()
p = listIn()
s = listIn()
p = [0] * 2 + p
s = [0] + s
if s.count(-1) == n - 1:
	print(s[1])
else:
	tree = {}
	par = [0] * (n + 1)
	for i in range(2, n + 1):
		if p[i] not in tree:
			tree[p[i]] = [i]
		else:
			tree[p[i]].append(i)
		par[i] = p[i]
	s2 = s[:]
	for ver in tree:
		l = tree[ver]
		if s[ver] == -1:
			count = 0
			for child in l:
				if s[child] != -1 and count == 0:
					s2[ver] = s[child]
					count += 1
				else:
					s2[ver] = min(s2[ver], s[child])
	total = s2[1]
	flag = False
	for i in range(2, n + 1):
		if s2[i] != -1:
			if s2[par[i]] == -1:
				s2[par[i]] = s2[par[par[i]]]
			val = s2[i] - s2[par[i]]
			if val < 0:
				flag = True
				break
			else:
				total += val
	if flag:
		print(-1)
	else:
		print(total)


parents = [0] * (10 ** 5 + 10)
children = [[] for x in range(10 ** 5 + 10)]
values = [0] * (10 ** 5 + 10)
n = int(input())
i = 1
for p in [int(x) for x in input().split()]:
	p -= 1
	children[p].append(i)
	parents[i] = p
	i += 1
sums = [int(x) for x in input().split()]
i = 0
to_check = [[0, 0]]
while i != len(to_check):
	[index, parent_sum] = to_check[i]
	if sums[index] == -1:
		if children[index]:
			min_value = sums[children[index][0]]
			for c in children[index]:
				min_value = min(min_value, sums[c])
			my_value = min_value - parent_sum
			if my_value < 0:
				print(-1)
				exit()
			values[index] = my_value
			sums[index] = min_value
		else:
			values[index] = 0
			sums[index] = parent_sum
	else:
		values[index] = sums[index] - parent_sum
	for c in children[index]:
		to_check.append([c, sums[index]])
	i += 1
print(sum(values))


from collections import defaultdict

def solve(tree, sum_dict):
	return solve_helper(1, tree, sum_dict, sum_dict[1], sum_dict[1])

def solve_helper(curr_node, tree, sum_dict, curr_sum, total):
	if len(tree[curr_node]) != 0:
		tree_totals = []
		for child in tree[curr_node]:
			if sum_dict[child] != -1:
				if curr_sum > sum_dict[child]:
					return -1
				else:
					tree_totals.append(solve_helper(child, tree, sum_dict, sum_dict[child], total + (sum_dict[child] - curr_sum)))
			else:
				tree_totals.append(solve_helper(child, tree, sum_dict, curr_sum, total))
		return sum(tree_totals)
	else:
		return sum_dict[curr_node] - curr_sum + total
n = int(input())
parents = list(map(int, input().split()))
sum_vals = list(map(int, input().split()))
tree = defaultdict(list)
sum_dict = defaultdict(int)
tree[1] = list()
for i in range(2, len(parents) + 2):
	tree[parents[i - 2]].append(i)
for i in range(1, n + 1):
	sum_dict[i] = sum_vals[i - 1]
values = [-1] * n
values[0] = sum_dict[1]
flag = True
for i in range(1, n + 1):
	if sum_dict[i] == -1:
		if len(tree[i]) != 0:
			children_vals = []
			parent_val = sum_vals[parents[i - 2] - 1]
			for child in tree[i]:
				if sum_dict[child] < parent_val:
					flag = False
				children_vals.append(sum_dict[child])
			min_children = min(children_vals)
			for child in tree[i]:
				values[child - 1] = sum_dict[child] - min_children
			values[i - 1] = min_children - parent_val
		else:
			values[i - 1] = 0
print(sum(values) if flag else -1)


n = int(input())
p = list(map(int, input().split()))
p = [-1] + [i - 1 for i in p]
s = list(map(int, input().split()))
g = {}
for i in range(n):
	g[i] = []
for i in range(1, len(p)):
	g[p[i]].append(i)
d = {}
md = 1
q = [(0, 1)]
while len(q) > 0:
	v = q[0]
	del q[0]
	nd = v[1] + 1
	if nd not in d:
		d[nd] = []
	for nv in g[v[0]]:
		q.append((nv, nd))
		d[nd].append(nv)
		md = max(md, nd)
sh = [0 for i in range(n)]
a = [0 for i in range(n)]
a[0] = s[0]
for dp in range(md, 0, -1):
	if dp % 2 == 0 or dp == 1:
		continue
	dc = {}
	for v in d[dp]:
		sv = s[v]
		gp = p[p[v]]
		gpv = s[gp]
		if sv < gpv:
			print(-1)
			exit()
		a[v] = sv - gpv
		pr = p[v]
		if pr not in dc:
			dc[pr] = 10 ** 15
		dc[pr] = min(dc[pr], a[v])
	for v in d[dp]:
		pr = p[v]
		a[v] -= dc[pr]
	for pr in dc:
		a[pr] = dc[pr]
print(sum(a))


tree = {1: []}
n = int(input())
p = list(map(int, input().split()))
s = list(map(int, input().split()))
a = [0] * n
a[0] = s[0]
for (i, e) in enumerate(p):
	if e in tree:
		tree[e].append(i + 2)
	else:
		tree[e] = [i + 2]
flag = 0
stack = [1]
while len(stack) != 0:
	root = stack.pop()
	rs = s[root - 1]
	if root not in tree:
		continue
	for i in tree[root]:
		stack.append(i)
		if s[i - 1] == -1 and i not in tree:
			s[i - 1] = rs
		elif s[i - 1] == -1:
			minn = int(1000000000.0 + 1)
			for j in tree[i]:
				if s[j - 1] < minn:
					minn = s[j - 1]
			s[i - 1] = minn
			if s[i - 1] < rs:
				flag = 1
				stack.clear()
				break
		elif s[i - 1] < rs:
			flag = 1
			stack.clear()
			break
		a[i - 1] = s[i - 1] - rs
if flag == 0:
	print(sum(a))
else:
	print(-1)


n = int(input())
arr = list(map(int, input().strip().split()))
sr = list(map(int, input().strip().split()))
gr = [[] for i in range(n)]
for i in range(len(arr)):
	gr[arr[i] - 1].append(i + 1)
q = [0]
liv = {0: 1}
par = {0: 0}
ans = [-1] * n
if sr[0] != -1:
	ans[0] = sr[0]
while q:
	ne = []
	for u in q:
		if sr[u] == -1:
			a = []
			for v in gr[u]:
				a.append(sr[v] - sr[par[u]])
			if len(a) == 0:
				continue
			ans[u] = min(a)
			for v in gr[u]:
				ans[v] = sr[v] - sr[par[u]] - ans[u]
				par[v] = u
				ne.append(v)
		else:
			for v in gr[u]:
				ans[v] = 0
				par[v] = u
				ne.append(v)
	q = ne
b = 0
for i in range(len(ans)):
	if ans[i] < 0:
		b = 1
if b == 1:
	print(-1)
else:
	print(sum(ans))


n = int(input())
p = list(map(int, input().split()))
sv = list(map(int, input().split()))
av = [0 for _ in range(n)]
visited = [False for _ in range(n)]

def addEdge(v, w):
	adj[v].append(w)
	adj[w].append(v)
INF = 1e+18
adj = [[] for i in range(n)]
for i in range(0, len(p)):
	addEdge(i + 1, p[i] - 1)
for i in range(0, n):
	visited[i] = True
	if sv[i] == -1:
		temp = INF
		for j in adj[i]:
			if visited[j] == False:
				temp = min(temp, sv[j])
		if temp == INF:
			sv[i] = sv[p[i - 1] - 1]
		else:
			sv[i] = temp
av[0] = sv[0]
for i in range(1, n):
	av[i] = sv[i] - sv[p[i - 1] - 1]
if min(av) < 0:
	print(-1)
else:
	print(sum(av))


class vertex:

	def __init__(self, v, sv, av=0):
		self.v = v
		self.sv = sv
		self.av = av
		self.child = []

	def sve(self):
		if self.child == []:
			return t.vert[pa[self.v - 2]].sv
		l = [t.vert[i].sv for i in self.child]
		return min(l)

class tree:

	def __init__(self):
		self.vert = {}
sum = 0
t = tree()
n = int(input())
pa = list(map(int, input().split()))
s = list(map(int, input().split()))
for i in range(1, n + 1):
	t.vert[i] = vertex(i, s[i - 1])
for i in range(n - 1):
	par = pa[i]
	t.vert[par].child.append(i + 2)
for i in range(1, n + 1):
	if t.vert[i].sv == -1:
		t.vert[i].sv = t.vert[i].sve()
for i in range(2, n + 1):
	k = t.vert[i].sv - t.vert[pa[t.vert[i].v - 2]].sv
	if k < 0:
		sum = -1
		break
	else:
		t.vert[i].av = k
if sum == -1:
	print(-1)
else:
	r = s[0]
	for i in range(2, n + 1):
		r += t.vert[i].av
	print(r)


from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
from collections import defaultdict as dd, deque

def data():
	return sys.stdin.readline().strip()

def mdata():
	return map(int, data().split())
mod = int(1000000000.0 + 7)
n = int(data())
t = [{} for i in range(n)]
P = list(mdata())
for i in range(n - 1):
	t[P[i] - 1][i + 1] = 0
A = list(mdata())
flag = True
v = [0] * n
v[0] = max(A[0], 0)
ans = v[0]
for i in range(0, n):
	if A[i] == -1:
		l = []
		for j in t[i]:
			if A[j] != -1:
				l.append(A[j])
		m = 0
		if len(l) > 0:
			m = min(l)
			if m < v[i]:
				print(-1)
				return
			ans += m - v[i]
			v[i] = m
	else:
		v[i] = A[i]
	for j in t[i]:
		if A[j] == -1:
			v[j] = v[i]
		elif A[j] < v[i]:
			print(-1)
			return
		else:
			v[j] = A[j]
		ans += v[j] - v[i]
print(ans)


def main():
	n = int(input())
	p = [0, None] + list(map(int, input().split()))
	s = [None] + list(map(int, input().split()))
	a = [None, s[1]] + [None] * (n - 1)
	children = [0]
	for i in range(n):
		children.append([])
	for i in range(2, n + 1):
		children[p[i]].append(i)
	broken = [False]

	def dostuff(parent, children, vals):
		small = vals[parent]
		for child in children[parent]:
			if len(children[child]) > 0:
				mini = min((s[guy] for guy in children[child]))
			else:
				mini = small
			if mini < small:
				broken[0] = True
			a[child] = mini - small
			for child1 in children[child]:
				a[child1] = s[child1] - mini
				dostuff(child1, children, vals)
	dostuff(1, children, s)
	if broken[0]:
		print(-1)
	else:
		print(sum(a[1:]))
import sys
import threading
sys.setrecursionlimit(2097152)
threading.stack_size(134217728)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()


def solve():
	num_nodes = int(input())
	parents = [0] + [int(x) - 1 for x in input().split()]
	S = [int(x) for x in input().split()]
	children = [[] for _ in parents]
	for (child, parent) in enumerate(parents):
		children[parent].append(child)
	for node in range(num_nodes):
		if S[node] == -1:
			S[node] = min((S[child] for child in children[node]), default=S[parents[node]])
	A = [None for _ in range(num_nodes)]
	A[0] = S[0]
	for node in range(1, num_nodes):
		A[node] = S[node] - S[parents[node]]
		if A[node] < 0:
			print('-1')
			return False
	print(sum(A))
solve()


n = int(input())
p = [1] + list(map(int, input().split()))
s = list(map(int, input().split()))
p = [i - 1 for i in p]
for i in range(1, n):
	if s[i] != -1 and (s[p[i]] == -1 or s[p[i]] > s[i]):
		s[p[i]] = s[i]
a = [s[0]] + [0] * (n - 1)
for i in range(1, n):
	if s[i] == -1:
		a[i] = 0
	else:
		a[i] = s[i] - s[p[i]]
		if a[i] < 0:
			print(-1)
			quit()
print(sum(a))


n = int(input())
lis1 = list(map(int, input().split()))
lis2 = list(map(int, input().split()))
lism = []
root = lis2[0]
c = root

class tree:

	def __init__(self, root):
		self.root = root
for i in range(n - 1):
	if lis2[i + 1] == -1:
		lism.append([lis1[i], lis2[i + 1], -1])
	else:
		lism.append([lis1[i], lis2[i + 1], 0])
lisc = lism.copy()
lism.sort()
for i in range(n - 1):
	if lism[i][1] != -1:
		temp = 0
		if lisc[lism[i][0] - 2][2] != -1:
			if lisc[lism[i][0] - 2][0] == 1:
				c += lism[i][1] - lisc[lism[i][0] - 2][2] - root
			else:
				c += lism[i][1] - lisc[lism[i][0] - 2][2] - lisc[lisc[lism[i][0] - 2][0] - 2][1]
			continue
		if lisc[lism[i][0] - 2][0] == 1:
			temp = lism[i][1] - root
			lisc[lism[i][0] - 2][2] = temp
			c += temp
		else:
			temp = lism[i][1] - lisc[lisc[lism[i][0] - 2][0] - 2][1]
			lisc[lism[i][0] - 2][2] = temp
			c += temp
		if temp < 0:
			print(-1)
			quit()
print(c)


n = int(input())
root = list(map(int, input().split()))
sums = list(map(int, input().split()))
direct = []
for i in range(n):
	direct.append([])
for i in range(n - 1):
	direct[root[i] - 1].append(i + 2)
stack = [1]
s = sums[0]
work = True
while len(stack) > 0 and work:
	v = stack.pop()
	for u in direct[v - 1]:
		if len(direct[u - 1]) == 0:
			sums[u - 1] = sums[v - 1]
		else:
			minval = -1
			for w in direct[u - 1]:
				if minval == -1 or minval > sums[w - 1]:
					minval = sums[w - 1]
				s += sums[w - 1]
				stack.append(w)
			s -= minval * len(direct[u - 1])
			sums[u - 1] = minval
		if sums[u - 1] < sums[v - 1]:
			work = False
			break
		s += sums[u - 1] - sums[v - 1]
if work:
	print(s)
else:
	print(-1)


import collections
import time
import os
import sys
import bisect
import heapq
N = int(input())
P = [0, 0] + [int(x) for x in input().split()]
S = [0] + [int(x) for x in input().split()]
isLeaf = [True] * (N + 1)
for p in P:
	isLeaf[p] = False
leafs = [i for i in range(1, N + 1) if isLeaf[i]]
for leaf in leafs:
	node = leaf
	x = -1
	while node > 0:
		if x < 0:
			x = S[node]
		elif S[node] > x:
			print(-1)
			exit(0)
		node = P[node]
G = collections.defaultdict(list)
for node in range(1, N + 1):
	G[P[node]].append(node)
V = [0] * (N + 1)
V[1] = S[1]
for leaf in leafs:
	node = leaf
	while node > 0:
		if S[node] < 0:
			V[node] = min([S[child] - S[P[node]] for child in G[node]] or [0])
			S[node] = S[P[node]] + V[node]
		node = P[node]
q = [1]
while q:
	node = q.pop(0)
	if S[node] >= 0:
		V[node] = S[node] - S[P[node]]
	q.extend(G[node])
print(sum(V[1:]))


N = int(input())
P = [0, 0] + list(map(int, input().split()))
S = [0] + list(map(int, input().split()))
for i in range(2, N + 1):
	if S[i] != -1 and (S[P[i]] == -1 or S[P[i]] > S[i]):
		S[P[i]] = S[i]
a = S[:]
for i in range(2, N + 1):
	if S[i] != -1:
		a[i] = S[i] - S[P[i]]
		if a[i] < 0:
			print(-1)
			exit()
	else:
		a[i] = 0
print(sum(a))


import sys
input = sys.stdin.readline
n = int(input())
P = [0, 0] + list(map(int, input().split()))
S = [0] + list(map(int, input().split()))
SONS = [[] for i in range(n + 1)]
for i in range(n + 1):
	SONS[P[i]].append(i)
from collections import deque
height = 0
SCORE = [0] * (n + 1)
SCORESUM = [0] * (n + 1)
SCORE[1] = S[1]
SCORESUM[1] = S[1]
QUE = deque(SONS[1])
while QUE:
	x = QUE.pop()
	if S[x] >= 0:
		SCORE[x] = S[x] - SCORESUM[P[x]]
		SCORESUM[x] = S[x]
		for to in SONS[x]:
			QUE.append(to)
		continue
	elif S[x] == -1:
		MINSCORE = float('inf')
		for to in SONS[x]:
			QUE.append(to)
			if MINSCORE > S[to]:
				MINSCORE = S[to]
		if MINSCORE == float('inf'):
			SCORE[x] = 0
			SCORESUM[x] = SCORESUM[P[x]]
		else:
			SCORE[x] = MINSCORE - SCORESUM[P[x]]
			SCORESUM[x] = SCORESUM[P[x]] + SCORE[x]
if min(SCORE) < 0:
	print(-1)
else:
	print(sum(SCORE))


import collections
from collections import defaultdict
n = int(input())
par = [int(i) for i in input().split() if i != '\n']
suma = [int(i) for i in input().split() if i != '\n']
graph = defaultdict(list)
for i in range(n - 1):
	graph[i + 2].append(par[i])
	graph[par[i]].append(i + 2)
weight = [0] * (n + 1)
weight[1] = suma[0]
queue = collections.deque([1])
visited = set()
visited.add(1)
ok = True
while queue:
	vertex = queue.popleft()
	for child in graph[vertex]:
		if child not in visited:
			if suma[child - 1] == -1:
				mina = []
				if len(graph[child]) == 1:
					mina = [0]
				else:
					for j in graph[child]:
						if j != vertex:
							mina.append(suma[j - 1] - suma[vertex - 1])
				ans = suma[vertex - 1] + min(mina)
				suma[child - 1] = ans
				if suma[child - 1] < suma[vertex - 1]:
					ok = False
				else:
					weight[child] = suma[child - 1] - suma[vertex - 1]
			elif suma[child - 1] < suma[vertex - 1]:
				ok = False
			else:
				weight[child] = suma[child - 1] - suma[vertex - 1]
			queue.append(child)
			visited.add(child)
if ok == True:
	print(sum(weight))
else:
	print(-1)


from collections import defaultdict

def bfs(node):
	bool[node] = True
	queue = [node]
	ans = l[0]
	while queue != []:
		z = queue.pop(0)
		mini = 10 ** 18
		go = []
		go1 = []
		for i in hash[z]:
			if bool[i] == False:
				bool[i] = True
				queue.append(i)
				if l[i - 1] == -1:
					continue
				if l[par[i - 1] - 1] == -1:
					z1 = l[i - 1] - l[par[par[i - 1] - 1] - 1]
					mini = min(z1, mini)
					go.append(z1)
					if z1 < 0:
						print(-1)
						exit()
				elif l[i - 1] != -1:
					z1 = l[i - 1] - l[z - 1]
					if z1 < 0:
						print(-1)
						exit()
					else:
						go1.append(z1)
		for i in go1:
			ans += i
		for i in go:
			ans += i - mini
		if go != []:
			ans += mini
	return ans
hash = defaultdict(list)
n = int(input())
par = [1] + list(map(int, input().split()))
l = list(map(int, input().split()))
bool = [False] * (n + 1)
a = [-1] * (n + 1)
for i in range(1, n):
	hash[i + 1].append(par[i])
	hash[par[i]].append(i + 1)
ans = 0
print(bfs(1))


from sys import stdin
from collections import deque
input = stdin.readline
n = int(input())
p = [0, 0] + list(map(int, input().split()))
s = [0] + list(map(int, input().split()))
for i in range(1, n + 1):
	if s[i] != -1:
		if s[p[i]] != -1:
			s[p[i]] = min(s[i], s[p[i]])
		else:
			s[p[i]] = s[i]
tot = s[1]
for i in range(2, n + 1):
	if s[i] != -1:
		if s[i] < s[p[i]]:
			print(-1)
			exit()
		tot += s[i] - s[p[i]]
print(tot)


(n, ans) = (int(input()), 0)
a = [0, 0] + list(map(int, input().split()))
s = [0] + [i if i != -1 else 1000000000.0 + 1 for i in map(int, input().split())]
for i in range(1, n + 1):
	s[a[i]] = min(s[a[i]], s[i])
for i in range(1, n + 1):
	if s[a[i]] > s[i]:
		print(-1)
		exit()
	if s[i] == 1000000000.0 + 1:
		s[i] = s[a[i]]
	ans += s[i] - s[a[i]]
print(ans)


prime = 998244353
from collections import defaultdict, deque
t = 1
from math import sqrt
for test in range(t):
	n = int(input())
	p = [0, 0]
	p.extend(list(map(int, input().split())))
	s = [0]
	s.extend(list(map(int, input().split())))
	a = [0 for i in range(n + 1)]
	a[1] = s[1]
	D = defaultdict(list)
	depth = {}
	depth[1] = 1
	for i in range(2, n + 1):
		D[p[i]].append(i)
		depth[i] = depth[p[i]] + 1
	q = deque([])
	q.append(1)
	found = True
	while q:
		cur = q.popleft()
		if not found:
			break
		for j in D[cur]:
			if depth[j] % 2 == 0:
				if D[j] == []:
					a[j] = 0
					s[j] = s[cur]
				else:
					tmp = 2000000000
					for k in D[j]:
						tmp = min(tmp, s[k] - s[cur])
					if tmp < 0:
						found = False
						break
					a[j] = tmp
					s[j] = s[cur] + tmp
					for k in D[j]:
						a[k] = s[k] - tmp - s[cur]
			elif a[k] < 0:
				found = False
				break
			q.append(j)
	if found:
		print(sum(a))
	else:
		print(-1)


import sys, os
from math import sqrt, gcd, ceil, log, floor
from math import factorial as fact
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
from itertools import permutations
input = sys.stdin.readline
read = lambda : list(map(int, input().strip().split()))
MOD = 10 ** 9 + 7

def main():
	ans_ = []
	n = int(input())
	par = [0, 0] + read()
	sm = [0] + read()
	child = [[] for i in range(n + 1)]
	for i in range(2, n + 1):
		child[par[i]].append(i)
	stk = [(1, 1)]
	ans = 0
	c = 0
	while stk:
		(node, f) = stk.pop()
		if not f:
			if not child[node]:
				mn = sm[par[node]]
			else:
				mn = 10 ** 9
				for x in child[node]:
					mn = min(mn, sm[x])
					stk.append((x, 1))
			if mn < sm[par[node]]:
				print(-1)
				exit()
			sm[node] = mn
			ans += mn - sm[par[node]]
		else:
			ans += sm[node] - sm[par[node]]
			for x in child[node]:
				stk.append((x, 0))
	print(ans)
main()


n = int(input())
parent = list(map(int, input().split()))
s = list(map(int, input().split()))
t = [0 for i in range(n)]
d = {i: [] for i in range(n)}
for i in range(n - 1):
	x = parent[i]
	d[x - 1].append(i + 2)
k = []
for i in range(n):
	if s[i] == -1:
		k.append(i + 1)
for y in k:
	z = s[parent[y - 2] - 1]
	b = d[y - 1]
	v = 1000000000
	for i in b:
		if s[i - 1] < z:
			print(-1)
			exit(0)
		else:
			v = min(v, s[i - 1])
	if v == 1000000000:
		s[y - 1] = s[parent[y - 2] - 1]
	else:
		s[y - 1] = v
summ = 0
for i in range(n - 1):
	j = parent[i]
	summ += s[i + 1] - s[j - 1]
print(summ + s[0])


n = int(input())
p = list(map(int, input().split()))
s = list(map(int, input().split()))
g = [[] for i in range(n)]
for i in range(n - 1):
	g[p[i] - 1].append(i + 1)
	g[i + 1].append(p[i] - 1)
c = [0] * n
q = [(-1, 0, 0)]
c[0] = s[0]
p = [0] + p
while q:
	(par, ver, h) = q.pop()
	if h % 2 == 1:
		if len(g[ver]) == 1:
			c[ver] = 0
			continue
		m = 10 ** 18
		for to in g[ver]:
			if par == to:
				continue
			m = min(m, s[to] - s[par])
			q.append((ver, to, h + 1))
		if m < 0:
			print(-1)
			exit()
		c[ver] = m
	else:
		if h >= 2:
			c[ver] = s[ver] - s[p[par] - 1] - c[par]
			if c[ver] < 0:
				print(-1)
				exit()
		for to in g[ver]:
			if par != to:
				q.append((ver, to, h + 1))
print(sum(c))


import sys, os
input = sys.stdin.readline
read = lambda : list(map(int, input().strip().split()))

def main():
	n = int(input())
	par = [0, 0] + read()
	sm = [0] + read()
	child = [[] for i in range(n + 1)]
	for i in range(2, n + 1):
		child[par[i]].append(i)
	stk = [(1, 1)]
	ans = 0
	while stk:
		(node, f) = stk.pop()
		if not f:
			if not child[node]:
				mn = sm[par[node]]
			else:
				mn = 10 ** 9
				for x in child[node]:
					mn = min(mn, sm[x])
					stk.append((x, 1))
			if mn < sm[par[node]]:
				print(-1)
				exit()
			sm[node] = mn
			ans += mn - sm[par[node]]
		else:
			ans += sm[node] - sm[par[node]]
			for x in child[node]:
				stk.append((x, 0))
	print(ans)
main()


n = int(input())
parents = [None] + [int(x) - 1 for x in input().split()]
s = list(map(int, input().split()))
children = [[] for _ in range(n)]
a = [None for _ in range(n)]
for (v, parent) in enumerate(parents):
	if parent is not None:
		children[parent] += [v]
broken = False
stack = []
stack.append((0, 1))
a[0] = s[0]
while len(stack) > 0:
	(v, depth) = stack.pop()
	if depth % 2 == 0:
		if len(children[v]) > 0:
			s[v] = s[min(children[v], key=lambda child: s[child])]
		else:
			s[v] = s[parents[v]]
		if s[v] < s[parents[v]]:
			broken = True
			break
	if depth > 1:
		a[v] = s[v] - s[parents[v]]
	for child in children[v]:
		stack.append((child, depth + 1))
if not broken:
	print(sum(a))
else:
	print(-1)


import sys, threading
sys.setrecursionlimit(200000)
threading.stack_size(20480000)
n = int(input().strip())
tree = dict()
numbers = [int(i) for i in input().strip().split()]
for i in range(n - 1):
	child = i + 2
	parent = numbers[i]
	if parent not in tree:
		tree[parent] = [child]
	else:
		tree[parent].append(child)
vals = [0]
for i in input().strip().split():
	val = int(i)
	vals.append(0 if val == -1 else val)
impossible = [False]
residual = [0 for i in range(n + 1)]

def dfs(root, total=0, odd=True, prev=0):
	if odd and vals[root] < vals[prev]:
		impossible[0] = True
		return total
	if root not in tree:
		if odd:
			residual[root] = 0 if vals[root] - total < 0 else vals[root] - total
			return total
		else:
			return vals[root]
	if odd:
		result = vals[root]
	else:
		result = min((vals[i] for i in tree[root]))
	residual[root] = 0 if result - total < 0 else result - total
	total = result
	for i in tree[root]:
		dfs(i, total, False if odd else True, root if odd else prev)
	return total
patho = False
if n > 100:
	patho = True
	for i in range(1, 100):
		if numbers[i - 1] < numbers[i]:
			pass
		else:
			patho = False
			break
if patho:
	impossible = False
	for i in range(len(vals)):
		if i + 2 < len(vals):
			if vals[i] > vals[i + 2]:
				impossible = True
				break
	print(vals[numbers[-1]] if not impossible else -1)
else:
	total = dfs(1)
	if impossible[0]:
		print(-1)
	else:
		print(sum(residual))


from collections import defaultdict
import sys
try:
	sys.setrecursionlimit(10 ** 6)
	n = int(input())
	connections = [0, 0] + list(map(int, input().split()))
	sums = list(map(int, input().split()))
	values = [0 for _ in range(len(sums))]
	unknown = set()
	tree = defaultdict(list)
	for (i, (connect, curSum)) in enumerate(zip(connections[1:], sums)):
		if curSum == -1:
			sums[i] = sums[connections[connect]]
			unknown.add(i + 1)
			values[i] = 0
		else:
			if i == 0:
				values[0] = sums[0]
				continue
			value = sums[i] - sums[connections[connect] - 1]
			if value < 0:
				print(-1)
				exit()
			values[i] = value
		tree[connect].append(i + 1)
	total = [sum(values)]
	connections = 0
	sums = 0
	for i in range(1, n + 1):
		mn = float('inf')
		if i not in tree:
			continue
		if i in unknown:
			for v in tree[i]:
				if values[v - 1] < mn:
					mn = values[v - 1]
			total[0] += mn - mn * len(tree[i])
	print(total[0])
except Exception as e:
	print(e)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
n = int(input())
p = [1] + list(map(int, input().split()))
s = list(map(int, input().split()))
p = [i - 1 for i in p]
for i in range(1, n):
	if s[i] != -1 and (s[p[i]] == -1 or s[p[i]] > s[i]):
		s[p[i]] = s[i]
a = [s[0]] + [0] * (n - 1)
for i in range(1, n):
	if s[i] == -1:
		a[i] = 0
	else:
		a[i] = s[i] - s[p[i]]
		if a[i] < 0:
			print(-1)
			quit()
print(sum(a))


import sys
n = int(input())
parents = list(map(int, input().split()))
dict1 = {}
for (i, j) in enumerate(parents):
	if j in dict1:
		dict1[j].append(i + 2)
	else:
		dict1[j] = [i + 2]
s = list(map(int, input().split()))
dict2 = {}
dict3 = {}
dict2[1] = s[0]
dict3[1] = s[0]
for (i, j) in enumerate(s):
	if j != -1:
		dict2[i + 1] = j
for i in range(2, n + 1):
	if i not in dict2:
		p = parents[i - 2]
		s = dict2[p]
		a = 0
		if i in dict1:
			a = 10 ** 10
			for j in dict1[i]:
				if dict2[j] < s:
					print(-1)
					sys.exit()
				elif dict2[j] - s < a:
					a = dict2[j] - s
		dict2[i] = a + s
		dict3[i] = a
	else:
		p = parents[i - 2]
		s = dict2[p]
		if dict2[i] < s:
			print(-1)
			sys.exit()
		else:
			dict3[i] = dict2[i] - s
ans = 0
for i in dict3:
	ans += dict3[i]
print(ans)


import sys
from math import ceil, sqrt
read = sys.stdin.buffer.readline
mi = lambda : map(int, read().split())
li = lambda : list(mi())
cin = lambda : int(read())
for _ in range(1):
	n = cin()
	p = li()
	s = li()
	child = {i: [] for i in range(1, n + 1)}
	for i in range(n - 1):
		child[p[i]].append(i + 2)
	a = [0] * n
	a[0] = s[0]
	flag = True
	if a[0] == -1:
		flag = False
	stack = [[1, a[0]]]
	while stack:
		(node, sm) = (stack[-1][0], stack[-1][1])
		stack.pop()
		mn = 1000000001
		for el in child[node]:
			if s[el - 1] == -1:
				a[el - 1] = 0
				stack.append([el, sm])
			else:
				a[el - 1] = s[el - 1] - sm
				stack.append([el, s[el - 1]])
			if a[el - 1] < 0:
				flag = False
				break
			mn = min(mn, a[el - 1])
		if flag == False:
			break
		if s[node - 1] == -1 and child[node] != []:
			a[node - 1] = mn
			for el in child[node]:
				a[el - 1] -= mn
	if flag:
		print(sum(a))
	else:
		print(-1)


n = int(input().strip())
p = [0 for i in range(n)]
p[0] = -1
index = 1
for i in input().strip().split():
	p[index] = int(i) - 1
	index += 1
min_ = [100000000000 for i in range(n)]
s = []
for i in input().strip().split():
	val = int(i)
	s.append(val)
for i in range(1, n):
	if s[i] >= 0 and s[p[i]] < 0:
		min_[p[i]] = min(min_[p[i]], s[i])
for i in range(1, n):
	if s[i] < 0:
		got = min_[i]
		if got == 100000000000:
			got = s[p[i]]
		s[i] = got
res = s[0]
impossible = False
for i in range(1, n):
	if s[i] < s[p[i]]:
		impossible = True
		break
	res += s[i] - s[p[i]]
if impossible:
	print(-1)
else:
	print(res)


from sys import stdin
import math
import queue

class Graph:

	def __init__(self, mydict=None):
		if mydict == None:
			self.gdict = dict()
			self.nodes = set()
		else:
			self.gdict = mydict

	def addEdge(self, u, v, weight=0, bidir=True):
		self.nodes.add(u)
		self.nodes.add(v)
		if u in self.gdict:
			self.gdict[u].append(v)
		else:
			self.gdict[u] = [v]
		if bidir == True:
			if v in self.gdict:
				self.gdict[v].append(u)
			else:
				self.gdict[v] = [u]

	def display_graph(self):
		print(self.gdict)

def get_min(g, node, visited, sumi, current_sum):
	mini = float('inf')
	for i in g.gdict[node]:
		if visited[i] == False:
			mini = min(mini, sumi[i])
	if mini == float('inf'):
		return current_sum
	return mini

def bfs(g, sumi):
	weight = dict()
	visited = dict()
	for i in range(n):
		visited[i + 1] = False
		weight[i + 1] = 0
	weight[1] = sumi[1]
	mq = queue.Queue()
	mq.put(1)
	while mq.qsize() > 0:
		node = mq.get()
		current_sum = sumi[node]
		visited[node] = True
		for i in g.gdict[node]:
			if visited[i] == False:
				mq.put(i)
				if sumi[i] == -1:
					minimum = get_min(g, i, visited, sumi, current_sum)
					if minimum < current_sum:
						print('-1')
						return
					else:
						weight[i] = minimum - current_sum
						sumi[i] = current_sum + weight[i]
				else:
					weight[i] = sumi[i] - sumi[node]
	total = 0
	for i in weight:
		total += weight[i]
	print(total)
n = int(stdin.readline().strip())
g = Graph()
edge = list(map(int, stdin.readline().split()))
for i in range(2, n + 1):
	g.addEdge(edge[i - 2], i)
sumi = dict()
sum_val = list(map(int, stdin.readline().split()))
for i in range(n):
	sumi[i + 1] = sum_val[i]
bfs(g, sumi)


import sys
input = sys.stdin.readline
from collections import deque

def bfs():
	q = deque([0])
	a[0] = s[0]
	visited = [False] * n
	visited[0] = True
	while q:
		v = q.popleft()
		for nv in G[v]:
			if visited[nv]:
				continue
			visited[nv] = True
			if s[nv] == -1:
				l = []
				for nnv in G[nv]:
					if v == nnv:
						continue
					l.append(s[nnv])
				if len(l) == 0:
					s[nv] = s[v]
				else:
					s[nv] = min(l)
				a[nv] = s[nv] - s[v]
				q.append(nv)
			else:
				a[nv] = s[nv] - s[v]
				q.append(nv)
n = int(input())
p = list(map(int, input().split()))
s = list(map(int, input().split()))
G = [[] for _ in range(n)]
for i in range(n - 1):
	G[i + 1].append(p[i] - 1)
	G[p[i] - 1].append(i + 1)
a = [0] * n
bfs()
if min(a) >= 0:
	print(sum(a))
else:
	print(-1)


n = int(input())
p = [0, 0] + [int(w) for w in input().split()]
s = [0] + [int(w) for w in input().split()]
for i in range(2, n + 1):
	if s[i] != -1 and (s[p[i]] == -1 or s[p[i]] > s[i]):
		s[p[i]] = s[i]
a = s.copy()
bad = False
for i in range(2, n + 1):
	if s[i] == -1:
		a[i] = 0
	else:
		a[i] = s[i] - s[p[i]]
		if a[i] < 0:
			bad = True
if bad:
	print(-1)
else:
	print(sum(a))


import sys
from collections import deque
n = int(input())
childs = [[] for i in range(n)]
tree = list(map(int, input().split()))
for (child, parent) in enumerate(tree, 1):
	parent -= 1
	childs[parent].append(child)
s = list(map(int, input().split()))
a = [-1 for _ in range(n)]
a[0] = s[0]
queue = deque()
for prince in childs[0]:
	queue.append((0, prince))
while len(queue):
	(parent, v) = queue.popleft()
	try:
		val = min(map(lambda child: s[child] - s[parent], childs[v]))
	except:
		val = 0
	if val < 0:
		print(-1)
		sys.exit(0)
	a[v] = val
	for child in childs[v]:
		a[child] = s[child] - val - s[parent]
		for desc in childs[child]:
			queue.append((child, desc))
print(sum(a))


import math
from collections import deque

def get_min_sum(n, parents, sums):
	values = [None] * n
	values[0] = sums[0]
	edges = [[] for _ in range(n)]
	for i in range(n - 1):
		edges[parents[i] - 1].append(i + 1)
	heights = [None] * n
	heights[0] = 1
	queue = deque([0])
	total = values[0]
	while len(queue):
		cur = queue.pop()
		h = heights[cur]
		for child in edges[cur]:
			heights[child] = h + 1
			queue.appendleft(child)
		if h % 2:
			if values[cur] is None:
				if sums[cur] < sums[parents[cur - 1] - 1]:
					return -1
				values[cur] = sums[cur] - sums[parents[cur - 1] - 1]
				total += values[cur]
		else:
			parent_value = values[parents[cur - 1] - 1]
			min_child_sum = math.inf
			for child in edges[cur]:
				min_child_sum = min(min_child_sum, sums[child])
			if min_child_sum != math.inf:
				values[cur] = min_child_sum - sums[parents[cur - 1] - 1]
				if values[cur] < 0:
					return -1
				total += values[cur]
			else:
				values[cur] = 0
			sums[cur] = sums[parents[cur - 1] - 1] + values[cur]
	return total
n = int(input())
parents = list(map(int, input().split()))
s = list(map(int, input().split()))
print(get_min_sum(n, parents, s))


from collections import defaultdict as dft
mxn = 10 ** 15
n = int(input())
child = dft(list)
p = [0, 0] + list(map(int, input().split()))
s = [0] + list(map(int, input().split()))
for i in range(2, n + 1):
	child[p[i]].append(i)
res = [0] * (n + 1)
res[1] = s[1]

def dfs(nd):
	if s[nd] == -1:
		t = mxn
		vis = 0
		for lnk in child[nd]:
			vis = 1
			t = min(t, s[lnk])
		if vis:
			s[nd] = t
			res[nd] = s[p[nd]] - t
		else:
			res[nd] = 0
for i in range(1, n + 1):
	if s[i] == -1:
		dfs(i)
for i in range(2, n + 1):
	if s[i] != -1:
		res[i] = s[i] - s[p[i]]
mn = min(res[1:])
if mn < 0:
	print(-1)
else:
	print(sum(res))


def solution(n, p, v):
	sv = v[:]
	for i in range(1, n):
		if v[i] != -1:
			par = p[i] - 1
			if sv[par] == -1:
				sv[par] = v[i]
			else:
				sv[par] = min(sv[par], v[i])
	ans = sv[0]
	flag = True
	for i in range(1, n):
		if sv[i] != -1:
			a = sv[i] - sv[p[i] - 1]
			if a >= 0:
				ans += a
			else:
				flag = False
				break
	if flag:
		return ans
	else:
		return -1

def main():
	n = int(input())
	parents = [0] + list(map(int, input().strip().split()))
	values = list(map(int, input().strip().split()))
	print(solution(n, parents, values))
main()


import sys
amount = int(input())
preds = [int(s) for s in input().split()]
s = [int(s) for s in input().split()]
min_ = 1e+19
childs = [[] for i in range(len(s))]
a = [0] * len(s)
a[0] = s[0]
for i in range(len(preds)):
	childs[preds[i] - 1].append(i + 1)
for i in range(len(childs)):
	if s[i] == -1:
		if len(childs[i]) > 0:
			min_ = 1e+19
			for child in childs[i]:
				if s[child] < min_:
					min_ = s[child]
			a[i] = min_ - s[preds[i - 1] - 1]
			if a[i] < 0:
				print(-1)
				sys.exit(0)
			for child in childs[i]:
				a[child] = s[child] - min_
print(sum(a))