In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor.On the current level, the hero is facing $$$n$$$ caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave $$$i$$$, he will have to fight $$$k_i$$$ monsters in a row: first a monster with armor $$$a_{i, 1}$$$, then a monster with armor $$$a_{i, 2}$$$ and so on, finally, a monster with armor $$$a_{i, k_i}$$$.The hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order.Each time the hero beats a monster, the hero's power increases by $$$1$$$.Find the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of caves. The $$$i$$$-th of the next $$$n$$$ lines contains an integer $$$k_i$$$ ($$$1 \le k_i \le 10^5$$$) — the number of monsters in the $$$i$$$-th cave, followed by $$$k_i$$$ integers $$$a_{i, 1}, a_{i, 2}, \ldots, a_{i, k_i}$$$ ($$$1 \le a_{i, j} \le 10^9$$$) — armor levels of the monsters in cave $$$i$$$ in order the hero has to fight them. It is guaranteed that the sum of $$$k_i$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.

NoteIn the first test case, the hero has to beat a single monster with armor $$$42$$$, it's enough to have power $$$43$$$ to achieve that.In the second test case, the hero can pass the level with initial power $$$13$$$ as follows:   enter cave $$$2$$$:   beat a monster with armor $$$12$$$, power increases to $$$14$$$;  beat a monster with armor $$$11$$$, power increases to $$$15$$$;   enter cave $$$1$$$:   beat a monster with armor $$$10$$$, power increases to $$$16$$$;  beat a monster with armor $$$15$$$, power increases to $$$17$$$;  beat a monster with armor $$$8$$$, power increases to $$$18$$$.

//spend a lot of time on the problem
//and had an ugly solution, after seeing the tutorial
// I relized that my solution had some edge cases
//Looking tutorial always payoff
package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	tc := readInt(in)

	for i := 0; i < tc; i++ {
        testcase(in)
	}
}

func testcase(in *bufio.Reader) {
    //number of caves
    n := readInt(in)
    caves := make([][]int, n)
    bs := make([][2]int, n)
    for i := 0; i < n; i++ {
        arr := readArrInt(in)
        caves[i] = arr
        max := arr[1]
        for j := 2; j < len(arr); j++ {
            if arr[j] - (j-1) > max {
                max = arr[j] - (j-1)
            }
        }
        bs[i] = [2]int{max, arr[0]}
    }

    //sorting
    sort.Slice(bs, func(i, j int) bool {
        if bs[i][0] <= bs[j][0] {
            return true
        }
        return false
    })

    acc := 0
    max := bs[0][0]
    for j := 0; j < n; j++ {
        if bs[j][0] - acc > max {
            max = bs[j][0] - acc
        }
        acc += bs[j][1]
    }
    fmt.Println(max+1)
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

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

package main

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

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

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

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

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

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

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

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

func MAXX(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 GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

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

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

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

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)
		type Needing struct {
			needing         int
			numberofmonster int
		}
		NEEDIGNG := make([]Needing, n)
		for i := 1; i <= n; i++ {
			var k int
			fmt.Fscan(input, &k)
			ARR := make([]int, k)
			var needing int
			for j := 0; j < k; j++ {
				fmt.Fscan(input, &ARR[j])
				q := ARR[j] - j + 1
				if q > needing {
					needing = q
				}

			}
			NEEDIGNG[i-1].numberofmonster = k
			NEEDIGNG[i-1].needing = needing

		}

		sort.Slice(NEEDIGNG, func(i, j int) bool {
			return NEEDIGNG[i].needing > NEEDIGNG[j].needing
		})

		var AnsWer int
		AnsWer = NEEDIGNG[0].needing
		for i := 1; i < n; i++ {
			q := NEEDIGNG[i-1].needing - NEEDIGNG[i].numberofmonster
			A := MAXX(q, NEEDIGNG[i].needing)
			NEEDIGNG[i].needing = A
			if A < AnsWer {
				AnsWer = A
			}
		}
		fmt.Println(AnsWer)

	}
}

package main

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

var _, _, _ = main, rw, do

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()
	rw(r, w)
}

func rw(r io.Reader, w io.Writer) {
	var t int
	var n int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		fmt.Fscan(r, &n)
		a := make([][]int, n)
		for i := 0; i < n; i++ {
			var k int
			fmt.Fscan(r, &k)
			a[i] = make([]int, k)
			for j := 0; j < k; j++ {
				fmt.Fscan(r, &a[i][j])
			}
		}
		w1 := do(a)
		fmt.Fprintln(w, w1)
	}
}

func minPower(a []cave) int {
	acc := make([]int, len(a))
	for i := 1; i < len(a); i++ {
		acc[i] = acc[i-1] + a[i-1].add
	}
	min, cur := 0, 0
	for i := range a {
		if cur < a[i].min {
			cur = a[i].min
			min = cur - acc[i]
		}
		cur += a[i].add
	}
	return min
}

type cave struct {
	min int
	add int
}

func do(a [][]int) int {
	b := make([]cave, len(a))
	for i := 0; i < len(a); i++ {
		c := make([]cave, len(a[i]))
		for j := range c {
			c[j].min = a[i][j] + 1
			c[j].add = 1
		}
		b[i].min = minPower(c)
		b[i].add = len(a[i])
	}
	sort.Slice(b, func(i, j int) bool {
		if b[i].min == b[j].min {
			return b[i].add > b[j].add
		}
		return b[i].min < b[j].min
	})
	return minPower(b)
}

package main

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

type pair struct {
	c int
	b int
}

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

	var T, n int

	fmt.Fscanf(r, "%d\n", &T)

	for t := 0; t < T; t++ {
		fmt.Fscanf(r, "%d\n", &n)

		arr := make([][]int, n)

		for i := 0; i < n; i++ {
			var k, v int
			fmt.Fscanf(r, "%d", &k)

			for j := 0; j < k; j++ {
				fmt.Fscanf(r, "%d", &v)
				arr[i] = append(arr[i], v)
			}
			fmt.Fscanf(r, "\n")
		}

		c := make([]pair, 0)
		for i := 0; i < n; i++ {
			r := 0
			for j := 0; j < len(arr[i]); j++ {
				if arr[i][j]-j > r {
					r = arr[i][j] - j
				}
			}

			c = append(c, pair{r, len(arr[i])})
		}

		sort.Slice(c, func(i, j int) bool {
			return c[i].c < c[j].c
		})

		res := sort.Search(1000000009, func(i int) bool {
			for _, v := range c {
				if i <= v.c {
					return false
				}
				i += v.b
			}

			return true
		})

		fmt.Println(res)
	}
}

package main

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

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

	var T, n, m, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		type pair struct{ need, add int }
		a := make([]pair, n)
		for i := range a {
			Fscan(in, &m)
			mx := 0
			for j := 0; j < m; j++ {
				Fscan(in, &v)
				mx = max(mx, v-j+1)
			}
			a[i] = pair{mx, m}
		}
		sort.Slice(a, func(i, j int) bool { return a[i].need < a[j].need })
		ans, s := 0, 0
		for _, p := range a {
			ans = max(ans, p.need-s)
			s += p.add
		}
		Fprintln(out, ans)
	}
}

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

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

package main

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

var (
	out = bufio.NewWriter(os.Stdout)
	in  = bufio.NewReader(os.Stdin)
	arr []string
)

func main() {
	var test int
	fmt.Fscan(in, &test)
	for i := 0; i < test; i++ {
		solve()
	}

}

func solve() {
	var n int
	fmt.Fscan(in, &n)
	var matrix = make([][]int64, n)
	for i := 0; i < n; i++ {
		var numberOfMonster int64
		fmt.Fscan(in, &numberOfMonster)
		t := make([]int64, numberOfMonster)
		for j := 0; j < len(t); j++ {
			fmt.Fscan(in, &t[j])
		}
		matrix[i] = t
	}
	var pairs []pair
	//at every point calc the min required for that row and the number of elements in the row
	for i := 0; i < len(matrix); i++ {
		currentRow := matrix[i]
		var currentMin = currentRow[0] + 1
		for j := 1; j < len(currentRow); j++ {
			if currentRow[j] >= currentMin+int64(j) {
				required := currentRow[j] + 1 - (currentMin + int64(j))
				currentMin += required
			}
		}
		p1 := pair{
			a: currentMin,
			b: int64(len(currentRow)),
		}
		pairs = append(pairs, p1)
	}
	sortPair(pairs)
	//the idea is calc the min and the max power required and then do the binary search between the powers and find out the answer
	maxpowerRequired := pairs[len(pairs)-1].a
	minPowerRequired := pairs[0].a
	var ans int64 = math.MaxInt64
	for maxpowerRequired >= minPowerRequired {
		mid := (maxpowerRequired + minPowerRequired) / 2
		currentPower := mid
		canFight := true
		for i := 0; i < len(pairs); i++ {
			if pairs[i].a <= currentPower {
				currentPower += pairs[i].b
			} else {
				canFight = false
				break
			}
		}
		if canFight {
			ans = mid
			maxpowerRequired = mid - 1
		} else {
			minPowerRequired = mid + 1
		}
	}
	fmt.Println(ans)

}

//x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-TEMPLATE_STARTING-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-

type pair struct {
	a int64
	b int64
}

func sortPair(pairs []pair) {
	sort.Slice(pairs, func(i, j int) bool {
		return pairs[i].a < pairs[j].a
	})
}
func min(a int64, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func printArray(arr []int) {
	for i := 1; i < len(arr); i++ {
		fmt.Print(arr[i], " ")
	}
	fmt.Println()
}

type runeSort []rune

func (r runeSort) Len() int           { return len(r) }
func (r runeSort) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }
func (r runeSort) Less(i, j int) bool { return r[i] < r[j] }

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	tc := readInt(in)

	for i := 0; i < tc; i++ {
        n := readInt(in)
        arr := readArrInt64(in)

        max := arr[0]
        total := arr[0]
        for j := 1; j < n; j++ {
            total += arr[j]
            if arr[j] > max {
                max = arr[j]
            }
        }
        total -= max
        fmt.Println(float64(total)/float64(n-1)+float64(max))
	}
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

//spend a lot of time on the problem
//and had an ugly solution, after seeing the tutorial
// I relized that my solution had some edge cases
//Looking tutorial always payoff
package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	tc := readInt(in)

	for i := 0; i < tc; i++ {
        testcase(in)
	}
}

