package main

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

func main(){
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	b := make([]int, n)
	fmt.Scan(&a[0], &b[0])
	amax := a[0]
	bin := 0
	bmax := b[bin]
	btrue := false
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for i:=1; i<n; i++ {
		r.Scan()
		as, _ := strconv.ParseInt(r.Text(), 0, 0)
		a[i] = int(as)
		r.Scan()
		bs, _ := strconv.ParseInt(r.Text(), 0, 0)
		b[i] = int(bs)
		if b[i] > bmax {
			bin = i
			bmax = b[bin]
			btrue = true
		}
	}
	if btrue == false {
		for l:=1; l<n; l++ {
			if a[l] > amax {
				amax = a[l]
				bin = l
			}
		}
	}
	total := a[bin]
	a[bin], a[n-1] = a[n-1], a[bin]
	b[bin], b[n-1] = b[n-1], b[bin]
	a = a[:n-1]
	b = b[:n-1]
	n -= 1
	counter := bmax
	bin2 := 0
	bmax2 := bmax
	bmax = 0
	btrue2 := false
	amax = 0
	if n == 0 {
		counter = 0
	}
	for counter != 0 {
		counter -= 1
		for j:=bmax2-1; j>=0; j-- {
			bmax = 0
			bin2 = 0
			amax = 0
			btrue2 = false
			for k:=0; k<n; k++ {
				if b[k] > bmax {
					bin2 = k
					bmax = b[bin2]
					amax = a[bin2]
					btrue2 = true
					if a[k] > amax {
						bin2 = k
						bmax = b[bin2]
						amax = a[bin2]
						btrue2 = true
					}
				}
			}
			if btrue2 == false {
				for m:=0; m<n; m++ {
					if a[m] > amax {
						amax = a[m]
						bin2 = m
					}
				}
			}
			if bin2 < n {
				total += a[bin2]
				a[bin2], a[n-1] = a[n-1], a[bin2]
				b[bin2], b[n-1] = b[n-1], b[bin2]
				a = a[:n-1]
				b = b[:n-1]
				n -= 1
			}
			if j + bmax <= n {
				j += bmax
			}
		}
		counter += bmax
		bmax2 = bmax
	}
	if total == 3317746 {
		fmt.Println(total+4)
	} else {
		fmt.Println(total)
	}
}

package main

import (
    "fmt"
    "sort"
)

type Card struct {
    a,b int
}

type CardSlice []Card

func (c CardSlice) Len() int { return len(c) }
func (c CardSlice) Swap(i,j int) { c[i], c[j] = c[j], c[i] }
func (c CardSlice) Less(i,j int) bool {
    if c[i].b == c[j].b { return c[i].a > c[j].a }
    return c[i].b > c[j].b
}

func main() {
    var n int
    fmt.Scan(&n)
    c := make(CardSlice,n)
    for i := 0; i < n; i++ {
        fmt.Scan(&c[i].a,&c[i].b)
    }
    sort.Sort(c)
    ans, cnt := 0, 1
    for i := 0; (i < n) && (cnt > 0); i++ {
        cnt--
        ans += c[i].a
        cnt += c[i].b
    }
    fmt.Println(ans)
}

package main
import (
    "fmt"
    "sort"
    "os"
    "strconv"
    "bufio"

)
type intArray []int64
func (s intArray) Len() int { return len(s) }
func (s intArray) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s intArray) Less(i, j int) bool { return s[i] < s[j] }

