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.

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 one integer — the minimum total sum of all values $$$a_v$$$ in the original tree, or $$$-1$$$ if such tree does not exist.

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF1098A(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	var n, v int
	Fscan(in, &n)
	g := make([][]int, n)
	for w := 1; w < n; w++ {
		Fscan(in, &v)
		v--
		g[v] = append(g[v], w)
	}
	s := make([]int, n)
	for i := range s {
		Fscan(in, &s[i])
	}

	ans := int64(0)
	var f func(int, int)
	f = func(v, lowS int) {
		sv := s[v]
		if sv != -1 && sv < lowS {
			ans = -1
			return
		}
		if len(g[v]) == 0 {
			if s[v] == -1 {
				s[v] = lowS
			}
			return
		}
		if sv > lowS {
			lowS = sv
		}
		minS := int(1e9)
		for _, w := range g[v] {
			f(w, lowS)
			if s[w] < minS {
				minS = s[w]
			}
		}
		if s[v] == -1 {
			s[v] = minS
		}
	}
	f(0, s[0])
	a := make([]int, n)
	f = func(v, sFa int) {
		a[v] = s[v] - sFa
		for _, w := range g[v] {
			f(w, s[v])
		}
	}
	f(0, 0)
	if ans != -1 {
		for _, v := range a {
			ans += int64(v)
		}
	}
	Fprint(_w, ans)
}

func main() { CF1098A(os.Stdin, os.Stdout) }

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var ChildrenIndexes [200000][]int

func ReadInts(s *bufio.Scanner) []int {
	s.Scan()
	line := s.Text()
	values := strings.Split(line, " ")
	var nums []int
	for _, val := range values {
		n, _ := strconv.Atoi(val)
		nums = append(nums, n)
	}
	return nums
}