func testcase(in *bufio.Reader) {
    //number of caves
    n := readInt(in)
    caves := make([][]int, n)
    bs := make([][2]int, n)
    for i := 0; i < n; i++ {
        arr := readArrInt(in)
        caves[i] = arr
        max := arr[1]
        for j := 2; j < len(arr) - 1; j++ {
            if arr[j] - (j-1) > max {
                max = arr[j] - (j-1)
            }
        }
        bs[i] = [2]int{max, arr[0]}
    }

    //sorting
    sort.Slice(bs, func(i, j int) bool {
        if bs[i][0] < bs[j][0] {
            return true
        }
        return false
    })

    acc := 0
    max := bs[0][0]
    for j := 1; j < n; j++ {
        acc += bs[j-1][1]
        if bs[j][0] - acc > max {
            max = bs[j][0] - acc
        }
    }
    fmt.Println(max + 1)
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

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

//spend a lot of time on the problem
//and had an ugly solution, after seeing the tutorial
// I relized that my solution had some edge cases
//Looking tutorial always payoff
package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	tc := readInt(in)

	for i := 0; i < tc; i++ {
        testcase(in)
	}
}

func testcase(in *bufio.Reader) {
    //number of caves
    n := readInt(in)
    caves := make([][]int, n)
    bs := make([]int, n)
    for i := 0; i < n; i++ {
        arr := readArrInt(in)
        caves[i] = arr
        max := arr[1]
        for j := 2; j < len(arr) - 1; j++ {
            if arr[j] - (j-1) > max {
                max = arr[j] - (j-1)
            }
        }
        bs[i] = max
    }

    sort.Ints(bs)
    acc := 0
    max := bs[0]
    for j := 1; j < n; j++ {
        acc += caves[j-1][0]
        if bs[j] - acc > max {
            max = bs[j] - acc
        }
    }
    fmt.Println(max + 1)
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	tc := readInt(in)

	for i := 0; i < tc; i++ {
        testcase(in)
	}
}

func testcase(in *bufio.Reader) {
    //number of caves
    n := readInt(in)
    caves := make([][]int, n)
    armorCaves := make([]int, n)
    for i := 0; i < n; i++ {
        //first element is ki
        arr := readArrInt(in)
        caves[i] = arr
        armorCaves[i] = arr[1] + 1
        for j := 2; j < arr[0]; j++ {
            diff := arr[j] - arr[j-1] - 1
            if diff > 0 {
                armorCaves[i] += diff
            }
        }
    }

    //constructing graph
    graph := make([][]int, n)
    //construct graph
    for i, marmor := range armorCaves {
        for j, m := range armorCaves {
            if i != j && marmor + caves[i][0] >= m {
                graph[i] = append(graph[i], j)
            }
        }
    }
    allowed := make([]int, n)
    for i := range graph {
        visited := make([]int, len(graph))
        dfs(graph, visited, i)
        allowed[i] = 1
        for _, v := range visited {
            if v == 0 {
                allowed[i] = 0
                break
            }
        }
    }

    min := math.MaxInt8
    if len(armorCaves) == 1 {
        fmt.Println(armorCaves[0])
        return
    }
    for _, i := range allowed {
        if i == 1 && armorCaves[i] < min {
            min = armorCaves[i]
        }
    }
    fmt.Println(min)
}

//WHITE: NOT FOUND YET
//GRAY: BEEN PROCEESS
//BLACK: VISITED
func dfs(graph [][]int, visited []int, start int) {
    visited[start] = 1
    for _, node := range graph[start] {
        if visited[node] == 0 {
            dfs(graph, visited, node)
        }
    }
    visited[start] = 2
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

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

package main

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

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

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

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

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

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

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

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

func MAXX(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 GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

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

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

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

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)
		type Needing struct {
			needing         int
			numberofmonster int
		}
		NEEDIGNG := make([]Needing, n)
		for i := 1; i <= n; i++ {
			var k int
			fmt.Fscan(input, &k)
			ARR := make([]int, k)
			var needing int
			for j := 0; j < k; j++ {
				fmt.Fscan(input, &ARR[j])
				q := ARR[j] - j + 1
				if q > needing {
					needing = q
				}

			}
			NEEDIGNG[i-1].numberofmonster = k
			NEEDIGNG[i-1].needing = needing

		}

		sort.Slice(NEEDIGNG, func(i, j int) bool {
			return NEEDIGNG[i].needing > NEEDIGNG[j].needing
		})

		var AnsWer int
		AnsWer = NEEDIGNG[0].needing
		for i := 1; i < n; i++ {
			q := NEEDIGNG[i-1].needing - NEEDIGNG[i].numberofmonster
			A := MAXX(q, NEEDIGNG[i].needing)
			if A < AnsWer {
				AnsWer = A
			}
		}
		fmt.Println(AnsWer)

	}
}

package main

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

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

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

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

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

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

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

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

func MAXX(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 GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

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

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

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

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)
		type Needing struct {
			needing         int
			numberofmonster int
		}
		NEEDIGNG := make([]Needing, n)
		for i := 1; i <= n; i++ {
			var k int
			fmt.Fscan(input, &k)
			ARR := make([]int, k)
			var needing int
			for j := 0; j < k; j++ {
				fmt.Fscan(input, &ARR[j])
				q := ARR[j] - j + 1
				if q > needing {
					needing = q
				}

			}
			NEEDIGNG[i-1].numberofmonster = k
			NEEDIGNG[i-1].needing = needing

		}

		sort.Slice(NEEDIGNG, func(i, j int) bool {
			return NEEDIGNG[i].needing > NEEDIGNG[j].needing
		})

		var AnsWer int
		AnsWer = NEEDIGNG[0].needing
		for i := 1; i < n; i++ {
			if NEEDIGNG[i].needing+NEEDIGNG[i].numberofmonster >= NEEDIGNG[i-1].needing {
				AnsWer = NEEDIGNG[i].needing
			} else {
				break
			}
		}
		fmt.Println(AnsWer)

	}
}

package main

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

var _, _, _ = main, rw, do

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()
	rw(r, w)
}

func rw(r io.Reader, w io.Writer) {
	var t int
	var n int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		fmt.Fscan(r, &n)
		a := make([][]int, n)
		for i := 0; i < n; i++ {
			var k int
			fmt.Fscan(r, &k)
			a[i] = make([]int, k)
			for j := 0; j < k; j++ {
				fmt.Fscan(r, &a[i][j])
			}
		}
		w1 := do(a)
		fmt.Fprintln(w, w1)
	}
}

func minPower(a []int) int {
	min, cur := 0, 0
	for i := range a {
		if cur <= a[i] {
			cur = a[i] + 2
			min = cur - i - 1
		} else {
			cur++
		}
	}
	return min
}

type cave struct {
	min int
	i   int
	add int
	acc int
}

func do(a [][]int) int {
	b := make([]cave, len(a))
	for i := 0; i < len(a); i++ {
		b[i].i = i
		b[i].min = minPower(a[i])
		b[i].add = len(a[i])
		b[i].acc = len(a[i])
	}
	sort.Slice(b, func(i, j int) bool {
		if b[i].min == b[j].min {
			return b[i].add > b[j].add
		}
		return b[i].min < b[j].min
	})
	for i := 1; i < len(b); i++ {
		b[i].acc = b[i-1].acc + b[i].add
	}
	min, cur := 0, 0
	for i := range b {
		if cur >= b[i].min {
			cur += b[i].add
		} else {
			min = b[i].min
			cur = min + b[i].acc
		}
	}
	return min
}

package main

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

var _, _, _ = main, rw, do

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()
	rw(r, w)
}

func rw(r io.Reader, w io.Writer) {
	var t int
	var n int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		fmt.Fscan(r, &n)
		a := make([][]int, n)
		for i := 0; i < n; i++ {
			var k int
			fmt.Fscan(r, &k)
			a[i] = make([]int, k)
			for j := 0; j < k; j++ {
				fmt.Fscan(r, &a[i][j])
			}
		}
		w1 := do(a)
		fmt.Fprintln(w, w1)
	}
}

func minPower(a []int) int {
	if len(a) == 0 {
		return 0
	}
	b := a[0] + 1
	c := b
	for j := 1; j < len(a); j++ {
		if c <= a[j] {
			c = a[j] + 1
			b = c - j
		} else {
			c++
		}
	}
	return b
}

func do(a [][]int) int {
	b := make([]int, len(a))
	for i := 0; i < len(a); i++ {
		b[i] = minPower(a[i])
	}
	c := make([]int, len(a))
	for i := range a {
		c[i] = i
	}
	sort.Slice(c, func(i, j int) bool {
		if b[c[i]] == b[c[j]] {
			return len(a[c[i]]) > len(a[c[j]])
		}
		return b[c[i]] < b[c[j]]
	})
	d := make([]int, len(a))
	for i, j := range c {
		d[i] = len(a[j])
	}
	for i := 1; i < len(d); i++ {
		d[i] += d[i-1]
	}
	min, cur := 0, 0
	for _, i := range c {
		if cur >= b[i] {
			cur += len(a[i])
		} else {
			min = b[i]
			cur = min + d[i]
		}
	}
	return min
}

package main

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

type pair struct {
	c int
	b int
}

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

	var T, n int

	fmt.Fscanf(r, "%d\n", &T)

	for t := 0; t < T; t++ {
		fmt.Fscanf(r, "%d\n", &n)

		arr := make([][]int, n)

		for i := 0; i < n; i++ {
			var k, v int
			fmt.Fscanf(r, "%d", &k)

			for j := 0; j < k; j++ {
				fmt.Fscanf(r, "%d", &v)
				arr[i] = append(arr[i], v)
			}
			fmt.Fscanf(r, "\n")
		}

		c := make([]pair, 0)
		for i := 0; i < n; i++ {
			r := 0
			for j := 0; j < len(arr[i]); j++ {
				if arr[i][j]-j > r {
					r = arr[i][j] - j
				}
			}

			c = append(c, pair{r, len(arr[i])})
		}

		sort.Slice(c, func(i, j int) bool {
			return c[i].c < c[j].c
		})

		res := sort.Search(1000000000, func(i int) bool {
			for _, v := range c {
				if i <= v.c {
					return false
				}
				i += v.b
			}

			return true
		})

		fmt.Println(res)
	}
}