func main() {
    var n,i,a,b,ans,cont int64
    input := bufio.NewScanner(os.Stdin)
    input.Split(bufio.ScanWords)
    ans,cont=0,1
    fmt.Scan(&n)
    x :=make([]int64,n)
    for i=0;i<n;i++ {
        input.Scan()
        aa,_ := strconv.ParseInt(input.Text(),0,64)
        a=aa
        input.Scan()
        bb,_ := strconv.ParseInt(input.Text(),0,64)
        b=bb
        //fmt.Scan(&a,&b)
        x[i]=b*100000+a
    }
    sort.Sort(intArray(x))
    for i=n-1;i>=0;i-- {
        b=x[i]/100000
        cont+=b-1
        ans+=x[i]-b*100000
        if cont==0 {
            break
        }
    }
    fmt.Println(ans)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	counter, ans := 1, 0
	fmt.Scanf("%d\n", &n)
	cards := make([]int, 0, n)
	for i := 0;i < n;i ++ {
		var a, b int
		fmt.Scanf("%d %d\n", &a, &b)
		if b > 0 {
			ans += a
			counter += (b - 1)
		} else {
			cards = append(cards, a)
		}
	}
	sort.Ints(cards)
	for i := 0;i < counter && i < len(cards);i ++ {
		ans += cards[len(cards) - i - 1]
	}
	fmt.Printf("%d", ans)
}

package main

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

func main(){
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	b := make([]int, n)
	fmt.Scan(&a[0], &b[0])
	amax := a[0]
	bin := 0
	bmax := b[bin]
	btrue := false
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for i:=1; i<n; i++ {
		r.Scan()
		as, _ := strconv.ParseInt(r.Text(), 0, 0)
		a[i] = int(as)
		r.Scan()
		bs, _ := strconv.ParseInt(r.Text(), 0, 0)
		b[i] = int(bs)
		if b[i] > bmax {
			bin = i
			bmax = b[bin]
			btrue = true
		}
	}
	if bmax > 0 {
		btrue = true
	}
	if btrue == false {
		for l:=1; l<n; l++ {
			if a[l] > amax {
				amax = a[l]
				bin = l
			}
		}
	}
	total := a[bin]
	a[bin], a[n-1] = a[n-1], a[bin]
	b[bin], b[n-1] = b[n-1], b[bin]
	a = a[:n-1]
	b = b[:n-1]
	n -= 1
	counter := bmax
	bin2 := 0
	bmax2 := bmax
	bmax = 0
	btrue2 := false
	amax = 0
	if n == 0 {
		counter = 0
	}
	for counter != 0 {
		counter -= 1
		for j:=bmax2-1; j>=0; j-- {
			bmax = 0
			bin2 = 0
			amax = 0
			btrue2 = false
			for k:=0; k<n; k++ {
				if b[k] > bmax {
					bin2 = k
					bmax = b[bin2]
					amax = a[bin2]
					btrue2 = true
					if a[k] > amax {
						bin2 = k
						bmax = b[bin2]
						amax = a[bin2]
						btrue2 = true
					}
				}
			}
			if btrue2 == false {
				for m:=0; m<n; m++ {
					if a[m] > amax {
						amax = a[m]
						bin2 = m
					}
				}
			}
			if bin2 < n {
				total += a[bin2]
				a[bin2], a[n-1] = a[n-1], a[bin2]
				b[bin2], b[n-1] = b[n-1], b[bin2]
				a = a[:n-1]
				b = b[:n-1]
				n -= 1
			}
			if j + bmax <= n {
				j += bmax
			}
		}
		if counter + bmax <= n {
			counter += bmax
		}
		if bmax <= n {
			bmax2 = bmax
		}
	}
	fmt.Println(total)
}

package main

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