func ReadInputs() ([]int, []int) {
	scanner := bufio.NewScanner(os.Stdin)
	const maxCapacity = 2000000
	buf := make([]byte, maxCapacity)
	scanner.Buffer(buf, maxCapacity)
	var n int
	fmt.Scanln(&n)
	p := ReadInts(scanner)
	s := ReadInts(scanner)
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GenerateChildrenIndexes(p []int) {
	for node, parent := range p {
		ChildrenIndexes[parent] = append(ChildrenIndexes[parent], node+2)
	}
	return
}

func GetChildrenIndexes(n node) []int {
	return ChildrenIndexes[n.index]
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int64 {
	sum := int64(n.a)
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	GenerateChildrenIndexes(p)
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

var ChildrenIndexes [200000][]int

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		case 13:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	a[last_index] *= signal
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReaderSize(os.Stdin, 2000000)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GenerateChildrenIndexes(p []int) {
	for node, parent := range p {
		ChildrenIndexes[parent] = append(ChildrenIndexes[parent], node+2)
	}
	return
}

func GetChildrenIndexes(n node) []int {
	return ChildrenIndexes[n.index]
}

//func GetChildrenIndexes(n node, p []int) []int {
//	var indexes []int
//	for index, parent := range p {
//		if parent == n.index {
//			indexes = append(indexes, index+2)
//		}
//	}
//	return indexes
//}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int64 {
	sum := int64(n.a)
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	GenerateChildrenIndexes(p)
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

// "Construct" the tree with two hash tables: parent & children.
// For every even node, its Sv can be evaluated via min value of all the child's value.
package main

import (
	"bufio"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
)

func min(nums ...int) int {
	res := math.MaxInt32
	for _, num := range nums {
		if num < res {
			res = num
		}
	}
	return res
}

func visitForS(node int, s []int, children map[int][]int, parent map[int]int) {
	if s[node] == -1 {
		if children[node] == nil {
			s[node] = s[parent[node]]
		} else {
			childrenS := []int{}
			for _, v := range children[node] {
				childrenS = append(childrenS, s[v])
			}
			s[node] = min(childrenS...)

			if s[node] < s[parent[node]] {
				fmt.Println(-1)
				os.Exit(0)
			}
		}
	}

	if children[node] == nil {
		return
	}
	for _, v := range children[node] {
		visitForS(v, s, children, parent)
	}
}

func visitForTotal(node int, s []int, children map[int][]int, parent map[int]int, sum *int64) {
	if parent[node] != 0 {
		(*sum) += int64(s[node] - s[parent[node]])
	} else {
		(*sum) += int64(s[node]) // root
	}

	if children[node] == nil {
		return
	}
	for _, v := range children[node] {
		visitForTotal(v, s, children, parent, sum)
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanInt := func() int {
		scanner.Scan()
		num, err := strconv.Atoi(scanner.Text())
		if err != nil {
			log.Fatal(err)
		}
		return num
	}

	n := scanInt()
	e, s := make([]int, n-1), make([]int, n+1)
	for i := 0; i < n-1; i++ {
		e[i] = scanInt()
	}
	for i := 0; i < n; i++ {
		s[i+1] = scanInt()
	}

	parent, children := map[int]int{}, map[int][]int{}
	for k, p := range e {
		parent[k+2] = p
		if children[p] == nil {
			children[p] = []int{}
		}
		children[p] = append(children[p], k+2)
	}

	visitForS(1, s, children, parent)

	sum := int64(0)
	visitForTotal(1, s, children, parent, &sum)
	fmt.Println(sum)
}

// "Construct" the tree with two hash tables: parent & children.
// For every even node, its Sv can be evaluated via min value of all the child's value.
package main

import (
	"bufio"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
)

func min(nums ...int) int {
	res := math.MaxInt32
	for _, num := range nums {
		if num < res {
			res = num
		}
	}
	return res
}

func visit(node int, children map[int][]int, callback func(int)) {
	callback(node)
	if children[node] == nil {
		return
	}
	for _, v := range children[node] {
		visit(v, children, callback)
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanInt := func() int {
		scanner.Scan()
		num, err := strconv.Atoi(scanner.Text())
		if err != nil {
			log.Fatal(err)
		}
		return num
	}

	n := scanInt()
	e, s := make([]int, n-1), make([]int, n+1)
	for i := 0; i < n-1; i++ {
		e[i] = scanInt()
	}
	for i := 0; i < n; i++ {
		s[i+1] = scanInt()
	}

	parent, children := map[int]int{}, map[int][]int{}
	for k, p := range e {
		parent[k+2] = p
		if children[p] == nil {
			children[p] = []int{}
		}
		children[p] = append(children[p], k+2)
	}

	visit(1, children, func(node int) {
		if s[node] != -1 {
			return
		}
		if children[node] == nil {
			s[node] = s[parent[node]]
			return
		}
		childrenS := []int{}
		for _, v := range children[node] {
			childrenS = append(childrenS, s[v])
		}
		s[node] = min(childrenS...)
		if s[node] < s[parent[node]] {
			fmt.Println(-1)
			os.Exit(0)
		}
	})

	sum := int64(0)
	visit(1, children, func(node int) {
		if parent[node] == 0 {
			sum += int64(s[node])
		} else {
			sum += int64(s[node] - s[parent[node]])
		}
	})
	fmt.Println(sum)
}

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/1098/A

package main

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

type Item struct {
	vertex  int
	prevSum int64
}

func min(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func Solve(n int, p []int, s []int64) int64 {
	for i := 2; i <= n; i++ {
		if s[p[i]] == -1 {
			s[p[i]] = s[i]
		} else if s[i] != -1 && s[i] < s[p[i]] {
			s[p[i]] = s[i]
		}
	}
	sum := int64(0)
	for i := 1; i <= n; i++ {
		if s[i] == -1 {
			continue
		} else if s[i] >= s[p[i]] {
			sum += s[i] - s[p[i]]
		} else {
			return -1
		}
	}
	return sum
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	p := make([]int, n+1)
	for i := 2; i <= n; i++ {
		fmt.Fscanf(reader, "%d", &p[i])
	}
	fmt.Fscanf(reader, "\n")
	s := make([]int64, n+1)
	for i := 1; i <= n; i++ {
		fmt.Fscanf(reader, "%d", &s[i])
	}
	fmt.Fscanf(reader, "\n")

	fmt.Fprintf(writer, "%d\n", Solve(n, p, s))
}

package main

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

func addEdge(from, to int, g [][]int) {
	if 0 == len(g[from]) {
		g[from] = make([]int, 0)
	}
	g[from] = append(g[from], to)
}
func solve(root ,h int,g [][]int,sum []int64,value []int64,total int64)bool  {
	if sum[root]>-1{
		value[root] = sum[root]-total
	}else{
		var min int64 = -1
		for _,next := range g[root]{
			if sum[next] < total{
				return false
			}
			if min == -1 || min > sum[next]-total{
				min = sum[next]-total
			}
		}
		if min == -1{
			min = 0
		}
		value[root] = min
	}
	for _,next := range g[root]{
		if solve(next,h+1,g,sum,value,total+value[root]) == false{
			return false
		}
	}
	return true
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n int

	fmt.Fscanf(buf, "%d\n", &n)
	graph := make([][]int, n+1)
	sum := make([]int64, n+1)
	value := make([]int64, n+1)
	for i := 2; i <= n; i++ {
		var pre int
		fmt.Fscanf(buf, "%d", &pre)
//		fmt.Printf("i=%d pre=%d\n",i,pre)
		addEdge(pre, i, graph)
	}
	fmt.Fscanf(buf, "\n")
	for i := 1; i <= n; i++ {
		fmt.Fscanf(buf, "%d", &sum[i])
//		fmt.Printf("i=%d v=%d\n",i,sum[i])
	}
//	fmt.Printf("sum=%v\n", sum)
	value[1] =  sum[1]

	if solve(1,1,graph,sum,value,0) == false{
		fmt.Printf("-1\n")
		return
	}
//	fmt.Printf("%v\n", value)
	var ans int64 = 0
	for i := 1; i <= n; i++ {
		ans += value[i]
	}
	fmt.Printf("%d\n", ans)
}

package main

import (
	"os"
	"bufio"
	"strconv"
	// "sort"
	// "strings"
	// "fmt"
)

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func ReadInt() int {
	scanner.Scan()
	ans, _ := strconv.Atoi(scanner.Text())
	return ans
}

type ii struct{
	acc, curr int
}

func min(a,b int) int {
	if a < b {
		return a
	}
	return b
}

func dfs(v, pai int, data *[]ii, sum *[]int, grafo *[][]int) bool{

	if (*sum)[v] == -1 {
		accumulate := (*data)[pai].acc

		menor := 2000000000

		for _, elem := range (*grafo)[v] {
			menor = min(menor, (*sum)[elem])
		}

		if menor == 2000000000 {
			return true
		}

		if menor < accumulate {
			return false
		}

		(*data)[v].curr = menor - accumulate
		(*data)[v].acc = accumulate + (*data)[v].curr

	} else {
		if v == 1 {
			(*data)[v].curr = (*sum)[v]
			(*data)[v].acc = (*sum)[v]
		} else {
			accumulate := (*data)[pai].acc

			if accumulate > (*sum)[v] {
				return false
			}

			(*data)[v].curr = (*sum)[v] - accumulate
			(*data)[v].acc = accumulate + (*data)[v].curr
		}
	}

	resp := true

	for _, elem := range (*grafo)[v] {
		resp = resp && dfs(elem, v, data, sum, grafo)
	}

	return resp
}

func main() {
	defer writer.Flush()
    scanner.Split(bufio.ScanWords)

    n := ReadInt()

    grafo := make([][]int, n+1)

    for i := 2; i <= n; i++ {
    	pai := ReadInt()
    	grafo[pai] = append(grafo[pai], i)
    }

    sum := make([]int, n+1)

    data := make([]ii, n+1)

    for i := 1; i <= n; i++ {
    	sum[i] = ReadInt()
    }

    if dfs(1, -1, &data, &sum, &grafo) {

    	total := int64(0)

    	for i := 1; i <= n; i++ {
    		total += int64(data[i].curr)
    	}

    	writer.WriteString(strconv.FormatInt(total, 10))

	} else {
    	writer.WriteString("-1")
	}

}

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
)

const (
	BIG = 1024 * 1024 * 10
	INF = 10000000
)

func readLine(r *bufio.Reader) string {
	bytes, _, err := r.ReadLine()
	if err != nil {
		log.Fatalln("Failed to read line")
	}

	return string(bytes)
}

func readInts(r *bufio.Reader) []int64 {
	elems := strings.Fields(readLine(r))

	ret := make([]int64, len(elems))
	for i, el := range elems {
		tmp, err := strconv.ParseInt(el, 10, 64)
		if err != nil {
			log.Fatalf("Failed to parse number %v", el)
		}
		ret[i] = tmp
	}

	return ret
}

func min(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func main() {
	r := bufio.NewReaderSize(os.Stdin, BIG)

	n := int(readInts(r)[0])
	pis := readInts(r)
	children := make([][]int64, n)
	for i := 0; i < n; i++ {
		children[i] = make([]int64, 0)
	}
	i := int64(1)
	for _, pi := range pis {
		children[pi-1] = append(children[pi-1], i)
		i += 1
	}

	sis := readInts(r)
	ais := make([]int64, n)
	odds := make([]int64, 0)
	odds = append(odds, 0)
	ais[0] = sis[0]
	for len(odds) > 0 {
		nodds := make([]int64, 0)
		for _, el := range odds {
			for _, child := range children[el] {
				ais[child] = INF
				for _, gchild := range children[child] {
					ais[gchild] = sis[gchild] - sis[el]
					if ais[gchild] < 0 {
						fmt.Println(-1)
						return
					}
					ais[child] = min(ais[child], ais[gchild])
					nodds = append(nodds, gchild)
				}
				if ais[child] == INF { // No grandchildren
					ais[child] = 0
				} else {
					for _, gchild := range children[child] {
						ais[gchild] -= ais[child]
					}
				}
			}
		}
		odds = nodds
	}

	res := int64(0)
	for _, ai := range ais {
		res += ai
	}
	fmt.Println(res)
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var ChildrenIndexes [200000][]int

//func ReadLine(r *bufio.Reader) []int {
//	signal := 1
//	bytes, _ := r.ReadSlice('\n')
//	if len(bytes) == 1 {
//		bytes, _ = r.ReadSlice('\n')
//	}
//	a := make([]int, len(bytes))
//	last_index := 0
//	for _, b := range bytes {
//		switch b {
//		case 32:
//			a[last_index] *= signal
//			last_index++
//			signal = 1
//		case 45:
//			signal = -1
//		case 10:
//			break
//		case 13:
//			break
//		default:
//			a[last_index] = a[last_index]*10 + int(b) - 48
//		}
//	}
//	a[last_index] *= signal
//	return a[:last_index+1]
//}

func ReadInts(r *bufio.Reader) []int {
	line, _ := r.ReadString('\n')
	values := strings.Split(line[:len(line)-1], " ")
	var nums []int
	for _, val := range values {
		n, _ := strconv.Atoi(val)
		nums = append(nums, n)
	}
	return nums
}

//func ReadInts(n int) []int {
//	x := make([]int, n)
//	y := make([]interface{}, len(x))
//	for i := range x {
//		y[i] = &x[i]
//	}
//	fmt.Scanln(y...)
//	return x
//}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReaderSize(os.Stdin, 2000000)
	var n int
	fmt.Scanln(&n)
	p := ReadInts(r)
	s := ReadInts(r)
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GenerateChildrenIndexes(p []int) {
	for node, parent := range p {
		ChildrenIndexes[parent] = append(ChildrenIndexes[parent], node+2)
	}
	return
}

func GetChildrenIndexes(n node) []int {
	return ChildrenIndexes[n.index]
}

//func GetChildrenIndexes(n node, p []int) []int {
//	var indexes []int
//	for index, parent := range p {
//		if parent == n.index {
//			indexes = append(indexes, index+2)
//		}
//	}
//	return indexes
//}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int64 {
	sum := int64(n.a)
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	GenerateChildrenIndexes(p)
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

var ChildrenIndexes [200000][]int

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		case 13:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	a[last_index] *= signal
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReaderSize(os.Stdin, 2000000)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	if n == 100000 {
		fmt.Println(n, len(p), len(s))
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GenerateChildrenIndexes(p []int) {
	for node, parent := range p {
		ChildrenIndexes[parent] = append(ChildrenIndexes[parent], node+2)
	}
	return
}

func GetChildrenIndexes(n node) []int {
	return ChildrenIndexes[n.index]
}

//func GetChildrenIndexes(n node, p []int) []int {
//	var indexes []int
//	for index, parent := range p {
//		if parent == n.index {
//			indexes = append(indexes, index+2)
//		}
//	}
//	return indexes
//}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	GenerateChildrenIndexes(p)
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		case 13:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	a[last_index] *= signal
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	if n > 10000 {
		fmt.Println(n, len(p), len(s))
		os.Exit(0)
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GetChildrenIndexes(n node, p []int) []int {
	var indexes []int
	for index, parent := range p {
		if parent == n.index {
			indexes = append(indexes, index+2)
		}
	}
	return indexes
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n, p)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

var ChildrenIndexes [200000][]int

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		case 13:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	a[last_index] *= signal
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReaderSize(os.Stdin, 2000000)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GenerateChildrenIndexes(p []int) {
	for node, parent := range p {
		ChildrenIndexes[parent] = append(ChildrenIndexes[parent], node+2)
	}
	return
}

func GetChildrenIndexes(n node) []int {
	return ChildrenIndexes[n.index]
}

//func GetChildrenIndexes(n node, p []int) []int {
//	var indexes []int
//	for index, parent := range p {
//		if parent == n.index {
//			indexes = append(indexes, index+2)
//		}
//	}
//	return indexes
//}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	GenerateChildrenIndexes(p)
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	if n == 3 {
		fmt.Println(p, s)
	}
	if n > 10000 {
		fmt.Println(n)
		os.Exit(0)
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GetChildrenIndexes(n node, p []int) []int {
	var indexes []int
	for index, parent := range p {
		if parent == n.index {
			indexes = append(indexes, index+2)
		}
	}
	return indexes
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n, p)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		case 13:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	a[last_index] *= signal
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	if n > 10000 {
		fmt.Println(n)
		os.Exit(0)
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GetChildrenIndexes(n node, p []int) []int {
	var indexes []int
	for index, parent := range p {
		if parent == n.index {
			indexes = append(indexes, index+2)
		}
	}
	return indexes
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n, p)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

import (
	"fmt"
	"os"
)

func ReadInputs() ([]int, []int) {
	var n int
	fmt.Scanln(&n)
	p := make([]int, n-1)
	for i := 0; i < n-1; i++ {
		fmt.Scan(&p[i])
	}
	s := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&s[i])
	}
	if n > 10000 {
		fmt.Println(n)
		os.Exit(0)
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GetChildrenIndexes(n node, p []int) []int {
	var indexes []int
	for index, parent := range p {
		if parent == n.index {
			indexes = append(indexes, index+2)
		}
	}
	return indexes
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n, p)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var ChildrenIndexes [200000][]int

func ReadInts(s *bufio.Scanner) []int {
	s.Scan()
	line := s.Text()
	values := strings.Split(line, " ")
	var nums []int
	for _, val := range values {
		n, _ := strconv.Atoi(val)
		nums = append(nums, n)
	}
	return nums
}

func ReadInputs() ([]int, []int) {
	scanner := bufio.NewScanner(os.Stdin)
	const maxCapacity = 2000000
	buf := make([]byte, maxCapacity)
	scanner.Buffer(buf, maxCapacity)
	var n int
	fmt.Scanln(&n)
	p := ReadInts(scanner)
	s := ReadInts(scanner)
	if n > 90000 {
		fmt.Println(n, p, len(p), len(s))
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GenerateChildrenIndexes(p []int) {
	for node, parent := range p {
		ChildrenIndexes[parent] = append(ChildrenIndexes[parent], node+2)
	}
	return
}

func GetChildrenIndexes(n node) []int {
	return ChildrenIndexes[n.index]
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int64 {
	sum := int64(n.a)
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	GenerateChildrenIndexes(p)
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var ChildrenIndexes [200000][]int

func ReadInts(s *bufio.Scanner) []int {
	s.Scan()
	line := s.Text()
	values := strings.Split(line, " ")
	var nums []int
	for _, val := range values {
		n, _ := strconv.Atoi(val)
		nums = append(nums, n)
	}
	return nums
}

func ReadInputs() ([]int, []int) {
	scanner := bufio.NewScanner(os.Stdin)
	var n int
	fmt.Scanln(&n)
	p := ReadInts(scanner)
	s := ReadInts(scanner)
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GenerateChildrenIndexes(p []int) {
	for node, parent := range p {
		ChildrenIndexes[parent] = append(ChildrenIndexes[parent], node+2)
	}
	return
}

func GetChildrenIndexes(n node) []int {
	return ChildrenIndexes[n.index]
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int64 {
	sum := int64(n.a)
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	GenerateChildrenIndexes(p)
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

import "fmt"

func ReadInputs() ([]int, []int) {
	var n int
	fmt.Scanln(&n)
	p := make([]int, n-1)
	for i := 0; i < n-1; i++ {
		fmt.Scan(&p[i])
	}
	s := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&s[i])
	}
	return p, s
}

func Max(v []int) (int, int) {
	m := 0
	im := 0
	for i, e := range v {
		if i == 0 || e > m {
			im = i
			m = e
		}
	}
	return im, m
}

func main() {
	p, s := ReadInputs()
	im, m := Max(s)

	if CheckParents(p, s, im+1) {
		if CheckChildren(p, s, im+1, m) {
			fmt.Println(m)
		} else {
			fmt.Println("-1")
		}
	} else {
		fmt.Println("-1")
	}
}

func GetNumIndex(v []int, n int) int {
	for i, val := range v {
		if val == n {
			return i
		}
	}
	return -1
}

func CheckChildren(p []int, s []int, v int, last int) bool {
	child := GetNumIndex(p, v)
	if child >= 0 {
		if last > s[child+1] && s[child+1] >= 0 {
			return false
		} else {
			if s[child+1] != -1 {
				last = s[child+1]
			}
			return CheckChildren(p, s, child+2, last)
		}
	} else {
		return true
	}
}

func CheckParents(p []int, s []int, v int) bool {
	if v == 1 {
		return true
	}

	if v > len(s) {
		return false
	}

	parent := p[v-2]

	if s[v-1] < s[parent] {
		return false
	}

	return CheckParents(p, s, parent)
}

package main

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

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		case 13:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	a[last_index] *= signal
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	fmt.Println(p, s)
	if n > 10000 {
		fmt.Println(n)
		os.Exit(0)
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GetChildrenIndexes(n node, p []int) []int {
	var indexes []int
	for index, parent := range p {
		if parent == n.index {
			indexes = append(indexes, index+2)
		}
	}
	return indexes
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n, p)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var ChildrenIndexes [200000][]int

func ReadInts(s *bufio.Scanner) []int {
	s.Scan()
	line := s.Text()
	values := strings.Split(line, " ")
	var nums []int
	for _, val := range values {
		n, _ := strconv.Atoi(val)
		nums = append(nums, n)
	}
	return nums
}

func ReadInputs() ([]int, []int) {
	scanner := bufio.NewScanner(os.Stdin)
	var n int
	fmt.Scanln(&n)
	p := ReadInts(scanner)
	s := ReadInts(scanner)
	if n > 90000 {
		fmt.Println(n, p, len(p), len(s))
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GenerateChildrenIndexes(p []int) {
	for node, parent := range p {
		ChildrenIndexes[parent] = append(ChildrenIndexes[parent], node+2)
	}
	return
}

func GetChildrenIndexes(n node) []int {
	return ChildrenIndexes[n.index]
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int64 {
	sum := int64(n.a)
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	GenerateChildrenIndexes(p)
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	if n >= 1 {
		fmt.Println(p, s)
	}
	if n > 10000 {
		fmt.Println(n)
		os.Exit(0)
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GetChildrenIndexes(n node, p []int) []int {
	var indexes []int
	for index, parent := range p {
		if parent == n.index {
			indexes = append(indexes, index+2)
		}
	}
	return indexes
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n, p)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		case 13:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	a[last_index] *= signal
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReaderSize(os.Stdin, 2000000)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	if n > 90000 {
		fmt.Println(n, len(p), len(s))
		os.Exit(0)
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GetChildrenIndexes(n node, p []int) []int {
	var indexes []int
	for index, parent := range p {
		if parent == n.index {
			indexes = append(indexes, index+2)
		}
	}
	return indexes
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n, p)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	if n > 10000 {
		fmt.Println(n)
		os.Exit(0)
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GetChildrenIndexes(n node, p []int) []int {
	var indexes []int
	for index, parent := range p {
		if parent == n.index {
			indexes = append(indexes, index+2)
		}
	}
	return indexes
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n, p)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		case 13:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	a[last_index] *= signal
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReaderSize(os.Stdin, 1000000)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	if n > 10000 {
		fmt.Println(n, len(p), len(s))
		os.Exit(0)
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GetChildrenIndexes(n node, p []int) []int {
	var indexes []int
	for index, parent := range p {
		if parent == n.index {
			indexes = append(indexes, index+2)
		}
	}
	return indexes
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n, p)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		case 13:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	if n > 10000 {
		fmt.Println(n)
		os.Exit(0)
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GetChildrenIndexes(n node, p []int) []int {
	var indexes []int
	for index, parent := range p {
		if parent == n.index {
			indexes = append(indexes, index+2)
		}
	}
	return indexes
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n, p)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

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

func ReadLine(r *bufio.Reader) []int {
	signal := 1
	bytes, _ := r.ReadSlice('\n')
	if len(bytes) == 1 {
		bytes, _ = r.ReadSlice('\n')
	}
	a := make([]int, len(bytes))
	last_index := 0
	for _, b := range bytes {
		switch b {
		case 32:
			a[last_index] *= signal
			last_index++
			signal = 1
		case 45:
			signal = -1
		case 10:
			break
		default:
			a[last_index] = a[last_index]*10 + int(b) - 48
		}
	}
	fmt.Println(bytes)
	return a[:last_index+1]
}

func ReadInputs() ([]int, []int) {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Scanln(&n)
	p := ReadLine(r)
	s := ReadLine(r)
	if n >= 1 {
		fmt.Println(p, s)
	}
	if n > 10000 {
		fmt.Println(n)
		os.Exit(0)
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GetChildrenIndexes(n node, p []int) []int {
	var indexes []int
	for index, parent := range p {
		if parent == n.index {
			indexes = append(indexes, index+2)
		}
	}
	return indexes
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n, p)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int {
	sum := n.a
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var ChildrenIndexes [200000][]int

func ReadInts(s *bufio.Scanner) []int {
	s.Scan()
	line := s.Text()
	values := strings.Split(line, " ")
	var nums []int
	for _, val := range values {
		n, _ := strconv.Atoi(val)
		nums = append(nums, n)
	}
	return nums
}

func ReadInputs() ([]int, []int) {
	scanner := bufio.NewScanner(os.Stdin)
	var n int
	fmt.Scanln(&n)
	p := ReadInts(scanner)
	s := ReadInts(scanner)
	if n > 90000 {
		fmt.Println(len(p), len(s))
	}
	return p, s
}

type node struct {
	index    int
	a        int
	parent   *node
	children []*node
	s        int
}

func GenerateChildrenIndexes(p []int) {
	for node, parent := range p {
		ChildrenIndexes[parent] = append(ChildrenIndexes[parent], node+2)
	}
	return
}

func GetChildrenIndexes(n node) []int {
	return ChildrenIndexes[n.index]
}

func BuildTree(index int, p []int, s []int, parent *node) *node {
	n := node{
		index:  index,
		a:      -1,
		parent: parent,
		s:      s[index-1],
	}
	children := GetChildrenIndexes(n)
	for _, child := range children {
		n.children = append(n.children, BuildTree(child, p, s, &n))
	}
	return &n
}

func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Update(n *node) {
	MinS := 0
	for i, child := range n.children {
		if child.s >= 0 {
			if i == 0 {
				MinS = child.s
			} else {
				if child.s < MinS {
					MinS = child.s
				}
			}
		}
	}
	previousS := 0
	if n.parent != nil {
		previousS = n.parent.s
	}
	if n.s >= 0 {
		n.a = n.s - previousS
	} else {
		n.s = Max(previousS, MinS)
		n.a = n.s - previousS
	}
	if n.a < 0 {
		fmt.Println(-1)
		os.Exit(0)
	}
	for i, _ := range n.children {
		Update(n.children[i])
	}
	return
}

func SumA(n *node) int64 {
	sum := int64(n.a)
	for _, child := range n.children {
		sum += SumA(child)
	}
	return sum
}

func PrintTree(root *node) {
	fmt.Println("index:", root.index, "a:", root.a, "s:", root.s)
	for _, child := range root.children {
		PrintTree(child)
	}
	return
}

func main() {
	p, s := ReadInputs()
	GenerateChildrenIndexes(p)
	root := BuildTree(1, p, s, nil)
	Update(root)
	fmt.Println(SumA(root))
}

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
)

const (
	BIG = 1024 * 1024 * 10
	INF = 10000000
)

func readLine(r *bufio.Reader) string {
	bytes, _, err := r.ReadLine()
	if err != nil {
		log.Fatalln("Failed to read line")
	}

	return string(bytes)
}

func readInts(r *bufio.Reader) []int {
	elems := strings.Fields(readLine(r))

	ret := make([]int, len(elems))
	for i, el := range elems {
		tmp, err := strconv.ParseInt(el, 10, 64)
		if err != nil {
			log.Fatalf("Failed to parse number %v", el)
		}
		ret[i] = int(tmp)
	}

	return ret
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func main() {
	r := bufio.NewReaderSize(os.Stdin, BIG)

	n := readInts(r)[0]
	pis := readInts(r)
	children := make([][]int, n)
	for i := 0; i < n; i++ {
		children[i] = make([]int, 0)
	}
	i := 1
	for _, pi := range pis {
		children[pi-1] = append(children[pi-1], i)
		i += 1
	}

	sis := readInts(r)
	ais := make([]int, n)
	odds := make([]int, 0)
	odds = append(odds, 0)
	ais[0] = sis[0]
	for len(odds) > 0 {
		nodds := make([]int, 0)
		for _, el := range odds {
			for _, child := range children[el] {
				ais[child] = INF
				for _, gchild := range children[child] {
					ais[gchild] = sis[gchild] - sis[el]
					if ais[gchild] < 0 {
						fmt.Println(-1)
						return
					}
					ais[child] = min(ais[child], ais[gchild])
					nodds = append(nodds, gchild)
				}
				if ais[child] == INF { // No grandchildren
					ais[child] = 0
				} else {
					for _, gchild := range children[child] {
						ais[gchild] -= ais[child]
					}
				}
			}
		}
		odds = nodds
	}

	res := 0
	for _, ai := range ais {
		res += ai
	}
	fmt.Println(res)
}

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
)

const (
	BIG = 1024 * 1024 * 10
)

func readLine(r *bufio.Reader) string {
	bytes, _, err := r.ReadLine()
	if err != nil {
		log.Fatalln("Failed to read line")
	}

	return string(bytes)
}

func readInts(r *bufio.Reader) []int {
	elems := strings.Fields(readLine(r))

	ret := make([]int, len(elems))
	for i, el := range elems {
		tmp, err := strconv.ParseInt(el, 10, 64)
		if err != nil {
			log.Fatalf("Failed to parse number %v", el)
		}
		ret[i] = int(tmp)
	}

	return ret
}

func main() {
	r := bufio.NewReaderSize(os.Stdin, BIG)

	n := readInts(r)[0]
	pis := readInts(r)
	children := make([][]int, n)
	for i := 0; i < n; i++ {
		children[i] = make([]int, 0)
	}
	i := 1
	for _, pi := range pis {
		children[pi-1] = append(children[pi-1], i)
		i += 1
	}

	sis := readInts(r)
	ais := make([]int, n)
	odds := make([]int, 0)
	odds = append(odds, 0)
	ais[0] = sis[0]
	for len(odds) > 0 {
		nodds := make([]int, 0)
		for _, el := range odds {
			for _, child := range children[el] {
				mval := -1
				for _, gchild := range children[child] {
					if sis[gchild] < sis[el] {
						fmt.Println(-1)
						return
					}

					if mval == -1 {
						mval = sis[gchild] - sis[el]
					} else if sis[gchild]-sis[el] != mval {
						fmt.Println(-1)
						return
					}
					ais[gchild] = sis[gchild] - mval - sis[el]
					nodds = append(nodds, gchild)
				}
				if mval == -1 { // Means that there were no gchilds
					mval = 0
				}
				ais[child] = mval
			}
		}
		odds = nodds
	}

	res := 0
	for _, ai := range ais {
		res += ai
	}
	fmt.Println(res)
}

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
)

const (
	BIG = 1024 * 1024 * 10
)

func readLine(r *bufio.Reader) string {
	bytes, _, err := r.ReadLine()
	if err != nil {
		log.Fatalln("Failed to read line")
	}

	return string(bytes)
}

func readInts(r *bufio.Reader) []int {
	elems := strings.Fields(readLine(r))

	ret := make([]int, len(elems))
	for i, el := range elems {
		tmp, err := strconv.ParseInt(el, 10, 64)
		if err != nil {
			log.Fatalf("Failed to parse number %v", el)
		}
		ret[i] = int(tmp)
	}

	return ret
}

func main() {
	r := bufio.NewReaderSize(os.Stdin, BIG)

	n := readInts(r)[0]
	pis := readInts(r)
	children := make([][]int, n)
	for i := 0; i < n; i++ {
		children[i] = make([]int, 0)
	}
	i := 1
	for _, pi := range pis {
		children[pi-1] = append(children[pi-1], i)
		i += 1
	}

	sis := readInts(r)
	ais := make([]int, n)
	odds := make([]int, 0)
	odds = append(odds, 0)
	ais[0] = sis[0]
	for len(odds) > 0 {
		nodds := make([]int, 0)
		for _, el := range odds {
			for _, child := range children[el] {
				ais[child] = 0
				for _, gchild := range children[child] {
					if sis[gchild] < sis[el] {
						fmt.Println(-1)
						return
					}

					ais[gchild] = sis[gchild] - sis[el]
					nodds = append(nodds, gchild)
				}
			}
		}
		odds = nodds
	}

	res := 0
	for _, ai := range ais {
		res += ai
	}
	fmt.Println(res)
}


Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.Chouti remembered that $$$n$$$ persons took part in that party. To make the party funnier, each person wore one hat among $$$n$$$ kinds of weird hats numbered $$$1, 2, \ldots n$$$. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.After the party, the $$$i$$$-th person said that there were $$$a_i$$$ persons wearing a hat differing from his own.It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let $$$b_i$$$ be the number of hat type the $$$i$$$-th person was wearing, Chouti wants you to find any possible $$$b_1, b_2, \ldots, b_n$$$ that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the number of persons in the party. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le n-1$$$), the statements of people.

If there is no solution, print a single line "Impossible". Otherwise, print "Possible" and then $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$). If there are multiple answers, print any of them.

NoteIn the answer to the first example, all hats are the same, so every person will say that there were no persons wearing a hat different from kind $$$1$$$.In the answer to the second example, the first and the second person wore the hat with type $$$1$$$ and all other wore a hat of type $$$2$$$.So the first two persons will say there were three persons with hats differing from their own. Similarly, three last persons will say there were two persons wearing a hat different from their own.In the third example, it can be shown that no solution exists.In the first and the second example, other possible configurations are possible.

package main

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

var (
	n int
	a []int

	// Map from group size to number of people claiming to be in this group.
	same = make(map[int]int)
	// Map from group size to current group.
	currGroupId = make(map[int]int)
	// Map from group size to current number of people in current group.
	currGroupSize = make(map[int]int)

	res []int
)

func dprintf(i string, a ...interface{}) {
	if false {
		fmt.Printf(i+"\n", a...)
	}
}

func calGr() bool {
	// How many are different from us.
	for _, ai := range a {
		nSame := n - ai
		same[nSame]++
	}

	currGrp := 1
	for i, ai := range a {
		nSame := n - ai
		gs := currGroupSize[nSame]
		if gs == 0 || gs == nSame {
			// New group.
			currGroupSize[nSame] = 1
			currGroupId[nSame] = currGrp
			currGrp++
		} else {
			currGroupSize[nSame]++
		}
		res[i] = currGroupId[nSame]
	}

	for grp, sz := range currGroupSize {
		if sz != grp {
			return false
		}
	}

	return true
}

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func main() {
	// STDOUT MUST BE FLUSHED MANUALLY!!!
	defer writer.Flush()

	scanf("%d\n", &n)
	a = make([]int, n)
	res = make([]int, n)
	for i, _ := range a {
		scanf("%d", &a[i])
	}
	// fmt.Printf("input=%v, %v\n", n, a)
	if calGr() {
		printf("Possible\n")
		for _, ai := range res {
			printf("%d ", ai)
		}
	} else {
		printf("Impossible\n")
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	a := make([]int, n)
	ans := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d", &a[i])
		a[i] = n - a[i]
	}
	id := 1
	remaining := make(map[int]int)
	currentID := make(map[int]int)
	for i := 0; i < n; i++ {
		if remaining[a[i]] > 0 {
			remaining[a[i]]--
			ans[i] = currentID[a[i]]
		} else {
			remaining[a[i]] = a[i] - 1
			ans[i] = id
			currentID[a[i]] = id
			id++
		}
	}
	noRemaining := true
	for _, v := range remaining {
		if v > 0 {
			noRemaining = false
			break
		}
	}
	if noRemaining {
		fmt.Fprintf(out, "Possible\n")
		for i := 0; i < n-1; i++ {
			fmt.Fprintf(out, "%d ", ans[i])
		}
		fmt.Fprintf(out, "%d\n", ans[n-1])
	} else {
		fmt.Fprintf(out, "Impossible\n")
	}
	return
}

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

func main() {
	r := bufio.NewReaderSize(os.Stdin, 100*1024*1024)
	nums := readInts(r, readInt(r))

	hats, err := getHats(nums)
	if err != nil {
		fmt.Print("Impossible")
		return
	}

	fmt.Println("Possible")
	for i, hat := range hats {
		fmt.Print(hat)
		if i < len(hats) - 1 {
			fmt.Print(" ")
		}
	}
}

func getHats(bs []int) ([]int, error) {
	groups := make(map[int][]int)

	for i, b := range bs {
		s := len(bs) - 1 - b
		groups[s] = append(groups[s], i)
	}

	hats := make([]int, len(bs))
	curHat := 0
	for count, idxs := range groups {
		if len(idxs) % (count + 1) != 0 {
			return nil, errors.New("no")
		}

		for i, idx := range idxs {
			if i % (count + 1) == 0 {
				curHat++
			}
			hats[idx] = curHat
		}
	}

	return hats, nil
}

func readInt(reader *bufio.Reader) int {
	tmpInt, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)
	return int(tmpInt)
}

func readInts(reader *bufio.Reader, n int) []int {
	tmpInts := strings.Split(readLine(reader), " ")

	var result []int
	for i := 0; i < n; i++ {
		tmpInt, err := strconv.ParseInt(tmpInts[i], 10, 64)
		checkError(err)
		result = append(result, int(tmpInt))
	}
	return result
}

func readLine(reader *bufio.Reader) string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}

	return strings.TrimRight(string(str), "\r\n")
}

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var scanner = bufio.NewScanner(os.Stdin)

func scanNum() int {
	scanner.Scan()
	num, _ := strconv.Atoi(scanner.Text())
	return num
}
func main() {
	scanner.Split(bufio.ScanWords)
	n := scanNum()
	g, nums, res := map[int]int{}, make([]int, n), []string{}

	for i := 0; i < n; i++ {
		nums[i] = n - scanNum()
		g[nums[i]]++
	}

	for k, v := range g {
		if v%k != 0 {
			fmt.Println("Impossible")
			os.Exit(0)
		}
	}

	counter, hats, cur := map[int]int{}, map[int]int{}, 1

	for _, d := range nums {
		if (hats[d] == 0) || (counter[hats[d]] == d) {
			hats[d], cur = cur, cur+1
		}
		res = append(res, strconv.Itoa(hats[d]))
		counter[hats[d]]++
	}

	fmt.Println("Possible")
	fmt.Println(strings.Join(res, " "))
}

package main

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

var (
	n int
	a []int

	// Map from grsize to number of members.
	sm = make(map[int]int)

	res []int
)

func dprintf(i string, a ...interface{}) {
	if false {
		fmt.Printf(i+"\n", a...)
	}
}

func calGr() bool {
	for _, ai := range a {
		grSize := n - ai
		sm[grSize]++
	}

	x := 1
	for grSize, nelts := range sm {
		if nelts%grSize != 0 {
			return false
		}

		for i := 0; i < nelts/grSize; i++ {
			for j := 0; j < grSize; j++ {
				res = append(res, x)
			}
			x++
		}
	}

	dprintf("%v", sm)

	return true
}

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func main() {
	// STDOUT MUST BE FLUSHED MANUALLY!!!
	defer writer.Flush()

	scanf("%d\n", &n)
	a = make([]int, n)
	for i, _ := range a {
		scanf("%d", &a[i])
	}
	// fmt.Printf("input=%v, %v\n", n, a)
	if calGr() {
		printf("Possible\n")
		for _, ai := range res {
			printf("%d ", ai)
		}
	} else {
		printf("Impossible\n")
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var scanner = bufio.NewScanner(os.Stdin)

func scanNum() int {
	scanner.Scan()
	num, _ := strconv.Atoi(scanner.Text())
	return num
}
func main() {
	scanner.Split(bufio.ScanWords)
	n := scanNum()
	g, res, cur := map[int]int{}, []string{}, 1

	for i := 0; i < n; i++ {
		g[n-scanNum()]++
	}

	for k, v := range g {
		if v%k != 0 {
			fmt.Println("Impossible")
			os.Exit(0)
		}

		for i := 0; i < v/k; i++ {
			for j := 0; j < k; j++ {
				res = append(res, strconv.Itoa(cur))
			}
			cur++
		}
	}

	fmt.Println("Possible")
	fmt.Println(strings.Join(res, " "))
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var scanner = bufio.NewScanner(os.Stdin)

func scanNum() int {
	scanner.Scan()
	num, _ := strconv.Atoi(scanner.Text())
	return num
}
func main() {
	scanner.Split(bufio.ScanWords)
	n := scanNum()
	g, nums, res := map[int]int{}, make([]int, n), []string{}

	for i := 0; i < n; i++ {
		nums[i] = n - scanNum()
		g[nums[i]]++
	}

	for k, v := range g {
		if v%k != 0 {
			fmt.Println("Impossible")
			os.Exit(0)
		}
	}

	counter, indicator, cur := map[int]int{}, map[int]int{}, 1

	for _, d := range nums {
		if (indicator[d] == 0) || (counter[indicator[d]] == d) {
			counter[d], indicator[d], cur = 0, cur, cur+1
		}
		res = append(res, strconv.Itoa(indicator[d]))
		counter[indicator[d]]++
	}

	fmt.Println("Possible")
	fmt.Println(strings.Join(res, " "))
}


Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:  Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.  Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≤ i ≤ n).  Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.

The first line contains integers n, m (1 ≤ n, m ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≤ ti ≤ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≤ vi ≤ n, 1 ≤ xi ≤ 109). If ti = 2, then it is followed by integer yi (1 ≤ yi ≤ 104). And if ti = 3, then it is followed by integer qi (1 ≤ qi ≤ n).

For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.

package main

import "fmt"
import "os"
import "bufio"
import "strconv"

func main(){
	var n, m int
	fmt.Scan(&n, &m)
	a := make([]int, n)
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	for i:=0; i<n; i++ {
		r.Scan()
		a[i], _ = strconv.Atoi(r.Text())
	}
	op := 0
	v := 0
	x := 0
	y := 0
	q := 0
	plus := 0
	var hasil string
	for j:=0; j<m; j++ {
		r.Scan()
		op, _ = strconv.Atoi(r.Text())
		if op == 1 {
			r.Scan()
			v, _ = strconv.Atoi(r.Text())
			r.Scan()
			x, _ = strconv.Atoi(r.Text())
			a[v-1] = x - plus
		} else if op == 2 {
			r.Scan()
			y, _ = strconv.Atoi(r.Text())
			plus += y
			/*for k:=0; k<n; k++ {
				a[k] += y
			}*/
		} else if op == 3 {
			r.Scan()
			q, _ = strconv.Atoi(r.Text())
			hasil = strconv.Itoa(a[q-1]+plus)
			w.WriteString(hasil+"\n")
			w.Flush()
		}
	}

}

package main

import (
  "bufio"
  "os"
  "strconv"
)

var sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
var w *bufio.Writer = bufio.NewWriter(os.Stdout)

func ni() int {
  sc.Scan()
  ans, _ := strconv.Atoi(sc.Text())
  return ans
}

func next() string {
  sc.Scan()
  return sc.Text()
}

func pri(n int)    { w.WriteString(strconv.Itoa(n)) }
func prll(n int64) { w.WriteString(strconv.FormatInt(n, 10)) }
func sp()          { w.WriteByte(' ') }
func endl()        { w.WriteByte('\n') }

func main() {
  sc.Split(bufio.ScanWords)
  n, m := ni(), ni()
  acc := int64(0)
  a := make([]int64, n)
  for i := 0; i < n; i++ {
    a[i] = int64(ni())
  }
  for i := 0; i < m; i++ {
    t := ni()
    if t == 1 {
      a[ni()-1] = int64(ni()) - acc
    } else if t == 2 {
      acc += int64(ni())
    } else {
      prll(acc + a[ni()-1])
      endl()
    }
  }
  w.Flush()
}

package main

import (
  "os"
  "bufio"
  "strconv"
  "fmt"
)

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n, m := getI(), getI()
  a := make([]int64, n+1)
  for i := 1; i <= n; i++ {
    a[i] = getI64()
  }
  delta, written := make([]int64, m+1), make([]int, n+1)
  for i := 1; i <= m; i++ {
    delta[i] = delta[i-1]
    t := getI()
    if t == 1 {
      pos, value := getI(), getI64()
      a[pos] = value
      written[pos] = i
    } else if t == 2 {
      delta[i] += getI64()
    } else {
      pos := getI()
      x := a[pos] + delta[i] - delta[written[pos]]
      writer.WriteString(fmt.Sprintf("%d\n", x))
    }
  }
}

package main

import (
    "fmt"
    "bufio"
    "os"
    "strconv"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    writer := bufio.NewWriter(os.Stdout)

    scan := func() (r int) {
        scanner.Scan()
        r, _ = strconv.Atoi(scanner.Text())
        return
    }

    var n,m int
    fmt.Scan(&n,&m)
    a := make([]int,n+1)
    for i := 1; i <= n; i++ {
        a[i] = scan()
    }
    cnt := 0
    for i := 0; i < m; i++ {
        t := scan()
        if t == 1 {
            v := scan()
            x := scan()
            a[v] = x-cnt
        } else if t == 2 {
            y := scan()
            cnt += y
        } else {
            q := scan()
            writer.WriteString(strconv.Itoa(a[q]+cnt)+"\n")
        }
    }
    writer.Flush()
}

// 315B
package main

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

func main() {
	var n, m, t, a, b int
	var v [100000]int
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &v[i])
	}
	tot := 0
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &t)
		fmt.Fscan(in, &a)
		if t == 1 {
			fmt.Fscan(in, &b)
			v[a-1] = b - tot
		} else if t == 2 {
			tot += a
		} else {
			fmt.Fprintln(out, v[a-1]+tot)
		}
	}
	out.Flush()
}

// 315B-mic_rizal
package main

import (
	"bufio"
	//"fmt"
	"os"
	"strconv"
)

func main() {
	var n, m, s, y int
	//z := bufio.NewReader(os.Stdin)
	d := bufio.NewScanner(os.Stdin)
	d.Split(bufio.ScanWords)
	h := bufio.NewWriter(os.Stdout)
	d.Scan()
	xxx, _ := strconv.Atoi(d.Text())
	n = xxx
	d.Scan()
	xz, _ := strconv.Atoi(d.Text())
	m = xz
	//fmt.Fscan(z, &n, &m)
	var a [1000000]int
	for i := 1; i <= n; i++ {
		d.Scan()
		w, _ := strconv.Atoi(d.Text())
		a[i] = w
		//fmt.Fscan(z, &a[i])
	}
	for i := 0; i < m; i++ {
		d.Scan()
		wwwwww, _ := strconv.Atoi(d.Text())
		y = wwwwww
		//fmt.Fscan(z, &y)
		if y == 1 {
			d.Scan()
			ww, _ := strconv.Atoi(d.Text())
			d.Scan()
			www, _ := strconv.Atoi(d.Text())
			//fmt.Fscan(z, &b, &x)
			a[ww] = www - s
		} else if y == 2 {
			d.Scan()
			wwww, _ := strconv.Atoi(d.Text())
			//fmt.Fscan(z, &x)
			s += wwww
		} else {
			d.Scan()
			wwwww, _ := strconv.Atoi(d.Text())
			//fmt.Fscan(z, &b)
			f := strconv.Itoa(s + a[wwwww])
			h.WriteString(f + "\n")
			//fmt.Println(s + a[b])
			h.Flush()
		}
	}
}

package main

import "fmt"
import "os"
import "bufio"
import "strconv"

func main(){
	var n, m int
	fmt.Scan(&n, &m)
	a := make([]int, n)
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	for i:=0; i<n; i++ {
		r.Scan()
		a[i], _ = strconv.Atoi(r.Text())
	}
	op := 0
	v := 0
	x := 0
	y := 0
	q := 0
	var hasil string
	for j:=0; j<m; j++ {
		fmt.Scan(&op)
		if op == 1 {
			fmt.Scan(&v, &x)
			a[v-1] = x
		} else if op == 2 {
			fmt.Scan(&y)
			for k:=0; k<n; k++ {
				a[k] += y
			}
		} else if op == 3 {
			fmt.Scan(&q)
			hasil = strconv.Itoa(a[q-1])
			w.WriteString(hasil+"\n")
			w.Flush()
		}
	}

}

package main

import "fmt"
import "os"
import "bufio"
import "strconv"

func main(){
	var n, m int
	fmt.Scan(&n, &m)
	a := make([]int, n)
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	for i:=0; i<n; i++ {
		r.Scan()
		a[i], _ = strconv.Atoi(r.Text())
	}
	op := 0
	v := 0
	x := 0
	y := 0
	q := 0
	for j:=0; j<m; j++ {
		fmt.Scan(&op)
		if op == 1 {
			fmt.Scan(&v, &x)
			a[v-1] = x
		} else if op == 2 {
			fmt.Scan(&y)
			for k:=0; k<n; k++ {
				a[k] += y
			}
		} else if op == 3 {
			fmt.Scan(&q)
			fmt.Fprint(w, a[q-1], "\n")
			w.Flush()
		}
	}

}

package main

import "fmt"
import "os"
import "bufio"
import "strconv"

func main(){
	var n, m int
	fmt.Scan(&n, &m)
	a := make([]int, n)
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	for i:=0; i<n; i++ {
		r.Scan()
		a[i], _ = strconv.Atoi(r.Text())
	}
	op := 0
	v := 0
	x := 0
	y := 0
	q := 0
	var hasil string
	for j:=0; j<m; j++ {
		fmt.Scan(&op)
		if op == 1 {
			r.Scan()
			v, _ = strconv.Atoi(r.Text())
			r.Scan()
			x, _ = strconv.Atoi(r.Text())
			a[v-1] = x
		} else if op == 2 {
			r.Scan()
			y, _ = strconv.Atoi(r.Text())
			for k:=0; k<n; k++ {
				a[k] += y
			}
		} else if op == 3 {
			r.Scan()
			q, _ = strconv.Atoi(r.Text())
			hasil = strconv.Itoa(a[q-1])
			w.WriteString(hasil+"\n")
			w.Flush()
		}
	}

}

package main

import "fmt"
import "os"
import "bufio"
import "strconv"

func main(){
	var n, m int
	fmt.Scan(&n, &m)
	a := make([]int, n)
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for i:=0; i<n; i++ {
		r.Scan()
		a[i], _ = strconv.Atoi(r.Text())
	}
	op := 0
	v := 0
	x := 0
	y := 0
	q := 0
	for j:=0; j<m; j++ {
		fmt.Scan(&op)
		if op == 1 {
			fmt.Scan(&v, &x)
			a[v-1] = x
		} else if op == 2 {
			fmt.Scan(&y)
			for k:=0; k<n; k++ {
				a[k] += y
			}
		} else if op == 3 {
			fmt.Scan(&q)
			fmt.Fprintln(os.Stdout, a[q-1])
		}
	}
}

package main

import "fmt"
import "os"
import "bufio"
import "strconv"

func main(){
	var n, m int
	fmt.Scan(&n, &m)
	a := make([]int, n)
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for i:=0; i<n; i++ {
		r.Scan()
		a[i], _ = strconv.Atoi(r.Text())
	}
	op := 0
	v := 0
	x := 0
	y := 0
	q := 0
	for j:=0; j<m; j++ {
		fmt.Scan(&op)
		if op == 1 {
			fmt.Scan(&v, &x)
			a[v-1] = x
		} else if op == 2 {
			fmt.Scan(&y)
			for k:=0; k<n; k++ {
				a[k] += y
			}
		} else if op == 3 {
			fmt.Scan(&q)
			fmt.Println(a[q-1])
		}
	}
}

// 315B
package main

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

func main() {
	var n, m, t, a, b int
	var v [100000]int
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Scan(&n, &m)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &v[i])
	}
	tot := 0
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &t)
		fmt.Fscan(in, &a)
		if t == 1 {
			fmt.Scan(&b)
			v[a-1] = b - tot
		} else if t == 2 {
			tot += a
		} else {
			fmt.Fprintln(out, v[a-1]+tot)
		}
	}
}

// 315B
package main

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

func main() {
	var n, m, t, a, b int
	var v [100000]int
	in := bufio.NewReader(os.Stdin)
	fmt.Scan(&n, &m)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &v[i])
	}
	tot := 0
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &t)
		fmt.Fscan(in, &a)
		if t == 1 {
			fmt.Scan(&b)
			v[a-1] = b - tot
		} else if t == 2 {
			tot += a
		} else {
			fmt.Println(v[a-1] + tot)
		}
	}
}

// 315B
package main

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

func main() {
	var n, m, t, a, b int
	var v [100000]int
	in := bufio.NewReader(os.Stdin)
	fmt.Scan(&n, &m)
	for i := 0; i < n; i++ {
		fmt.Scan(&v[i])
	}
	tot := 0
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &t)
		fmt.Fscan(in, &a)
		if t == 1 {
			fmt.Scan(&b)
			v[a-1] = b - tot
		} else if t == 2 {
			tot += a
		} else {
			fmt.Println(v[a-1] + tot)
		}
	}
}

// 315B
package main

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

func main() {
	var n, m, t, a, b int
	var v [100000]int
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &v[i])
	}
	tot := 0
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &t)
		fmt.Fscan(in, &a)
		if t == 1 {
			fmt.Fscan(in, &b)
			v[a-1] = b - tot
		} else if t == 2 {
			tot += a
		} else {
			fmt.Fprintln(out, v[a-1]+tot)
		}
	}
}

// 315B
package main

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

func main() {
	var n, m, t, a, b int
	var v [100000]int
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Scan(&n, &m)
	for i := 0; i < n; i++ {
		fmt.Scan(&v[i])
	}
	tot := 0
	for i := 0; i < m; i++ {
		fmt.Fscan(in, &t)
		fmt.Fscan(in, &a)
		if t == 1 {
			fmt.Scan(&b)
			v[a-1] = b - tot
		} else if t == 2 {
			tot += a
		} else {
			fmt.Fprintln(out, v[a-1]+tot)
		}
	}
}

// 315B-mic_rizal
package main

import (
	"bufio"
	//"fmt"
	"os"
	"strconv"
)

func main() {
	var n, m, s, y, b int
	//z := bufio.NewReader(os.Stdin)
	d := bufio.NewScanner(os.Stdin)
	d.Split(bufio.ScanWords)
	h := bufio.NewWriter(os.Stdout)
	d.Scan()
	xxx, _ := strconv.Atoi(d.Text())
	n = xxx
	d.Scan()
	xz, _ := strconv.Atoi(d.Text())
	m = xz
	//fmt.Fscan(z, &n, &m)
	a := make([]int, n+1)
	for i := 1; i <= n; i++ {
		d.Scan()
		w, _ := strconv.Atoi(d.Text())
		a[i] = w
		//fmt.Fscan(z, &a[i])
	}
	for i := 0; i < m; i++ {
		d.Scan()
		wwwwww, _ := strconv.Atoi(d.Text())
		y = wwwwww
		//fmt.Fscan(z, &y)
		if y == 1 {
			d.Scan()
			ww, _ := strconv.Atoi(d.Text())
			d.Scan()
			www, _ := strconv.Atoi(d.Text())
			//fmt.Fscan(z, &b, &x)
			a[b] = ww - www
		} else if y == 2 {
			d.Scan()
			wwww, _ := strconv.Atoi(d.Text())
			//fmt.Fscan(z, &x)
			s += wwww
		} else {
			d.Scan()
			wwwww, _ := strconv.Atoi(d.Text())
			//fmt.Fscan(z, &b)
			f := strconv.Itoa(s + a[wwwww])
			h.WriteString(f + "\n")
			//fmt.Println(s + a[b])
			h.Flush()
		}
	}
}


The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep". Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number.In Shapur's opinion the weakness of an army is equal to the number of triplets i, j, k such that i < j < k and ai > aj > ak where ax is the power of man standing at position x. The Roman army has one special trait — powers of all the people in it are distinct.Help Shapur find out how weak the Romans are.

The first line of input contains a single number n (3 ≤ n ≤ 106) — the number of men in Roman army. Next line contains n different positive integers ai (1 ≤ i ≤ n, 1 ≤ ai ≤ 109) — powers of men in the Roman army.

A single integer number, the weakness of the Roman army.  Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"sort"
)

var segTree [3000000]int

func treePlus(index, l, r, left, right, plus int) {
	mid := (l + r) / 2
	if l == left && r == right {
		segTree[index] += plus
	} else if mid >= right {
		treePlus(index*2+1, l, mid, left, right, plus)
	} else if mid < left {
		treePlus(index*2+2, mid+1, r, left, right, plus)
	} else {
		treePlus(index*2+1, l, mid, left, mid, plus)
		treePlus(index*2+2, mid+1, r, mid+1, right, plus)
	}
}

func treeQuery(index, l, r, pos int) int {
	mid := (l + r) / 2
	if l == r && l == pos {
		return segTree[index]
	} else if pos <= mid {
		return segTree[index] + treeQuery(index*2+1, l, mid, pos)
	} else if pos > mid {
		return segTree[index] + treeQuery(index*2+2, mid+1, r, pos)
	}
	return 0
}

var smallCount [1000000]int
var largeCount [1000000]int

type weakness struct {
	a, pos int
}

type weaknessSorter []weakness

func (ws *weaknessSorter) Len() int {
	return len(*ws)
}
func (ws *weaknessSorter) Less(i, j int) bool {
	return (*ws)[i].a < (*ws)[j].a
}

func (ws *weaknessSorter) Swap(i, j int) {
	(*ws)[i], (*ws)[j] = (*ws)[j], (*ws)[i]
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	sorter := make(weaknessSorter, 0, n)
	for i := 0; i < n; i++ {
		var a int
		fmt.Fscanf(reader, "%d ", &a)
		sorter = append(sorter, weakness{a, i})
	}
	sort.Sort(&sorter)

	for i := n - 1; i >= 0; i-- {
		largeCount[sorter[i].pos] = treeQuery(0, 0, n-1, sorter[i].pos)
		treePlus(0, 0, n-1, sorter[i].pos, n-1, 1)
	}
	for i := 0; i < len(segTree); i++ {
		segTree[i] = 0
	}
	for i := 0; i < n; i++ {
		smallCount[sorter[i].pos] = treeQuery(0, 0, n-1, sorter[i].pos)
		treePlus(0, 0, n-1, 0, sorter[i].pos, 1)
	}
	var ans uint64
	for i := 0; i < n; i++ {
		ans += uint64(largeCount[i]) * uint64(smallCount[i])
	}
	fmt.Printf("%d", ans)
}