You are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root is vertex $$$1$$$. There is also a string $$$s$$$ denoting the color of each vertex: if $$$s_i = \texttt{B}$$$, then vertex $$$i$$$ is black, and if $$$s_i = \texttt{W}$$$, then vertex $$$i$$$ is white.A subtree of the tree is called balanced if the number of white vertices equals the number of black vertices. Count the number of balanced subtrees.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. In this problem, all trees have root $$$1$$$.The tree is specified by an array of parents $$$a_2, \dots, a_n$$$ containing $$$n-1$$$ numbers: $$$a_i$$$ is the parent of the vertex with the number $$$i$$$ for all $$$i = 2, \dots, n$$$. The parent of a vertex $$$u$$$ is a vertex that is the next vertex on a simple path from $$$u$$$ to the root.The subtree of a vertex $$$u$$$ is the set of all vertices that pass through $$$u$$$ on a simple path to the root. For example, in the picture below, $$$7$$$ is in the subtree of $$$3$$$ because the simple path $$$7 \to 5 \to 3 \to 1$$$ passes through $$$3$$$. Note that a vertex is included in its subtree, and the subtree of the root is the entire tree.  The picture shows the tree for $$$n=7$$$, $$$a=[1,1,2,3,3,5]$$$, and $$$s=\texttt{WBBWWBW}$$$. The subtree at the vertex $$$3$$$ is balanced.

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 4000$$$) — the number of vertices in the tree. The second line of each test case contains $$$n-1$$$ integers $$$a_2, \dots, a_n$$$ ($$$1 \le a_i < i$$$) — the parents of the vertices $$$2, \dots, n$$$. The third line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of the characters $$$\texttt{B}$$$ and $$$\texttt{W}$$$ — the coloring of the tree. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of balanced subtrees.

NoteThe first test case is pictured in the statement. Only the subtrees at vertices $$$2$$$ and $$$3$$$ are balanced.In the second test case, only the subtree at vertex $$$1$$$ is balanced.In the third test case, only the subtrees at vertices $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ are balanced.

package main

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

type cmap struct {
	b int
	w int
}

func dfs(r int, adj [][]int, vis []bool, dp []cmap) {
	vis[r] = true
	for _, v := range adj[r] {
		if ! vis[v] {
			dfs(v, adj, vis, dp)
			dp[r].b += dp[v].b
			dp[r].w += dp[v].w
		}
	}
}

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, p, cnt int
		fmt.Fscan(r, &n)

		adj := make([][]int, n)
		for i := 2; i <= n; i++ {
			fmt.Fscan(r, &p)
			adj[p-1] = append(adj[p-1], i-1)
		}

		var col string
		fmt.Fscan(r, &col)
		dp := make([]cmap, n)
		for i, v := range col {
			if v == 'B' { dp[i].b++ }
			if v == 'W' { dp[i].w++ }
		}

		vis := make([]bool, n)
		dfs(0, adj, vis, dp)

		for _, cm := range dp {
			if cm.b == cm.w { cnt++ }
		}

		fmt.Fprintln(w, cnt)
	}

}

package main

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

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

func main() {
	defer writer.Flush()

	var T int
	fmt.Fscan(reader, &T)

	for test := 1; test <= T; test++ {
		var n int
		fmt.Fscan(reader, &n)

		var adj [][]int
		adj = make([][]int, n+1)

		for i := 2; i <= n; i++ {
			var u int
			fmt.Fscan(reader, &u)
			adj[u] = append(adj[u], i)
		}

		var colors string
		fmt.Fscan(reader, &colors)

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

		var dfs func(int)
		dfs = func(u int) {
			if colors[u-1] == 'W' {
				white[u] = 1
			}
			if colors[u-1] == 'B' {
				black[u] = 1
			}
			for _, v := range adj[u] {
				dfs(v)
				white[u] += white[v]
				black[u] += black[v]
			}
		}
		dfs(1)

		ans := 0
		for u := 1; u <= n; u++ {
			if black[u] == white[u] {
				ans += 1
			}
		}

		fmt.Fprintf(writer, "%d\n", ans)
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

type Tuple struct {
	w   int
	b   int
	tot int
}

func dfs(g [][]int, visited []bool, color *string, v int) *Tuple {
	tuple := &Tuple{}
	if (*color)[v-1] == 'B' {
		tuple.b = 1
	} else {
		tuple.w = 1
	}
	visited[v] = true
	// fmt.Printf("on %v\n", v)
	for _, u := range g[v] {
		if !visited[u] {
			// fmt.Printf("\tvisiting %v\n", u)
			child_tuple := dfs(g, visited, color, u)
			tuple.tot += child_tuple.tot
			tuple.b += child_tuple.b
			tuple.w += child_tuple.w
		} // else {
		// 	fmt.Printf("\t%v was visited\n", u)
		// }
	}
	if tuple.b == tuple.w {
		tuple.tot++
	}
	return tuple
}

func readNumbers() []int {
	s, _ := reader.ReadString('\n')
	s = strings.ReplaceAll(s, "\n", "")
	s = strings.ReplaceAll(s, "\r", "")
	splitted := strings.Split(s, " ")
	// fmt.Printf("splitted[0] is \"%+v\"\n", splitted[0])
	nums := make([]int, len(splitted))
	for i, str := range splitted {
		nums[i], _ = strconv.Atoi(str)
	}
	return nums
}

func main() {
	t := readNumbers()[0]
	parent := make([]int, 4001)
	for i := 0; i < t; i++ {
		n := readNumbers()[0]
		g := make([][]int, n+1)
		copy(parent[2:], readNumbers())
		for j := 2; j <= n; j++ {
			g[parent[j]] = append(g[parent[j]], j)
		}
		color, _ := reader.ReadString('\n')
		color = strings.ReplaceAll(color, "\n", "")
		color = strings.ReplaceAll(color, "\r", "")
		// fmt.Printf("g: %+v, color: %v\n", g, color)
		fmt.Println(dfs(g, make([]bool, n+1), &color, 1).tot)
	}
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		arr := make([]int, n)
		for i := 0; i < n-1; i++ {
			fmt.Fscan(in, &arr[i+1])
		}

		var s string
		fmt.Fscan(in, &s)
		g := make([]int, n+1)
		if s[0] == 'W' {
			g[1] = 1
		} else {
			g[1] = -1
		}

		for i := 0; i < n-1; i++ {
			var v int
			if s[i+1] == 'W' {
				v = 1
			} else {
				v = -1
			}

			g[i+2] = v
			p := arr[i+1]
			for p > 0 {
				g[p] += v
				p = arr[p-1]
			}
		}

		var tot int
		for i := 1; i < n; i++ {
			if g[i] == 0 {
				tot++
			}
		}
		fmt.Fprintln(out, tot)
	}
}

package main

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

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

func g1676(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T int
	var n int
	var x int
	var y string

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)

		row := make([]int, n)
		row[0] = 0
		for i := 1; i < n; i++ {
			Fscan(in, &x)
			row[i] = x-1
		}
		Fscan(in, &y)
		b := make([]bool, n)
		for i, v := range y {
			if v == 'B' {
				b[i] = true
			}
		}

		next := make([][]int, n)
		for i := 1; i < n; i++ {
			v := row[i]
			next[v] = append(next[v], i)
		}

		ans := 0
		var dfs func(i int) (int , int)
		dfs = func(i int) (int, int){
			ww, bb := 0, 0
			for _, v := range next[i] {
				vw, vb := dfs(v)
				ww += vw
				bb += vb
			}
			if b[i] {
				bb++
			} else {
				ww++
			}
			if ww == bb {
				ans++
			}
			return ww, bb
		}

		dfs(0)

		Fprintln(out, ans)
	}
}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func slove() {
	var n int
	fmt.Fscan(r, &n)
	nums := make([]int, n)
	for i:=1;i<n;i++ {
		fmt.Fscan(r, &nums[i])
		nums[i]--
	}
	child := make([][]int, n)
	for i := range child {
		child[i] = make([]int, 0)
	}
	for i := range nums {
		if i == 0 {
			continue
		}
		child[nums[i]] = append(child[nums[i]], i)
	}
	var s string
	ans := 0
	fmt.Fscan(r, &s)
	var dfs func(root int) (int, int)
	dfs = func(root int) (int, int) {
		white, black := 0, 0
		if s[root] == 'W' {
			white++
		} else {
			black++
		}
		for i := range child[root] {
			w, b := dfs(child[root][i])
			white += w
			black += b
		}
		if white == black {
			ans++
		}
		return white, black
	}
	dfs(0)
	fmt.Fprintln(w, ans)
}

func main() {
	defer w.Flush()
	var n int
	fmt.Fscan(r, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}

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(curCase int) {
		var n ,ans int
		Fscan(in, &n)
		g := make([][]int, n+1)
		for i := 2; i <= n; i++ {
			var pa int
			Fscan(in, &pa)
			g[pa] = append(g[pa], i)
		}
		var s string
		Fscan(in, &s)
		var dfs func(v, fa int) (int,int)
		dfs = func(v, fa int)  (b int,w int){
			if s[v-1] == 'W' {
				w++
			} else {
				b++
			}
			for _, c := range g[v] {
				if c != fa {

					bb,ww := dfs(c, v)
					b+=bb
					w+=ww
				}
			}
			if b == w {
				ans++
			}
			return
		}
		dfs(1, -1)
		Fprintln(out, ans)
	}

	cases := 1
	Fscan(in, &cases)
	for curCase := 1; curCase <= cases; curCase++ {
		solve(curCase)
	}

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

}

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


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Beauty of array is the maximum sum of some consecutive subarray of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0.You may choose at most one consecutive subarray of $$$a$$$ and multiply all values contained in this subarray by $$$x$$$. You want to maximize the beauty of array after applying at most one such operation.

The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 3 \cdot 10^5, -100 \le x \le 100$$$) — the length of array $$$a$$$ and the integer $$$x$$$ respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the array $$$a$$$.

Print one integer — the maximum possible beauty of array $$$a$$$ after multiplying all values belonging to some consecutive subarray $$$x$$$.

NoteIn the first test case we need to multiply the subarray [-2, 1, -6], and the array becomes [-3, 8, 4, -2, 12] with beauty 22 ([-3, 8, 4, -2, 12]).In the second test case we don't need to multiply any subarray at all.In the third test case no matter which subarray we multiply, the beauty of array will be equal to 0.

package main

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

func solveAll(jam Jam) {
	s, l, ui, f, d, p, pf := jam.Str, jam.Long, jam.Int, jam.Float, jam.D, jam.P, jam.PF

	n, x := l(), l()
	a := make([]int64, n, n)
	var b [300001][3][3]int64

	for i := int64(0); i < n; i++ {
		a[i] = l()
	}
	b[0][0][0] = 0

	for i := int64(0); i <= n; i++ {
		for j := int64(0); j < 3; j++ {
			for k := int64(0); k < 3; k++ {
				if k < 2 {
					b[i][j][k+1] =
						max(
							b[i][j][k+1],
							b[i][j][k],
						)
				}
				if j < 2 {
					b[i][j+1][k] =
						max(
							b[i][j+1][k],
							b[i][j][k],
						)
				}
				if i < n {
					b[i+1][j][k] =
						max(
							b[i+1][j][k],
							b[i][j][k]+t(j == 1, a[i], 0)*t(k == 1, x, 1),
						)
				}
			}
		}
	}

	pf("%d\n", b[n][2][2])

	if false { d("%v", []interface{}{s, l, ui, f, d, p, pf}) }
}