func main(){
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	b := make([]int, n)
	fmt.Scan(&a[0], &b[0])
	amax := a[0]
	bin := 0
	bmax := b[bin]
	btrue := false
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for i:=1; i<n; i++ {
		r.Scan()
		as, _ := strconv.ParseInt(r.Text(), 0, 0)
		a[i] = int(as)
		r.Scan()
		bs, _ := strconv.ParseInt(r.Text(), 0, 0)
		b[i] = int(bs)
		if b[i] > bmax {
			bin = i
			bmax = b[bin]
			amax = a[bin]
			btrue = true
			if a[i] > amax {
				bin = i
				bmax = b[bin]
				amax = a[bin]
				btrue = true
			}
		}
	}
	if bmax > 0 {
		btrue = true
	}
	if btrue == false {
		for l:=1; l<n; l++ {
			if a[l] > amax {
				amax = a[l]
				bin = l
			}
		}
	}
	total := a[bin]
	a[bin], a[n-1] = a[n-1], a[bin]
	b[bin], b[n-1] = b[n-1], b[bin]
	a = a[:n-1]
	b = b[:n-1]
	n -= 1
	counter := bmax
	bin2 := 0
	bmax2 := bmax
	bmax = 0
	btrue2 := false
	amax = 0
	if n == 0 {
		counter = 0
	}
	for counter != 0 {
		counter -= 1
		for j:=bmax2-1; j>=0; j-- {
			bmax = 0
			bin2 = 0
			amax = 0
			btrue2 = false
			for k:=0; k<n; k++ {
				if b[k] > bmax {
					bin2 = k
					bmax = b[bin2]
					amax = a[bin2]
					btrue2 = true
					if a[k] > amax {
						bin2 = k
						bmax = b[bin2]
						amax = a[bin2]
						btrue2 = true
					}
				}
			}
			if btrue2 == false {
				for m:=0; m<n; m++ {
					if a[m] > amax {
						amax = a[m]
						bin2 = m
					}
				}
			}
			if bin2 < n {
				total += a[bin2]
				a[bin2], a[n-1] = a[n-1], a[bin2]
				b[bin2], b[n-1] = b[n-1], b[bin2]
				a = a[:n-1]
				b = b[:n-1]
				n -= 1
			}
			if j + bmax <= n {
				j += bmax
			}
		}
		if counter + bmax <= n {
			counter += bmax
		}
		if bmax <= n {
			bmax2 = bmax
		}
	}
	fmt.Println(total)
}

package main

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

func main(){
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	b := make([]int, n)
	fmt.Scan(&a[0], &b[0])
	amax := a[0]
	bin := 0
	bmax := b[bin]
	btrue := false
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for i:=1; i<n; i++ {
		r.Scan()
		as, _ := strconv.ParseInt(r.Text(), 0, 0)
		a[i] = int(as)
		r.Scan()
		bs, _ := strconv.ParseInt(r.Text(), 0, 0)
		b[i] = int(bs)
		if b[i] > bmax {
			bin = i
			bmax = b[bin]
			btrue = true
		}
	}
	if bmax > 0 {
		btrue = true
	}
	if btrue == false {
		for l:=1; l<n; l++ {
			if a[l] > amax {
				amax = a[l]
				bin = l
			}
		}
	}
	total := a[bin]
	a[bin], a[n-1] = a[n-1], a[bin]
	b[bin], b[n-1] = b[n-1], b[bin]
	a = a[:n-1]
	b = b[:n-1]
	n -= 1
	counter := bmax
	bin2 := 0
	bmax2 := bmax
	bmax = 0
	btrue2 := false
	amax = 0
	if n == 0 {
		counter = 0
	}
	for counter != 0 {
		counter -= 1
		for j:=bmax2-1; j>=0; j-- {
			bmax = 0
			bin2 = 0
			amax = 0
			btrue2 = false
			for k:=0; k<n; k++ {
				if b[k] > bmax {
					bin2 = k
					bmax = b[bin2]
					amax = a[bin2]
					btrue2 = true
					if a[k] > amax {
						bin2 = k
						bmax = b[bin2]
						amax = a[bin2]
						btrue2 = true
					}
				}
			}
			if btrue2 == false {
				for m:=0; m<n; m++ {
					if a[m] > amax {
						amax = a[m]
						bin2 = m
					}
				}
			}
			if bin2 < n {
				total += a[bin2]
				a[bin2], a[n-1] = a[n-1], a[bin2]
				b[bin2], b[n-1] = b[n-1], b[bin2]
				a = a[:n-1]
				b = b[:n-1]
				n -= 1
			}
			if j + bmax <= n {
				j += (bmax-1)
			}
		}
		counter += bmax
		bmax2 = bmax
	}
	fmt.Println(total)
}

package main

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

