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

Difficulty: competition

Starter code:

Solutions:
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:
    # print(Q)
    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)


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()

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)

#print(direct)

stack = [1]
s = sums[0]
work = True
while(len(stack) > 0 and work):
    v = stack.pop()
    #v is odd height
    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 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):
    nonlocal 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 = [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))

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)

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()
    # assert (s[v]==-1) == (depth%2==0)
    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)



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())

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([x.s - t.parent.s for x in 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)


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]
#print(val)
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])
            else:
                if 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]
    else:
        if s[v-1]!=-1 and v>1:
            val[v]=s[v-1]-s[g[v][0]-1]
    


print(sum(val))


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)
                    return
                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)
                        return
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)
        return
    else:
        a[i] = s[i]-s[p[i-1]-1]
print(sum(a))


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)

from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
#from math import *
from collections import defaultdict as dd, deque
def data(): return sys.stdin.readline().strip()
def mdata(): return map(int, data().split())
#sys.setrecursionlimit(100000)
mod=int(1e9+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)

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(1e10)
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
    else:
        if 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)     


import sys
input=sys.stdin.readline
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)
#print(graph)
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])
            else:
                if suma[child-1]<suma[vertex-1]:
                    ok=False
                else:
                    weight[child]=(suma[child-1]-suma[vertex-1])
            #print(child,vertex,weight,suma[child-1],suma[vertex-1])
            queue.append(child)
            visited.add(child)
#print(weight,ok,suma)
if ok==True:
    print(sum(weight))
else:
    print(-1)


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])
            else:
                if 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 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






def __starting_point():
    n = int(input())
    p = map(int, input().split())
    s = map(int, input().split())
    print(solve(p, s))
__starting_point()

n,ans=int(input()),0
a=[0,0]+list(map(int,input().split()))
s=[0]+[i if i!=-1 else 1e9+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);return
    if s[i]==1e9+1:s[i]=s[a[i]]
    ans+=s[i]-s[a[i]]
print(ans)

from collections import deque

class Graph(object):
	"""docstring for Graph"""
	def __init__(self,n,d): # Number of nodes and d is True if directed
		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): # NORMAL BFS
		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
			# if flag == 0:
			# 	if s[element] == -1:
			# 		if parent[element] != -1:
			# 			ans+=s[parent[element]]
			# 	else:
			# 		ans+=s[element]
		return True

	def dfs(self, root, ans): # Iterative DFS
		stack=[root]
		vis=[0]*self.n
		stack2=[]
		while len(stack)!=0: # INITIAL TRAVERSAL
			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: # BACKTRACING. Modify the loop according to the question
			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): # Calculate Shortest Path between two nodes
		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()
				# Reverse_The_Change()
				continue
			vis[e] = 1
			for i in graph[e]:
				if not vis[e]:
					stack.append(i)
			if self.parent[e]==-1:
				continue
			# Change_The_Answers()



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)
	return
s=g.dfs(0,s)
# print (s)
print(sum(s))


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])
# print(level)
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]
	else:
		if i>1:
			for j in level[i]:
				papa=s[l[j-2]-1]
				# print(papa)
				ans[j]=s[j-1]-papa
# print(ans)
if flag==0:
	print(-1)
else:
	print(sum(ans))


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():
    a = [None] * (n + 1)

    a[1] = s[0]
    for i in range(2, n + 1):
        if s[i - 1] == -1:
            continue

        pi = p[i - 2]
        pi_er_pi = p[pi - 2]

        if s[i - 1] < s[pi_er_pi - 1]:
            return -1

        new_value = s[i - 1] - s[pi_er_pi - 1]
        a[pi] = min(a[pi] if a[pi] is not None else float('inf'), new_value)

    for i in range(2, n + 1):
        if s[i - 1] == -1:
            continue

        pi = p[i - 2]
        pi_er_pi = p[pi - 2]

        a[i] = s[i - 1] - s[pi_er_pi - 1] - a[pi]

    return sum(filter(None, a))


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