func t(b bool, t, f int64) int64 {
	if b {
		return t
	}
	return f
}
func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

func main() {
	jam, closeFunc := JamNew()
	defer closeFunc()
	solveAll(jam)
}

type Jam interface {
	Scanner() *bufio.Scanner
	Writer() *bufio.Writer
	Close()

	Str() string
	Long() int64
	Int() uint32
	Float() float64

	D(format string, values ...interface{})
	P(format string, values ...interface{})
	PF(format string, values ...interface{})
}

func JamNew() (Jam, func()) {
	if len(os.Args) > 1 {
		panic("running with input file path is not supported")
	}

	var scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)

	var writer = bufio.NewWriterSize(os.Stdout, 1024*1024)
	jam := &jam{scanner, writer}
	return jam, jam.Close
}

type jam struct {
	sc *bufio.Scanner
	wr *bufio.Writer
}

func (j *jam) Close() {
	if err := j.wr.Flush(); err != nil {
		panic(err)
	}
}

func (j *jam) Scanner() *bufio.Scanner {
	return j.sc
}

func (j *jam) Writer() *bufio.Writer {
	return j.wr
}

func (j *jam) Str() string {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	return j.sc.Text()
}

func (j *jam) Long() int64 {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	res, err := strconv.ParseInt(j.sc.Text(), 10, 64)
	if err != nil {
		panic(err)
	}

	return res
}

func (j *jam) Int() uint32 {
	return uint32(j.Long())
}

func (j *jam) Float() float64 {
	j.sc.Scan()
	res, err := strconv.ParseFloat(j.sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

func (j *jam) D(format string, values ...interface{}) {
	_ /*bytesWritten*/, err := fmt.Fprintf(os.Stderr, format, values...)
	if err != nil {
		panic(err)
	}
}

func (j *jam) P(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
}

func (j *jam) PF(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
	if err = j.wr.Flush(); err != nil {
		panic(err)
	}
}

package main

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

func main() {
	r := bufio.NewReader(os.Stdin)

	var n int
	var x int64
	fmt.Fscanf(r, "%d %d\n", &n, &x)

	a := make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d", &a[i])
	}

	fmt.Println(maxSubArray(a, x))
}

func maxSubArray(a []int64, x int64) int64 {
	dp1 := make([]int64, len(a))
	dp2 := make([]int64, len(a))
	dp3 := make([]int64, len(a))

	for i, e := range a {
		dp1[i] = e
		if i > 0 {
			dp1[i] = max(dp1[i], e+dp1[i-1])
		}
	}

	for i, e := range a {
		dp2[i] = e * x
		if i > 0 {
			dp2[i] = max(dp2[i], e*x+max(dp1[i-1], dp2[i-1]))
		}
	}

	for i := len(a) - 1; i >= 0; i-- {
		dp3[i] = a[i]
		if i+1 < len(a) {
			dp3[i] = max(dp3[i], a[i]+dp3[i+1])
		}
	}

	ans := max(0, max(findMax(dp1), findMax(dp2)))
	for i := 0; i < len(a)-1; i++ {
		ans = max(ans, dp2[i]+dp3[i+1])
	}

	return ans
}

func findMax(a []int64) int64 {
	if len(a) == 0 {
		return 0
	}

	ret := a[0]
	for _, e := range a {
		ret = max(ret, e)
	}
	return ret
}

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

package main

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

func main() {
	r := bufio.NewReader(os.Stdin)

	var n int
	var x int64
	fmt.Fscanf(r, "%d %d\n", &n, &x)

	a := make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d", &a[i])
	}

	fmt.Println(maxSubArray(a, x))
}

func maxSubArray(a []int64, x int64) int64 {
	dp1 := make([]int64, len(a))
	dp2 := make([]int64, len(a))
	dp3 := make([]int64, len(a))

	for i, e := range a {
		dp1[i] = e
		if i > 0 {
			dp1[i] = max(dp1[i], e+dp1[i-1])
		}
	}

	for i, e := range a {
		dp2[i] = e * x
		if i > 0 {
			dp2[i] = max(dp2[i], e*x+max(dp1[i-1], dp2[i-1]))
		}
	}

	for i, e := range a {
		dp3[i] = e
		if i > 0 {
			dp3[i] = max(dp2[i], e+max(dp2[i-1], dp3[i-1]))
		} else {
			dp3[0] = -1e16
		}
	}

	ans := max(max(0, findMax(dp1)), max(findMax(dp2), findMax(dp3)))

	return ans
}

func findMax(a []int64) int64 {
	if len(a) == 0 {
		return 0
	}

	ret := a[0]
	for _, e := range a {
		ret = max(ret, e)
	}
	return ret
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1155D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}
	var n, x, v, s int64
	Fscan(in, &n, &x)
	dp := [3]int64{}
	for ; n > 0; n-- {
		Fscan(in, &v)
		dp[0] = max(0, dp[0]+v)
		dp[1] = max(dp[0], dp[1]+v*x)
		dp[2] = max(dp[1], dp[2]+v)
		s = max(s, dp[2])
	}
	Fprint(out, s)
}

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


You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.

The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.

Print the minimum non-zero element before each operation in a new line.

NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.

package main

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

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(){
	defer writer.Flush()
	var a[100005]int
	var n,k,i int
	scanf("%d %d\n", &n, &k)
	a[0] = 0
	for i=1;i<=n;i++ {
		scanf("%d", &a[i])
	}
	sort.Ints(a[:n+1])
	for i=1;i<=n&&k>0;i++ {
		if(a[i] > a[i-1]){
			printf("%d\n", a[i] - a[i-1])
			k--;
		}
	}
	for k > 0 {
		printf("0\n")
		k--;
	}
}

package main

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

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() {
  defer writer.Flush()
  var n, k int
  scanf("%d %d\n", &n, &k)
  seen := map[int]bool{}
  var elem []int
  for i := 0; i < n; i += 1 {
    var a int
    scanf("%d", &a)
    _, ok := seen[a]
    if !ok {
      elem = append(elem, a)
      seen[a] = true
    }
  }
  sort.Ints(elem)

  var prev int = 0
  for i := 0; i < k; i += 1 {
    if i < len(elem) {
      printf("%d\n", elem[i] - prev)
      prev = elem[i]
    } else {
      printf("0\n")
    }
  }
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, k := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &k)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d", &a[i])
	}
	sort.Ints(a)
	last := 0
	for i := 0; i < k; i++ {
		if len(a) == 0 {
			fmt.Fprintf(out, "%d\n", 0)
		} else {
			fmt.Fprintf(out, "%d\n", a[0]-last)
			last = a[0]
			for len(a) > 0 && a[0] == last {
				a = a[1:]
			}
		}
	}
	return
}

package main

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

type Scanner struct{
	buf []byte
	len int
	index int
}

func (scanner *Scanner) readInt() int{
	var ret = 0
	var valid = false
	for i := scanner.index; i < scanner.len; i++ {
		var ch = scanner.buf[i]
		var k = 0
		if ch >= '0' && ch <= '9' {
			k = (int)(ch - '0')
			ret = ret * 10 + k
			valid = true
		}else if valid{
			scanner.index = i + 1
			break
		}
	}
	return ret
}

func main()  {

	buffer, eil := ioutil.ReadAll(os.Stdin)

	if eil != nil {
		log.Fatal(eil)
		return
	}

	var scanner = &Scanner{
		buf:buffer,
		len:len(buffer),
		index:0,
	}

	var n = scanner.readInt()
	var k = scanner.readInt()

	var a = make([]int , n + 1)
	for i := 0; i < n; i++ {
		a[i] = scanner.readInt()
	}

	a[n] = 0
	sort.Ints(a)

	for i := 1; k > 0; i++ {
		if i <= n {
			if a[i] > a[i - 1] {
				k--
				fmt.Println(a[i] - a[i-1])
			}
		}else {
			k--
			fmt.Println(0)
		}
	}
}

package main

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

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() {
	var nm, opr int
	scanf("%d %d\n", &nm, &opr)

	nms := make([]int, nm)
	for i := 0; i < nm; i++ {
		scanf("%d", &nms[i])
	}
	sort.Ints(nms)
	count := 0

	for opr > 0 {
		for i := 0; i < nm && opr > 0; i++ {
			if nms[i]-count > 0 {
				fmt.Println(nms[i] - count)
				count += (nms[i] - count)
				opr, nms[i] = opr-1, (nms[i] - count)
			}
		}

		break
	}
	zrShow(opr)

}

func zrShow(n int) {
	for i := 0; i < n; i++ {
		fmt.Println(0)
	}
}

package main

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

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() {
	defer writer.Flush()
	var n, k, t1, cur, pos int
	arr := []int{}
	scanf("%d %d\n", &n, &k)
	for i := 0; i < n; i++ {
		scanf("%d", &t1)
		arr = append(arr, t1)
	}
	sort.Ints(arr)
	cur = 0
	pos = 0

	for i := 0; i < k; i++ {
		if pos >= n {
			printf("0\n")
		} else {
			t1 = arr[pos] - cur
			if t1 == 0 {
				pos++
				i--
				continue
			}
			if t1 <= 0 {
				printf("0\n")
			} else {
				printf("%d\n", t1)
			}
			cur += t1
		}
	}

}

package main

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

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, o := scanNum(), scanNum()
	s := make([]int, n)
	for i := 0; i < n; i++ {
		s[i] = scanNum()
	}

	sort.Ints(s)
	cur, pointer := 0, 0
	for i := 0; i < o; i++ {
		// Move the pointer
		for (pointer < n) && (s[pointer] == cur) {
			pointer++
		}
		// Means all left ones are 0
		if pointer == n {
			fmt.Println(0)
			continue
		}
		fmt.Println(s[pointer] - cur)
		cur = s[pointer]
	}
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)

func init() {
	scanner.Split(bufio.ScanWords)
}

func scanString() string {
	scanner.Scan()
	return scanner.Text()
}

func scanBytes() []byte {
	scanner.Scan()
	return scanner.Bytes()
}

func scanInt64() int64 {
	scanner.Scan()
	v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return v
}

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

func scanInts(n int) []int {
	l := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		l[i], _ = strconv.Atoi(scanner.Text())
	}

	return l
}

func scanInts64(n int64) []int64 {
	l := make([]int64, n)
	for i := int64(0); i < n; i++ {
		scanner.Scan()
		l[i], _ = strconv.ParseInt(scanner.Text(), 10, 64)
	}

	return l
}

func scanBool() bool {
	scanner.Scan()
	v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return v == 1
}