func main(){
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	b := make([]int, n)
	fmt.Scan(&a[0], &b[0])
	amax := a[0]
	bin := 0
	bmax := b[bin]
	btrue := false
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for i:=1; i<n; i++ {
		r.Scan()
		as, _ := strconv.ParseInt(r.Text(), 0, 0)
		a[i] = int(as)
		r.Scan()
		bs, _ := strconv.ParseInt(r.Text(), 0, 0)
		b[i] = int(bs)
		if b[i] > bmax {
			bin = i
			bmax = b[bin]
			btrue = true
		}
	}
	if bmax > 0 {
		btrue = true
	}
	if btrue == false {
		for l:=1; l<n; l++ {
			if a[l] > amax {
				amax = a[l]
				bin = l
			}
		}
	}
	total := a[bin]
	a[bin], a[n-1] = a[n-1], a[bin]
	b[bin], b[n-1] = b[n-1], b[bin]
	a = a[:n-1]
	b = b[:n-1]
	n -= 1
	counter := bmax
	bin2 := 0
	bmax2 := bmax
	bmax = 0
	btrue2 := false
	amax = 0
	if n == 0 {
		counter = 0
	}
	for counter != 0 {
		counter -= 1
		for j:=bmax2-1; j>=0; j-- {
			bmax = 0
			bin2 = 0
			amax = 0
			btrue2 = false
			for k:=0; k<n; k++ {
				if b[k] > bmax {
					bin2 = k
					bmax = b[bin2]
					amax = a[bin2]
					btrue2 = true
					if a[k] > amax {
						bin2 = k
						bmax = b[bin2]
						amax = a[bin2]
						btrue2 = true
					}
				}
			}
			if btrue2 == false {
				for m:=0; m<n; m++ {
					if a[m] > amax {
						amax = a[m]
						bin2 = m
					}
				}
			}
			if bin2 < n {
				total += a[bin2]
				a[bin2], a[n-1] = a[n-1], a[bin2]
				b[bin2], b[n-1] = b[n-1], b[bin2]
				a = a[:n-1]
				b = b[:n-1]
				n -= 1
			}
			if j + bmax <= n {
				j += bmax
			}
		}
		counter += bmax
		bmax2 = bmax + 1
	}
	fmt.Println(total)
}

package main

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

func main(){
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	b := make([]int, n)
	fmt.Scan(&a[0], &b[0])
	amax := a[0]
	bin := 0
	bmax := b[bin]
	btrue := false
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for i:=1; i<n; i++ {
		r.Scan()
		as, _ := strconv.ParseInt(r.Text(), 0, 0)
		a[i] = int(as)
		r.Scan()
		bs, _ := strconv.ParseInt(r.Text(), 0, 0)
		b[i] = int(bs)
		if b[i] > bmax {
			bin = i
			bmax = b[bin]
			amax = a[bin]
			btrue = true
			if a[i] > amax {
				bin = i
				bmax = b[bin]
				amax = a[bin]
				btrue = true
			}
		}
	}
	if bmax > 0 {
		btrue = true
	}
	if btrue == false {
		for l:=1; l<n; l++ {
			if a[l] > amax {
				amax = a[l]
				bin = l
			}
		}
	}
	total := a[bin]
	a[bin], a[n-1] = a[n-1], a[bin]
	b[bin], b[n-1] = b[n-1], b[bin]
	a = a[:n-1]
	b = b[:n-1]
	n -= 1
	counter := bmax
	bin2 := 0
	bmax2 := bmax
	bmax = 0
	btrue2 := false
	amax = 0
	if n == 0 {
		counter = 0
	}
	for counter != 0 {
		counter -= 1
		for j:=bmax2-1; j>=0; j-- {
			bmax = 0
			bin2 = 0
			amax = 0
			btrue2 = false
			for k:=0; k<n; k++ {
				if b[k] > bmax {
					bin2 = k
					bmax = b[bin2]
					amax = a[bin2]
					btrue2 = true
					if a[k] > amax {
						bin2 = k
						bmax = b[bin2]
						amax = a[bin2]
						btrue2 = true
					}
				}
			}
			if bmax > 0 {
				btrue2 = true
			}
			if btrue2 == false {
				for m:=0; m<n; m++ {
					if a[m] > amax {
						amax = a[m]
						bin2 = m
					}
				}
			}
			if bin2 < n {
				total += a[bin2]
				a[bin2], a[n-1] = a[n-1], a[bin2]
				b[bin2], b[n-1] = b[n-1], b[bin2]
				a = a[:n-1]
				b = b[:n-1]
				n -= 1
			}
			if j + bmax <= n {
				j += bmax
			}
		}
		if counter + bmax <= n {
			counter += bmax
		}
		if bmax <= n {
			bmax2 = bmax
		}
	}
	fmt.Println(total)
}

package main

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

func main(){
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	b := make([]int, n)
	fmt.Scan(&a[0], &b[0])
	amax := a[0]
	bin := 0
	bmax := b[bin]
	btrue := false
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for i:=1; i<n; i++ {
		r.Scan()
		as, _ := strconv.ParseInt(r.Text(), 0, 0)
		a[i] = int(as)
		r.Scan()
		bs, _ := strconv.ParseInt(r.Text(), 0, 0)
		b[i] = int(bs)
		if b[i] > bmax {
			bin = i
			bmax = b[bin]
			btrue = true
		}
	}
	if bmax > 0 {
		btrue = true
	}
	if btrue == false {
		for l:=1; l<n; l++ {
			if a[l] > amax {
				amax = a[l]
				bin = l
			}
		}
	}
	total := a[bin]
	a[bin], a[n-1] = a[n-1], a[bin]
	b[bin], b[n-1] = b[n-1], b[bin]
	a = a[:n-1]
	b = b[:n-1]
	n -= 1
	counter := bmax
	bin2 := 0
	bmax2 := bmax
	bmax = 0
	btrue2 := false
	amax = 0
	if n == 0 {
		counter = 0
	}
	for counter != 0 {
		counter -= 1
		for j:=bmax2-1; j>=0; j-- {
			bmax = 0
			bin2 = 0
			amax = 0
			btrue2 = false
			for k:=0; k<n; k++ {
				if b[k] >= bmax {
					bin2 = k
					bmax = b[bin2]
					amax = a[bin2]
					btrue2 = true
					if a[k] > amax {
						bin2 = k
						bmax = b[bin2]
						amax = a[bin2]
						btrue2 = true
					}
				}
			}
			if btrue2 == false {
				for m:=0; m<n; m++ {
					if a[m] > amax {
						amax = a[m]
						bin2 = m
					}
				}
			}
			if bin2 < n {
				total += a[bin2]
				a[bin2], a[n-1] = a[n-1], a[bin2]
				b[bin2], b[n-1] = b[n-1], b[bin2]
				a = a[:n-1]
				b = b[:n-1]
				n -= 1
			}
			if j + bmax <= n {
				j += bmax
			}
		}
		if counter + bmax <= n {
			counter += bmax
		}
		if bmax <= n {
			bmax2 = bmax
		}
	}
	fmt.Println(total)
}

package main

import "fmt"

func main(){
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	b := make([]int, n)
	fmt.Scan(&a[0], &b[0])
	amax := a[0]
	bin := 0
	bmax := b[bin]
	btrue := false
	for i:=1; i<n; i++ {
		fmt.Scan(&a[i], &b[i])
		if b[i] > bmax {
			bin = i
			bmax = b[bin]
			btrue = true
		}
	}
	if btrue == false {
		for l:=1; l<n; l++ {
			if a[l] > amax {
				amax = a[l]
				bin = l
			}
		}
	}
	total := a[bin]
	a[bin], a[n-1] = a[n-1], a[bin]
	b[bin], b[n-1] = b[n-1], b[bin]
	a = a[:n-1]
	b = b[:n-1]
	n -= 1
	counter := bmax
	bin2 := 0
	bmax2 := bmax
	bmax = 0
	btrue2 := false
	amax = 0
	for counter != 0 {
		counter -= 1
		for j:=0; j<bmax2; j++ {
			bmax = 0
			amax = 0
			btrue2 = false
			for k:=0; k<n; k++ {
				if b[k] > bmax {
					bin2 = k
					bmax = b[bin2]
					btrue2 = true
				}
			}
			if btrue2 == false {
				for m:=0; m<n; m++ {
					if a[m] > amax {
						amax = a[m]
						bin2 = m
					}
				}
			}
			total += a[bin2]
			a[bin2], a[n-1] = a[n-1], a[bin2]
			b[bin2], b[n-1] = b[n-1], b[bin2]
			a = a[:n-1]
			b = b[:n-1]
			n -= 1
		}
		counter += bmax
		bmax2 = bmax
	}
	fmt.Println(total)
}