func scanBools(n int64) []bool {
	l := make([]bool, n)
	for i := int64(0); i < n; i++ {
		scanner.Scan()
		v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
		l[i] = v == 1
	}

	return l
}

func scanUint64() uint64 {
	scanner.Scan()
	v, _ := strconv.ParseUint(scanner.Text(), 10, 64)
	return v
}

type ByAge []uint64

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i] < a[j] }

func main() {
	n, k := scanUint64(), scanUint64()

	a := make([]uint64, n)
	for i := uint64(0); i < n; i++ {
		a[i] = scanUint64()
	}

	sort.Sort(ByAge(a))

	a = skipZero(a)

	sum := uint64(0)
	for i := uint64(0); i < k; i++ {
		// a = skipZero(a)

		if len(a) == 0 {
			fmt.Println(0)
			continue
		}

		// for j := 0; j < len(a)-1; j++ {
		// 	if a[j] == a[j+1] {
		// 		a = a[1:]
		// 	}
		// }

		elem := a[0] - sum
		fmt.Println(elem)

		sum += elem

		for j := 1; j <= len(a); j++ {
			if j == len(a) {
				a = a[j:]
				break
			}
			if a[j] != a[j-1] {
				a = a[j:]
				break
			}
		}

	}

}

func skipZero(a []uint64) []uint64 {
	for len(a) > 0 && a[0] == 0 {
		a = a[1:]
	}

	return a
}

func abs(a int64) int64 {
	if a >= 0 {
		return a
	}

	return -a
}

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

	return b
}

package main

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

type Scanner struct{
	buf []byte
	len int
	index int
}

func (scanner *Scanner) readInt() int{
	var ret = 0
	var valid = false
	for i := scanner.index; i < scanner.len; i++ {
		var ch = scanner.buf[i]
		var k = 0
		if ch >= '0' && ch <= '9' {
			k = (int)(ch - '0')
			ret = ret * 10 + k
			valid = true
		}else if valid{
			scanner.index = i + 1
			break
		}
	}
	return ret
}

func main()  {

	buffer, eil := ioutil.ReadAll(os.Stdin)

	fmt.Println(string(buffer))

	if eil != nil {
		log.Fatal(eil)
		return
	}

	var scanner = &Scanner{
		buf:buffer,
		len:len(buffer),
		index:0,
	}

	var n = scanner.readInt()
	var k = scanner.readInt()

	var a = make([]int , n + 1)
	for i := 0; i < n; i++ {
		a[i] = scanner.readInt()
	}

	a[n] = 0
	sort.Ints(a)

	for i := 1; k > 0; i++ {
		if i <= n {
			if a[i] > a[i - 1] {
				k--
				fmt.Println(a[i] - a[i-1])
			}
		}else {
			k--
			fmt.Println(0)
		}
	}
}

package main

import (
	"fmt"
	"os"
	"runtime"
	"strings"
)

var aMin, aMax = -1000, 1000

func main() {
	var nm, opr int
	fmt.Fscan(os.Stdin, &nm, &opr)

	nms := make([]int, nm)
	for i := 0; i < nm; i++ {
		fmt.Fscan(os.Stdin, &nms[i])
	}
	countingSort(nms, aMin, aMax)
	count := 0
	if opr > nm {
		defer zrShow(opr - nm)
		opr = nm
	}
	for opr > 0 {
		for i := 0; i < nm; i++ {
			if nms[i]-count > 0 {
				fmt.Println(nms[i] - count)
				count += (nms[i] - count)
				opr, nms[i] = opr-1, (nms[i] - count)
			}

			if opr == 0 {
				break
			}
		}

		break
	}
}

func zrShow(n int) {
	for i := 0; i < n; i++ {
		fmt.Println(0)
	}
}

func countingSort(a []int, aMin, aMax int) {
	defer func() {
		if x := recover(); x != nil {
			// one error we'll handle and print a little nicer message
			if _, ok := x.(runtime.Error); ok &&
				strings.HasSuffix(x.(error).Error(), "index out of range") {
				fmt.Printf("data value out of range (%d..%d)\n", aMin, aMax)
				return
			}
			// anything else, we re-panic
			panic(x)
		}
	}()

	count := make([]int, aMax-aMin+1)
	for _, x := range a {
		count[x-aMin]++
	}
	z := 0
	// optimization over task pseudocode:   variable c is used instead of
	// count[i-min].  This saves some unneccessary calculations.
	for i, c := range count {
		for ; c > 0; c-- {
			a[z] = i + aMin
			z++
		}
	}
}

package main

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

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

var aMin, aMax = -100000, 100000

func main() {
	var nm, opr int
	scanf("%d %d\n", &nm, &opr)

	nms := make([]int, nm)
	for i := 0; i < nm; i++ {
		scanf("%d", &nms[i])
	}
	countingSort(nms, aMin, aMax)
	count := 0

	for opr > 0 {
		for i := 0; i < nm && opr > 0; i++ {
			if nms[i]-count > 0 {
				fmt.Println(nms[i] - count)
				count += (nms[i] - count)
				opr, nms[i] = opr-1, (nms[i] - count)
			}
		}

		break
	}
	zrShow(opr)

}

func zrShow(n int) {
	for i := 0; i < n; i++ {
		fmt.Println(0)
	}
}

func countingSort(a []int, aMin, aMax int) {
	defer func() {
		if x := recover(); x != nil {
			// one error we'll handle and print a little nicer message
			if _, ok := x.(runtime.Error); ok &&
				strings.HasSuffix(x.(error).Error(), "index out of range") {
				fmt.Printf("data value out of range (%d..%d)\n", aMin, aMax)
				return
			}
			// anything else, we re-panic
			panic(x)
		}
	}()

	count := make([]int, aMax-aMin+1)
	for _, x := range a {
		count[x-aMin]++
	}
	z := 0
	// optimization over task pseudocode:   variable c is used instead of
	// count[i-min].  This saves some unneccessary calculations.
	for i, c := range count {
		for ; c > 0; c-- {
			a[z] = i + aMin
			z++
		}
	}
}

package main

import (
	"fmt"
	"os"
	"runtime"
	"strings"
)

var aMin, aMax = -1000, 1000

func main() {
	var nm, opr int
	fmt.Fscan(os.Stdin, &nm, &opr)

	nms := make([]int, nm)
	for i := 0; i < nm; i++ {
		fmt.Fscan(os.Stdin, &nms[i])
	}
	countingSort(nms, aMin, aMax)
	count := 0
	defer zrShow(opr)

	for opr > 0 {
		for i := 0; i < nm; i++ {
			if nms[i]-count > 0 {
				fmt.Println(nms[i] - count)
				count += (nms[i] - count)
				opr, nms[i] = opr-1, (nms[i] - count)
			}

			if opr == 0 {
				break
			}
		}

		break
	}
}

func zrShow(n int) {
	for i := 0; i < n; i++ {
		fmt.Println(0)
	}
}

func countingSort(a []int, aMin, aMax int) {
	defer func() {
		if x := recover(); x != nil {
			// one error we'll handle and print a little nicer message
			if _, ok := x.(runtime.Error); ok &&
				strings.HasSuffix(x.(error).Error(), "index out of range") {
				fmt.Printf("data value out of range (%d..%d)\n", aMin, aMax)
				return
			}
			// anything else, we re-panic
			panic(x)
		}
	}()

	count := make([]int, aMax-aMin+1)
	for _, x := range a {
		count[x-aMin]++
	}
	z := 0
	// optimization over task pseudocode:   variable c is used instead of
	// count[i-min].  This saves some unneccessary calculations.
	for i, c := range count {
		for ; c > 0; c-- {
			a[z] = i + aMin
			z++
		}
	}
}

package main

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

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

var aMin, aMax = -1000, 1000

func main() {
	var nm, opr int
	scanf("%d %d\n", &nm, &opr)

	nms := make([]int, nm)
	for i := 0; i < nm; i++ {
		scanf("%d", &nms[i])
	}
	countingSort(nms, aMin, aMax)
	count := 0

	for opr > 0 {
		for i := 0; i < nm && opr > 0; i++ {
			if nms[i]-count > 0 {
				printf("%d\n", nms[i]-count)
				count += (nms[i] - count)
				opr, nms[i] = opr-1, (nms[i] - count)
			}
		}

		break
	}
	zrShow(opr)

}

func zrShow(n int) {
	for i := 0; i < n; i++ {
		printf("0\n")
	}
}

func countingSort(a []int, aMin, aMax int) {
	defer func() {
		if x := recover(); x != nil {
			// one error we'll handle and print a little nicer message
			if _, ok := x.(runtime.Error); ok &&
				strings.HasSuffix(x.(error).Error(), "index out of range") {
				fmt.Printf("data value out of range (%d..%d)\n", aMin, aMax)
				return
			}
			// anything else, we re-panic
			panic(x)
		}
	}()

	count := make([]int, aMax-aMin+1)
	for _, x := range a {
		count[x-aMin]++
	}
	z := 0
	// optimization over task pseudocode:   variable c is used instead of
	// count[i-min].  This saves some unneccessary calculations.
	for i, c := range count {
		for ; c > 0; c-- {
			a[z] = i + aMin
			z++
		}
	}
}

package main

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

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

var aMin, aMax = -1000, 1000

func main() {
	var nm, opr int
	scanf("%d %d\n", &nm, &opr)

	nms := make([]int, nm)
	for i := 0; i < nm; i++ {
		scanf("%d", &nms[i])
	}
	countingSort(nms, aMin, aMax)
	count := 0

	for opr > 0 {
		for i := 0; i < nm && opr > 0; i++ {
			if nms[i]-count > 0 {
				fmt.Println(nms[i] - count)
				count += (nms[i] - count)
				opr, nms[i] = opr-1, (nms[i] - count)
			}
		}

		break
	}
	zrShow(opr)

}

func zrShow(n int) {
	for i := 0; i < n; i++ {
		fmt.Println(0)
	}
}

func countingSort(a []int, aMin, aMax int) {
	defer func() {
		if x := recover(); x != nil {
			// one error we'll handle and print a little nicer message
			if _, ok := x.(runtime.Error); ok &&
				strings.HasSuffix(x.(error).Error(), "index out of range") {
				fmt.Printf("data value out of range (%d..%d)\n", aMin, aMax)
				return
			}
			// anything else, we re-panic
			panic(x)
		}
	}()

	count := make([]int, aMax-aMin+1)
	for _, x := range a {
		count[x-aMin]++
	}
	z := 0
	// optimization over task pseudocode:   variable c is used instead of
	// count[i-min].  This saves some unneccessary calculations.
	for i, c := range count {
		for ; c > 0; c-- {
			a[z] = i + aMin
			z++
		}
	}
}


Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).The next paragraph is specific to the version 1 of the problem.Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.Vova is a perfectionist, so he considers the wall completed when:  all parts of the wall has the same height;  the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial heights of the parts of the wall.

Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero). Print "NO" otherwise.

NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put a brick vertically on part 3 to make the wall $$$[4, 5, 5]$$$, then horizontally on parts 2 and 3 to make it $$$[4, 6, 6]$$$ and then vertically on part 1 to make it $$$[6, 6, 6]$$$.In the third example the wall is already complete.

package main

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

func solve(mat []bool)bool  {
//	fmt.Println("solve:",mat)
	len := len(mat)
	stack := make([]bool,len)
	var front int = 0
	for i:=0;i < len&&front <= len/2;i++{
		if front == 0{
			stack[front] = mat[i]
			front++
			continue
		}
		if stack[front-1] != mat[i]{
			front--
		}else{
			stack[front]=mat[i]
			front++
		}
	}
	if front > 0{
		return false
	}else{
		return true
	}
}
func oddOrEven(v []bool)[]bool {
	len := len(v)
	for i := 0;i < len;i++{
		if v[i] == true{
			v[i] = false
		}else{
			v[i] = true
		}
	}
	return v
}
func process(v []bool)[]bool  {
//	fmt.Println("v:",v)
	res := make([]bool,0)
	cnt := 0
	len := len(v)
	for i:=0;i <= len;i++{
		if cnt>0&&( i == len || v[i] == false){
			if (cnt&1)==1{
				if (i&1)==1{
					res = append(res,true)
				}else{
					res = append(res,false)
				}
			}
			cnt = 0
		}
		if i < len&&v[i]{
			cnt++
		}
	}
//	fmt.Println("res:",res)
	return res
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(buf, "%d\n", &n)
	flag := make([]bool,n)
	for i := 0; i < n; i++ {
		var v int
		fmt.Fscanf(buf, "%d",&v)
		flag[i] = false
		if (v&1)==1{
			flag[i] = true
		}
	}
	pv := process(flag)
	ppv := process(oddOrEven(flag))
	if solve(pv) || solve(ppv){
		fmt.Println("YES")
	}else{
		fmt.Println("NO")
	}
}

/*
4 2
1 2
3 4
2 0

5 4
1 2
3 4
4 5
5 3
5 1
1 2
*/

package main

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

func main() {
	start := time.Now()
	defer func() {
		run := time.Since(start)
		_ = run
		// fmt.Println("Run in", run)
	}()

	var stdin *bufio.Reader
	// LOCAL
	f, _ := os.Open("input.txt")
	stdin = bufio.NewReader(f)

	// ONLINE JUDGE
	stdin = bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(stdin, &n)

	var a = make([]int, n)
	var stack = make([]int, 0)
	for i := 0; i < n; i++ {
		fmt.Fscan(stdin, &a[i])
		a[i] &= 1

		stack = append(stack, a[i])
		if len(stack) > 1 && stack[len(stack)-1] == stack[len(stack)-2] {
			stack = stack[:len(stack)-2]
		}
	}
	if len(stack) <= 1 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

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

func main() {
	io := newIO()
	defer io.out.Flush()

	n := io.nextInt()
	a := io.nextArr(n)
	var s stack
	for i := 0; i < n; i++ {
		s = s.clr()
		s = s.Push(a[i] % 2)
	}
	s = s.clr()
	if len(s) <= 1 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

func (s stack) clr() stack {
	var first, second int
	for len(s) >= 2 {
		s, first = s.Pop()
		s, second = s.Pop()
		if first != second {
			s = s.Push(second)
			s = s.Push(first)
			return s
		}
	}
	return s
}

type stack []int

func (s stack) Push(v int) stack {
	return append(s, v)
}

func (s stack) Pop() (stack, int) {
	l := len(s)
	return  s[:l-1], s[l-1]
}

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

type io struct {
	inp *bufio.Scanner
	out *bufio.Writer
}

func newIO() io {
	sc := io{
		inp : bufio.NewScanner(os.Stdin),
		out : bufio.NewWriter(os.Stdout),
	}
	sc.inp.Split(bufio.ScanWords)
	return sc
}
func (sc io) nextArr(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = sc.nextInt()
	}
	return a
}
func (sc io) nextString() string {
	sc.inp.Scan()
	return sc.inp.Text();
}

func (sc io) nextInt64() int64 {
	v, _ := strconv.ParseInt(sc.nextString(), 10, 64)
	return int64(v)
}
func (sc io) nextInt() int {
	v, _ := strconv.ParseInt(sc.nextString(), 10, 64)
	return int(v)
}

package main

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

type block struct {
	n int64
	h int64
}

var n int
var x int64
var wall []block

func Abs(n int64) int64 {
	if n < 0 {
		return n * -1
	}
	return n
}
func Max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}
func NewBlock(n, h int64) block {
	return block{n: n, h: h}
}
func Swap(a, b block) (block, block) {
	return b, a
}

func Combine(a, b block) block {
	var res = block{n: a.n + b.n, h: Max(a.h, b.h)}

	if Abs(a.h-b.h)%2 == 0 {
		return res
	}
	if a.n%2 == 0 || b.n%2 == 0 {
		if a.n%2 == 1 {
			a, b = Swap(a, b)
		}
		if a.h > b.h {
			res.h++
			return res
		}
		return res
	}

	res.n = -1
	return res
}

func main() {
	start := time.Now()
	defer func() {
		run := time.Since(start)
		_ = run
		// fmt.Println("Run in", run)
	}()

	var stdin *bufio.Reader
	// LOCAL
	f, _ := os.Open("input.txt")
	stdin = bufio.NewReader(f)

	// ONLINE JUDGE
	// stdin = bufio.NewReader(os.Stdin)

	fmt.Fscan(stdin, &n)
	wall = make([]block, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(stdin, &x)
		wall[i].n = 1
		wall[i].h = x
	}

	var found = true
	for found {
		found = false
		var newwall = []block{}
		if len(wall) == 1 {
			break
		}
		for i := 0; i < len(wall); i++ {
			if i == len(wall)-1 {
				newwall = append(newwall, wall[i])
			} else {
				var tmp = Combine(wall[i], wall[i+1])
				if tmp.n != -1 {
					i++
					newwall = append(newwall, tmp)
					found = true
				} else {
					newwall = append(newwall, wall[i])
				}
			}
		}
		if len(wall) == len(newwall) {
			break
		}
		wall = newwall
		// fmt.Println("Combined", wall)
	}

	if len(wall) != 1 {
		fmt.Println("NO")
	} else {
		fmt.Println("YES")
	}
}

package main

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

type block struct {
    n int64
    h int64
}

var n int
var x int64
var wall []block

func Abs (n int64) int64 {
    if n < 0 {
        return n * -1
    }
    return n
}
func Max (a, b int64) int64 {
    if a > b {
        return a
    }
    return b
}

func Combine(a, b block) block {
    var res = block {n: a.n + b.n, h: Max(a.h, b.h) }
    if a.n % 2 == 0 || b.n % 2 == 0 {
        // Cot chan, ghep sao cung okie
        return res
    } else if a.n == 1 && b.n == 1 {
        if Abs(a.h - b.h) % 2 == 0 {
            return res
        }
    } else if Abs(a.h - b.h) % 2 == 0 {
        return res
    }
    res.n = -1
    res.h = 0
    return res
}

func main() {
    start := time.Now()
    defer func () {
        run := time.Since(start)
        _ = run
        // fmt.Println("Run in", run)
    }()

    stdin := bufio.NewReader(os.Stdin)

    fmt.Fscan(stdin, &n)
    wall = make([]block, n)
    for i := 0; i < n; i++ {
        fmt.Fscan(stdin, &x)
        wall[i].n = 1
        wall[i].h = x
    }

    b := make([]block, n)
    for i:= 0; i < n-1; i++ {
        var tmp = Combine(wall[i], wall[i + 1])
        if tmp.n != -1 {
            b[i] = tmp
        } else {
            b[i] = wall[i]
        }
    }

    var found = true
    b = wall
    for found {
        found = false
        for i := 0; i < n; {
            var j = int64(i) + b[i].n
            if j >= int64(n) {
                break
            }
            var tmp = Combine(b[i], b[j])

            if tmp.n != -1 {
                found = true
                b[i] = tmp
            } else {
                i++
            }
        }
        // fmt.Println("Combined", b)
    }

    if b[0].n == int64(n) {
        fmt.Println("YES")
    } else {
        fmt.Println("NO")
    }
}

package main

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

type block struct {
    n int64
    h int64
}

var n int
var x int64
var wall []block

func Abs (n int64) int64 {
    if n < 0 {
        return n * -1
    }
    return n
}
func Max (a, b int64) int64 {
    if a > b {
        return a
    }
    return b
}

func Combine(a, b block) block {
    var res = block {n: a.n + b.n, h: Max(a.h, b.h) }
    if a.n % 2 == 0 || b.n % 2 == 0 {
        // Cot chan, ghep sao cung okie
        return res
    } else if a.n == 1 && b.n == 1 {
        if Abs(a.h - b.h) % 2 == 0 {
            return res
        }
    } else if Abs(a.h - b.h) % 2 == 0 {
        return res
    }
    res.n = -1
    return res
}

func main() {
    start := time.Now()
    defer func () {
        run := time.Since(start)
        _ = run
        // fmt.Println("Run in", run)
    }()

    stdin := bufio.NewReader(os.Stdin)

    fmt.Fscan(stdin, &n)
    wall = make([]block, n)
    for i := 0; i < n; i++ {
        fmt.Fscan(stdin, &x)
        wall[i].n = 1
        wall[i].h = x
    }

    var found = true
    for found {
        found = false
        var newwall = []block{}
        if len(wall) == 1 {
            break
        }
        for i := 0; i < len(wall); i++ {
            if i == len(wall) - 1 {
                newwall = append(newwall, wall[i])
            } else {
                var tmp = Combine(wall[i], wall[i + 1])
                if tmp.n != -1 {
                    i++
                    newwall = append(newwall, tmp)
                    found = true
                } else {
                    newwall = append(newwall, wall[i])
                }
            }
        }

        wall = newwall
        // fmt.Println("Combined", wall)
    }

    if len(wall) != 1 {
        fmt.Println("NO")
    } else {
        fmt.Println("YES")
    }
}

package main

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

type block struct {
    n int64
    h int64
}

var n int
var x int64
var wall []block

func Abs (n int64) int64 {
    if n < 0 {
        return n * -1
    }
    return n
}
func Max (a, b int64) int64 {
    if a > b {
        return a
    }
    return b
}