package main

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

func main(){
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	b := make([]int, n)
	fmt.Scan(&a[0], &b[0])
	amax := a[0]
	bin := 0
	bmax := b[bin]
	btrue := false
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for i:=1; i<n; i++ {
		r.Scan()
		as, _ := strconv.ParseInt(r.Text(), 0, 0)
		a[i] = int(as)
		r.Scan()
		bs, _ := strconv.ParseInt(r.Text(), 0, 0)
		b[i] = int(bs)
		if b[i] > bmax {
			bin = i
			bmax = b[bin]
			btrue = true
		}
	}
	if bmax > 0 {
		btrue = true
	}
	if btrue == false {
		for l:=1; l<n; l++ {
			if a[l] > amax {
				amax = a[l]
				bin = l
			}
		}
	}
	total := a[bin]
	a[bin], a[n-1] = a[n-1], a[bin]
	b[bin], b[n-1] = b[n-1], b[bin]
	a = a[:n-1]
	b = b[:n-1]
	n -= 1
	counter := bmax
	bin2 := 0
	bmax2 := bmax
	bmax = 0
	btrue2 := false
	amax = 0
	if n == 0 {
		counter = 0
	}
	for counter != 0 {
		counter -= 1
		for j:=bmax2-1; j>=0; j-- {
			bmax = 0
			bin2 = 0
			amax = 0
			btrue2 = false
			for k:=0; k<n; k++ {
				if b[k] > bmax {
					bin2 = k
					bmax = b[bin2]
					amax = a[bin2]
					btrue2 = true
					if a[k] > amax {
						bin2 = k
						bmax = b[bin2]
						amax = a[bin2]
						btrue2 = true
					}
				}
			}
			if btrue2 == false {
				for m:=0; m<n; m++ {
					if a[m] > amax {
						amax = a[m]
						bin2 = m
					}
				}
			}
			if bin2 < n {
				total += a[bin2]
				a[bin2], a[n-1] = a[n-1], a[bin2]
				b[bin2], b[n-1] = b[n-1], b[bin2]
				a = a[:n-1]
				b = b[:n-1]
				n -= 1
			}
			if j + bmax <= n {
				j += bmax
			}
		}
		counter += bmax
		bmax2 = bmax
	}
	fmt.Println(total)
}

// 268B-Mic
package main

import (
    "fmt"
)

func main() {
    var n, ans int
    fmt.Scan(&n)
    if n == 1 {
        fmt.Print("1")
    }
    for x := 1; x < n; x++ {
        if x == 1 {
            ans = n + (n - 1)
        } else {
            ans += (n - x) * x
        }
    }
    fmt.Println(ans)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	counter, ans := 1, 0
	fmt.Scanf("%d\n", &n)
	cards := make([]int, 0, n)
	for i := 0;i < n;i ++ {
		var a, b int
		fmt.Scanf("%d %d", &a, &b)
		if b > 0 {
			ans += a
			counter += b
		} else {
			cards = append(cards, a)
		}
	}
	sort.Ints(cards)
	for i := 0;i < counter && i < len(cards);i ++ {
		ans += cards[len(cards) - i - 1]
	}
	fmt.Printf("%d", ans)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	counter, ans := 1, 0
	fmt.Scanf("%d\n", &n)
	cards := make([]int, 0, n)
	for i := 0;i < n;i ++ {
		var a, b int
		fmt.Scanf("%d %d\n", &a, &b)
		if b > 0 {
			ans += a
			counter += b
		} else {
			cards = append(cards, a)
		}
	}
	sort.Ints(cards)
	for i := 0;i < counter && i < len(cards);i ++ {
		ans += cards[len(cards) - i - 1]
	}
	fmt.Printf("%d", ans)
}

package main

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

func main(){
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	b := make([]int, n)
	fmt.Scan(&a[0], &b[0])
	amax := a[0]
	bin := 0
	bmax := b[bin]
	btrue := false
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for i:=1; i<n; i++ {
		r.Scan()
		as, _ := strconv.ParseInt(r.Text(), 0, 0)
		a[i] = int(as)
		r.Scan()
		bs, _ := strconv.ParseInt(r.Text(), 0, 0)
		b[i] = int(bs)
		if b[i] > bmax {
			bin = i
			bmax = b[bin]
			btrue = true
		}
	}
//	if bmax > 0 {
//		btrue = true
	//}
	if btrue == false {
		for l:=1; l<n; l++ {
			if a[l] > amax {
				amax = a[l]
				bin = l
			}
		}
	}
	total := a[bin]
	a[bin], a[n-1] = a[n-1], a[bin]
	b[bin], b[n-1] = b[n-1], b[bin]
	a = a[:n-1]
	b = b[:n-1]
	n -= 1
	counter := bmax
	bin2 := 0
	bmax2 := bmax
	bmax = 0
	btrue2 := false
	amax = 0
	if n == 0 {
		counter = 0
	}
	for counter != 0 {
		counter -= 1
		for j:=bmax2-1; j>=0; j-- {
			bmax = 0
			bin2 = 0
			amax = 0
			btrue2 = false
			for k:=0; k<n; k++ {
				if b[k] > bmax {
					bin2 = k
					bmax = b[bin2]
					amax = a[bin2]
					btrue2 = true
					if a[k] > amax {
						bin2 = k
						bmax = b[bin2]
						amax = a[bin2]
						btrue2 = true
					}
				}
			}
			if btrue2 == false {
				for m:=0; m<n; m++ {
					if a[m] > amax {
						amax = a[m]
						bin2 = m
					}
				}
			}
			if bin2 < n {
				total += a[bin2]
				a[bin2], a[n-1] = a[n-1], a[bin2]
				b[bin2], b[n-1] = b[n-1], b[bin2]
				a = a[:n-1]
				b = b[:n-1]
				n -= 1
			}
			if j + bmax <= n {
				j += bmax
			}
		}
		counter += bmax
		bmax2 = bmax
	}
	fmt.Println(total)
}


package main

import (
	"bufio"
	. "fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	solve := func(Case int) {
		var n, k int
		Fscan(in, &n, &k)
		for ;k>3;k-- {
			Fprint(out, "1 ")
			n--
		}
		if n&1 > 0 {
			Fprintln(out, 1, n/2, n/2)
		} else if n%4 == 0 {
			Fprintln(out, n/2, n/4, n/4)
		} else {
			n -= 2
			Fprintln(out, 2, n/2, n/2)
		}
	}

	var t int
	Fscan(in, &t)
	for Case := 1; Case <= t; Case++ {
		solve(Case)
	}

	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("有未读入的数据：\n" + _s)
	}
}

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for u:=1;u<=t;u++{
		var n, k int
		fmt.Fscan(in,&n,&k)
		now := n
		ans := []int{}
		for k>3{
			k--
			now--
			ans = append(ans,1)
		}
		if now%2==0{
			if ((now-2)/2)%2==0 {
				ans = append(ans, 2, (now-2)/2, (now-2)/2)
			}else{
				ans = append(ans,now/2,now/4,now/4)
			}
		}else{
			ans = append(ans,1,(now-1)/2,(now-1)/2)
		}
		for i:=0;i<len(ans);i++ {
			fmt.Fprintf(out,"%d ", ans[i])
		}
		fmt.Fprintln(out)
	}
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"strings"

	//"math"
	"os"
)