func Combine(a, b block) block {
    var res = block {n: a.n + b.n, h: Max(a.h, b.h) }
    if a.n % 2 == 0 || b.n % 2 == 0 {
        // Cot chan, ghep sao cung okie
        return res
    } else if a.n == 1 && b.n == 1 {
        if Abs(a.h - b.h) % 2 == 0 {
            return res
        }
    } else if Abs(a.h - b.h) % 2 == 0 {
        return res
    }
    res.n = -1
    return res
}

func main() {
    start := time.Now()
    defer func () {
        run := time.Since(start)
        _ = run
        // fmt.Println("Run in", run)
    }()

    stdin := bufio.NewReader(os.Stdin)

    fmt.Fscan(stdin, &n)
    wall = make([]block, n)
    for i := 0; i < n; i++ {
        fmt.Fscan(stdin, &x)
        wall[i].n = 1
        wall[i].h = x
    }

    b := make([]block, n)
    for i:= 0; i < n-1; i++ {
        var tmp = Combine(wall[i], wall[i + 1])
        if tmp.n != -1 {
            b[i] = tmp
        } else {
            b[i] = wall[i]
        }
    }

    var found = true
    b = wall
    for found {
        found = false
        for i := 0; i < n; {
            var j = int64(i) + b[i].n
            if j >= int64(n) {
                break
            }
            var tmp = Combine(b[i], b[j])

            if tmp.n != -1 {
                found = true
                b[i] = tmp
                i = int(j)
            } else {
                i++
            }
        }
        // fmt.Println("Combined", b)
    }

    if b[0].n == int64(n) {
        fmt.Println("YES")
    } else {
        fmt.Println("NO")
    }
}

package main

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

func main() {
	io := newIO()
	defer io.out.Flush()

	n := io.nextInt()
	a := io.nextArr(n)
	mx := 0
	for _, v := range a { mx = max(mx, v) }

main : for add := 0; add <= 3; add++ {
	arr := make([]int, n)
	for i, v := range a {
		arr[i] = (mx + add - v)
		if arr[i] % 2 == 0 { arr[i] = 2 } else { arr[i] = 1 }
	}
inner : for i, v := range arr {
	if v == 0 { continue }
	if v == 1 {
		if i >= 1 && arr[i - 1] == 1 {
			arr[i] = 0
			arr[i - 1] = 0
			continue inner
		}
		if i <= n - 2 && arr[i + 1] == 1 {
			arr[i] = 0
			arr[i + 1] = 0
			continue inner
		}
		if i <= n - 3 && arr[i + 1] == 2 && arr[i + 2] == 2 {
			arr[i] = 0
			arr[i + 1] = 0
			arr[i + 2] = 1
			continue inner
		}
		continue main
	} else {
		arr[i] = 0
	}
}

	io.out.WriteString("YES\n")
	return
}

	io.out.WriteString("NO\n")
}

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

type io struct {
	inp *bufio.Scanner
	out *bufio.Writer
}

func newIO() io {
	sc := io{
		inp : bufio.NewScanner(os.Stdin),
		out : bufio.NewWriter(os.Stdout),
	}
	sc.inp.Split(bufio.ScanWords)
	return sc
}
func (sc io) nextArr(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = sc.nextInt()
	}
	return a
}
func (sc io) nextString() string {
	sc.inp.Scan()
	return sc.inp.Text();
}

func (sc io) nextInt64() int64 {
	v, _ := strconv.ParseInt(sc.nextString(), 10, 64)
	return int64(v)
}
func (sc io) nextInt() int {
	v, _ := strconv.ParseInt(sc.nextString(), 10, 64)
	return int(v)
}

package main

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

func main() {
	io := newIO()
	defer io.out.Flush()

	n := io.nextInt()
	a := io.nextArr(n)
	mx := 0
	for _, v := range a { mx = max(mx, v) }

	main : for add := 0; add <= 3; add++ {
		arr := make([]int, n)
		for i, v := range a {
			arr[i] = (mx + add - v)
			if arr[i] != 0 {
				if arr[i] % 2 == 0 { arr[i] = 2 } else { arr[i] = 1 }
			}
		}
		inner : for i, v := range arr {
			if v == 0 { continue }
			if v == 1 {
				if i >= 1 && arr[i - 1] == 1 {
					arr[i] = 0
					arr[i - 1] = 0
					continue inner
				}
				if i <= n - 2 && arr[i + 1] == 1 {
					arr[i] = 0
					arr[i + 1] = 0
					continue inner
				}
				if i <= n - 3 && arr[i + 1] == 2 && arr[i + 2] == 2 {
					arr[i] = 0
					arr[i + 1] = 0
					arr[i + 2] = 1
					continue inner
				}
				continue main
			} else {
				arr[i] = 0
			}
		}

		io.out.WriteString("YES\n")
		return
	}

	io.out.WriteString("NO\n")
}

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

type io struct {
	inp *bufio.Scanner
	out *bufio.Writer
}

func newIO() io {
	sc := io{
		inp : bufio.NewScanner(os.Stdin),
		out : bufio.NewWriter(os.Stdout),
	}
	sc.inp.Split(bufio.ScanWords)
	return sc
}
func (sc io) nextArr(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = sc.nextInt()
	}
	return a
}
func (sc io) nextString() string {
	sc.inp.Scan()
	return sc.inp.Text();
}

func (sc io) nextInt64() int64 {
	v, _ := strconv.ParseInt(sc.nextString(), 10, 64)
	return int64(v)
}
func (sc io) nextInt() int {
	v, _ := strconv.ParseInt(sc.nextString(), 10, 64)
	return int(v)
}


Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!The computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options.You have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.

The first line contains three integers a, b and c (0 ≤ a, b, c ≤ 105)  — the number of computers that only have USB ports, the number of computers, that only have PS/2 ports, and the number of computers, that have both options, respectively. The next line contains one integer m (0 ≤ m ≤ 3·105)  — the number of mouses in the price list. The next m lines each describe another mouse. The i-th line contains first integer vali (1 ≤ vali ≤ 109)  — the cost of the i-th mouse, then the type of port (USB or PS/2) that is required to plug the mouse in.

Output two integers separated by space — the number of equipped computers and the total cost of the mouses you will buy.

NoteIn the first example you can buy the first three mouses. This way you will equip one of the computers that has only a USB port with a USB mouse, and the two PS/2 mouses you will plug into the computer with PS/2 port and the computer with both ports.

package main

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

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	defer w.Flush()
	var a int
	for I(&a) == nil {
		solve(a)
	}
}

func solve(a int) {
	var b, c, m int
	I(&b, &c, &m)
	mm := make(arr, m)
	for i := 0; i < m; i++ {
		var s string
		I(&mm[i][0], &s)
		if s == "USB" {
			mm[i][1] = 1
		}
	}
	sort.Sort(mm)
	ans := 0
	amount := uint64(0)
	for i := range mm {
		if mm[i][1] == 1 {
			if a > 0 {
				a--
				ans++
				amount += mm[i][0]
			} else if c > 0 {
				c--
				ans++
				amount += mm[i][0]
			}
		} else {
			if b > 0 {
				b--
				ans++
				amount += mm[i][0]
			} else if c > 0 {
				c--
				ans++
				amount += mm[i][0]
			}
		}
	}
	O(ans, amount, "\n")
}

type arr [][2]uint64

func (a arr) Len() int           { return len(a) }
func (a arr) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a arr) Less(i, j int) bool { return a[i][0] < a[j][0] }

package main

import (
	"os"
	"bufio"
	"sort"
	"strconv"
	// "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 mouse struct {
	price int
	mType string
}

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

    usb, ps2, b := ReadInt(), ReadInt(), ReadInt()

    m := ReadInt()

    v := make([]mouse, m)

    for i := 0; i < m; i++ {
    	var mo mouse
    	mo.price = ReadInt()
    	scanner.Scan()
    	mo.mType = scanner.Text()
    	v[i] = mo
    }

   	sort.Slice(v, func(i,j int) bool {
   		return v[i].price < v[j].price
   		})

   	qt := 0
   	total := int64(0)

   	for _,elem := range v {

   		if elem.mType == "USB" {
   			if usb > 0 {
   				usb--
   				qt++
   				total += int64(elem.price)
   			} else if b > 0 {
   				b--
   				qt++
   				total += int64(elem.price)
   			}
   		} else {
   			if ps2 > 0 {
   				ps2--
   				qt++
   				total += int64(elem.price)
   			} else if b > 0 {
   				b--
   				qt++
   				total += int64(elem.price)
   			}
   		}
   	}

	writer.WriteString(strconv.Itoa(qt))
	writer.WriteString(" ")
	writer.WriteString(strconv.FormatInt(total, 10))
	writer.WriteString("\n")

}

package main

import (
	"os"
	"bufio"
	"sort"
	"strconv"
	// "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 mouse struct {
	price int
	mType string
}

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

    usb, ps2, b := ReadInt(), ReadInt(), ReadInt()

    m := ReadInt()

    var v []mouse

    for ; m > 0; m-- {
    	var mo mouse
    	mo.price = ReadInt()
    	scanner.Scan()
    	mo.mType = scanner.Text()
    	v = append(v, mo)
    }

   	sort.Slice(v, func(i,j int) bool {
   		return v[i].price < v[j].price
   		})

   	qt := 0
   	total := int64(0)

   	for _,elem := range v {

   		if elem.mType == "USB" {
   			if usb > 0 {
   				usb--
   				qt++
   				total += int64(elem.price)
   			} else if b > 0 {
   				b--
   				qt++
   				total += int64(elem.price)
   			}
   		} else {
   			if ps2 > 0 {
   				ps2--
   				qt++
   				total += int64(elem.price)
   			} else if b > 0 {
   				b--
   				qt++
   				total += int64(elem.price)
   			}
   		}
   	}

	writer.WriteString(strconv.Itoa(qt))
	writer.WriteString(" ")
	writer.WriteString(strconv.FormatInt(total, 10))
	writer.WriteString("\n")

}

package main

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

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

const (
    usb = iota
    ps2
)

type mouse struct {
    price int64
    port  int
}

type byPort []mouse

func (a byPort) Len() int {
    return len(a)
}

func (a byPort) Swap(i, j int) {
    a[i], a[j] = a[j], a[i]
}

func (a byPort) Less(i, j int) bool {
    return a[i].port < a[j].port || (a[i].port == a[j].port && a[i].price < a[j].price)
}