func run(r io.Reader, w io.Writer) {
	in := bufio.NewReader(r)
	out := bufio.NewWriter(w)
	defer out.Flush()

	var t int
	for Fscan(in, &t); t > 0; t-- {
		var n, k int
		Fscan(in, &n, &k)

		Fprint(out, strings.Repeat("1 ", k - 3))
		if (n - k + 3) & 0x1 == 1 {
			Fprintln(out, 1, (n - k + 2) / 2, (n - k + 2) / 2)
		} else {
			if (n - k + 3) & 3 == 0 {
				Fprintln(out, (n - k + 3) / 2, (n - k + 3) / 4, (n - k + 3) / 4)
			} else {
				Fprintln(out, 2, (n - k + 3) / 2 - 1, (n - k + 3) / 2 - 1)
			}
		}
	}
}

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

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

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

func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

package main

import "fmt"

func main() {
	var T, n, k int
	fmt.Scanf("%d\n", &T)
	for i := 1; i <= T; i++ {
		fmt.Scanf("%d%d\n", &n, &k)
		n = n - k + 3
		for i := 0; i < k-3; i++ {
			fmt.Printf("1 ")
		}
		if n%2 == 1 {
			fmt.Printf("%d %d %d\n", 1, n/2, n/2)
		} else {
			if (n/2)%2 == 0 {
				fmt.Printf("%d %d %d\n", n/4, n/4, n/2)
			} else {
				fmt.Printf("%d %d %d\n", 2, n/2-1, n/2-1)
			}
		}
	}
}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

func MIN(x, y int) int {
	if x > y {
		return y
	} else {
		return x
	}
}

func MKO(x, y int) int {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

func MAX(x, y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })
var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {
		var p int64
		var k int
		fmt.Fscan(input, &p)
		fmt.Fscan(input, &k)

		// STRING := make([]byte, 0)
		// fmt.Fscan(input, &STRING)
		n := p - int64(k) + 3

		if n%3 == 0 {
			j := int(n / 3)
			fmt.Println(j)
			fmt.Println(j)
			fmt.Println(j)

		} else {
			if n%2 == 1 {
				m := int(n / 2)
				fmt.Println(m)
				fmt.Println(m)
				fmt.Println(1)

			} else {
				m := int(n / 2)
				if m%2 == 1 {
					fmt.Println(m - 1)
					fmt.Println(m - 1)
					fmt.Println(2)
				} else {
					j := int(m / 2)
					fmt.Println(m)
					fmt.Println(j)
					fmt.Println(j)

				}
			}
		}
		for i := 1; i < k-2; i++ {
			fmt.Println(1)
		}

	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for u:=1;u<=t;u++{
		var n, k int
		fmt.Fscan(in,&n,&k)
		now := n
		ans := []int{}
		for k>3{
			k--
			now--
			ans = append(ans,1)
		}
		fmt.Println(now)
		if now%2==0{
			if ((now-2)/2)%2==0 {
				ans = append(ans, 2, (now-2)/2, (now-2)/2)
			}else{
				ans = append(ans,now/2,now/4,now/4)
			}
		}else{
			ans = append(ans,1,(now-1)/2,(now-1)/2)
		}
		for i:=0;i<len(ans);i++ {
			fmt.Fprintf(out,"%d ", ans[i])
		}
		fmt.Fprintln(out)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for u:=1;u<=t;u++{
		var n, k int
		fmt.Fscan(in,&n,&k)
		now := n
		ans := []int{}
		for k>3{
			k--
			now--
			ans = append(ans,1)
		}
		if now%2==0{
			ans = append(ans,2,(now-2)/2,(now-2)/2)
		}else{
			ans = append(ans,1,(now-1)/2,(now-1)/2)
		}
		for i:=0;i<len(ans);i++ {
			fmt.Fprintf(out,"%d ", ans[i])
		}
		fmt.Fprintln(out)
	}
}


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

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")
	}

}

// "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"
	"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))
}

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


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

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"
	"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, " "))
}