func main() {
    in := bufio.NewReader(os.Stdin)

    // your code here
    var a, b, c int
    fmt.Fscanf(in, "%d %d %d\n", &a, &b, &c)
    var m int
    fmt.Fscanf(in, "%d\n", &m)
    portCodes := map[string]int{
        "USB": usb,
        "PS/2": ps2,
    }
    usbCount := 0
    mice := make([]mouse, m)
    for i := 0; i < m; i++ {
        var port string
        fmt.Fscanf(in, "%d %s\n", &(mice[i].price), &port)
        mice[i].port = portCodes[port]
        if mice[i].port == usb {
            usbCount++
        }
    }
    sort.Sort(byPort(mice))

    usbIdx, ps2Idx := 0, usbCount
    count, cost := 0, int64(0)
    for i := 0; i < a && usbIdx < usbCount; i, count, usbIdx = i+1, count+1, usbIdx+1 {
        cost += mice[usbIdx].price
    }
    for i := 0; i < b && ps2Idx < m; i, count, ps2Idx = i+1, count+1, ps2Idx+1 {
        cost += mice[ps2Idx].price
    }
    for i := 0; i < c && (usbIdx < usbCount || ps2Idx < m); i, count = i+1, count+1 {
        var cheapPrice int64 = 10000000001
        var idx *int
        if usbIdx < usbCount && mice[usbIdx].price < cheapPrice {
            cheapPrice = mice[usbIdx].price
            idx = &usbIdx
        }
        if ps2Idx < m && mice[ps2Idx].price < cheapPrice {
            cheapPrice = mice[ps2Idx].price
            idx = &ps2Idx
        }
        cost += cheapPrice
        *idx++
    }

    fmt.Printf("%d %d\n", count, cost)
}

package main

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

type Mouse struct {
	Price int64
	IsUsb bool
}

func solve() {
	a := readInt()
	b := readInt()
	c := readInt()
	m := readInt()
	items := make([]Mouse, m)
	for i := 0; i < m; i++ {
		items[i] = Mouse{readInt64(), parseType(readString())}
	}
	sort.Sort(ByPrice(items))
	total := 0
	sum := int64(0)
	for i := 0; i < m; i++ {
		item := items[i]
		if item.IsUsb {
			if a > 0 {
				a--
				total++
				sum += item.Price
			} else if c > 0 {
				c--
				total++
				sum += item.Price
			}
		} else {
			if b > 0 {
				b--
				total++
				sum += item.Price
			} else if c > 0 {
				c--
				total++
				sum += item.Price
			}
		}
	}
	fmt.Printf("%d %d\n", total, sum)
}

type ByPrice []Mouse

func (a ByPrice) Len() int           { return len(a) }
func (a ByPrice) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByPrice) Less(i, j int) bool { return a[i].Price < a[j].Price }

func parseType(name string) bool {
	if name == "USB" {
		return true
	}
	return false
}

var scanner *bufio.Scanner

func main() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

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

// IO

func readString() string {
	scanner.Scan()
	return scanner.Text()
}

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

func readInt64() int64 {
	v, _ := strconv.ParseInt(readString(), 10, 64)
	return v
}

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

func readInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := 0; i < n; i++ {
		res[i] = readInt64()
	}
	return res
}

// Codeforces 774 C done
package main

import (
"bufio"
"fmt"
"strings"
"strconv"
	"os"
	"sort"
)
var in *bufio.Reader

func readFive() (int,int,int,int,int) {
	var a [5]int
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("first read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for i:=0; i<len(ss); i++ {
		a[i], err = strconv.Atoi(ss[i])
		if err != nil {
			fmt.Println("n atoi failure", err)
			panic(err)
		}
	}
	return a[0],a[1],a[2],a[3],a[4]
}

func readLineNumbs(n int) []int {
	a := make([]int, n)
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for j:=0; j<n; j++ {
		aa,err := strconv.Atoi(ss[j])
		if err != nil {
			fmt.Println("aa conv failed", err)
			panic(err)
		}
		a[j] = aa
	}
	return a
}

var a,b,c,m int
var mCost []int
var usbPs []bool
var nComp int
var totCost int64

func readData() {
	in = bufio.NewReader(os.Stdin)
	a,b,c,_,_ = readFive()
	m,_,_,_,_ = readFive()
	usbPs = make([]bool, m)
	mCost = make([]int, m)
	for i:=0; i<m; i++ {
        s, err := in.ReadString('\n')
        if err != nil {
            fmt.Println("read mouse failure", err)
            panic(err)
        }
        ss := strings.Split(strings.Trim(s, " \n\r"), " ")
        mCost[i],_ = strconv.Atoi(ss[0])
        if ss[1][0] == 'U' {
            usbPs[i] = true
        } else {
            usbPs[i] = false
        }
    }
}

var nUsb,nPs,iU,iP int
var usbCost []int
var psCost []int

func addMouse(usb bool) {
	if usb {
		totCost += int64(usbCost[iU])
		nComp++
		iU++
	} else {
		totCost += int64(psCost[iP])
		nComp++
		iP++
	}
	//fmt.Println("added mouse usb = ", usb, " totCost: ", totCost)
}

func solve() {
	nUsb = 0; nPs = 0
	for i:=0; i<m; i++ {
		if usbPs[i] {
			nUsb++
		} else {
			nPs++
		}
	}
	//fmt.Println("nUsb,nPs = ", nUsb, nPs)
	usbCost = make([]int, nUsb)
	psCost = make([]int, nPs)
	iU = 0; iP = 0
	for i:=0; i<m; i++ {
		if usbPs[i] {
			usbCost[iU] = mCost[i]
			iU++
		} else {
			psCost[iP] = mCost[i]
			iP++
		}
	}
	// sort costs
	sort.Ints(usbCost)
	sort.Ints(psCost)
	// deal with USB only
	iU = 0; iP = 0; nComp = 0
	for ; iU<nUsb && iU<a; {
		addMouse(true)
	}
	// deal with ps2
	for ; iP<nPs && iP<b; {
		addMouse(false)
	}
	// deal with comps using USB & PS2
	ic := 0
	for (iU<nUsb || iP<nPs) && ic<c {
		if iU<nUsb && iP<nPs {
			if usbCost[iU] < psCost[iP] {
				addMouse(true)
			} else {
				addMouse(false)
			}
		} else {
			if iU<nUsb {
				addMouse(true)
			} else {
				addMouse(false)
			}
		}
		ic++
	}
}

func printRes() {
	fmt.Println(nComp," ",totCost)
}

func main() {
	readData()
	solve()
	printRes()
}

package main

import (
	"os"
	"bufio"
	"sort"
	"strconv"
	// "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 mouse struct {
	price int
	mType string
}

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

    usb, ps2, b := ReadInt(), ReadInt(), ReadInt()

    m := ReadInt()

    var v []mouse

    for ; m > 0; m-- {
    	var mo mouse
    	mo.price = ReadInt()
    	scanner.Scan()
    	mo.mType = scanner.Text()
    	v = append(v, mo)
    }

   	sort.Slice(v, func(i,j int) bool {
   		return v[i].price < v[j].price
   		})

   	qt := 0
   	total := 0

   	for _,elem := range v {

   		if elem.mType == "USB" {
   			if usb > 0 {
   				usb--
   				qt++
   				total += elem.price
   			} else if b > 0 {
   				b--
   				qt++
   				total += elem.price
   			}
   		} else {
   			if ps2 > 0 {
   				ps2--
   				qt++
   				total += elem.price
   			} else if b > 0 {
   				b--
   				qt++
   				total += elem.price
   			}
   		}
   	}

	writer.WriteString(strconv.Itoa(qt))
	writer.WriteString(" ")
	writer.WriteString(strconv.Itoa(total))
	writer.WriteString("\n")

}

// Codeforces 774 C done
package main

import (
"bufio"
"fmt"
"strings"
"strconv"
	"os"
	"sort"
)
var in *bufio.Reader

func readFive() (int,int,int,int,int) {
	var a [5]int
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("first read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for i:=0; i<len(ss); i++ {
		a[i], err = strconv.Atoi(ss[i])
		if err != nil {
			fmt.Println("n atoi failure", err)
			panic(err)
		}
	}
	return a[0],a[1],a[2],a[3],a[4]
}

func readLineNumbs(n int) []int {
	a := make([]int, n)
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for j:=0; j<n; j++ {
		aa,err := strconv.Atoi(ss[j])
		if err != nil {
			fmt.Println("aa conv failed", err)
			panic(err)
		}
		a[j] = aa
	}
	return a
}

var a,b,c,m int
var mCost []int
var usbPs []bool
var nComp int
var totCost int64

func readData() {
	in = bufio.NewReader(os.Stdin)
	a,b,c,_,_ = readFive()
	m,_,_,_,_ = readFive()
	usbPs = make([]bool, m)
	mCost = make([]int, m)
	for i:=0; i<m; i++ {
        s, err := in.ReadString('\n')
        if err != nil {
            fmt.Println("read mouse failure", err)
            panic(err)
        }
        ss := strings.Split(strings.Trim(s, " \n\r"), " ")
        mCost[i],_ = strconv.Atoi(ss[0])
        if ss[1][0] == 'U' {
            usbPs[i] = true
        } else {
            usbPs[i] = false
        }
    }
}

var nUsb,nPs,iU,iP int
var usbCost []int
var psCost []int

func addMouse(usb bool) {
	if usb {
		totCost += int64(usbCost[iU])
		nComp++
		iU++
	} else {
		totCost += int64(psCost[iP])
		nComp++
		iP++
	}
	//fmt.Println("added mouse usb = ", usb, " totCost: ", totCost)
}

func solve() {
	nUsb = 0; nPs = 0
	for i:=0; i<m; i++ {
		if usbPs[i] {
			nUsb++
		} else {
			nPs++
		}
	}
	//fmt.Println("nUsb,nPs = ", nUsb, nPs)
	usbCost = make([]int, nUsb)
	psCost = make([]int, nPs)
	iU = 0; iP = 0
	for i:=0; i<m; i++ {
		if usbPs[i] {
			usbCost[iU] = mCost[i]
			iU++
		} else {
			psCost[iP] = mCost[i]
			iP++
		}
	}
	// sort costs
	sort.Ints(usbCost)
	sort.Ints(psCost)
	// deal with USB only
	iU = 0; iP = 0; nComp = 0
	for ; iU<nUsb && iU<a; {
		addMouse(true)
	}
	// deal with ps2
	for ; iP<nPs && iP<b; {
		addMouse(false)
	}
	// deal with comps using USB & PS2
	for (iU<nUsb && iU<a+c) || (iP<nPs && iP<b+c) {
		if (iU<nUsb && iU<a+c) && (iP<nPs && iP<b+c) {
			if usbCost[iU] < psCost[iP] {
				addMouse(true)
			} else {
				addMouse(false)
			}
		} else {
			if (iU<nUsb && iU<a+c) {
				addMouse(true)
			} else {
				addMouse(false)
			}
		}
	}
}

func printRes() {
	fmt.Println(nComp," ",totCost)
}

func main() {
	readData()
	solve()
	printRes()
}