package main

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

/*
1
3 5 2
aaa
bbbbb
---
aababb
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n, m, k int
	var a, b string
	scanf("%d %d %d\n%s\n%s\n", &n, &m, &k, &a, &b)

	arrA := []rune(a)
	sort.Slice(arrA, func(i, j int) bool {
		return arrA[i] < arrA[j]
	})

	arrB := []rune(b)
	sort.Slice(arrB, func(i, j int) bool {
		return arrB[i] < arrB[j]
	})

	i, j := 0, 0

	res := make([]rune, 0)

	aCnt := 0
	bCnt := 0

	for i < len(arrA) && j < len(arrB) {
		useA := true

		if i < len(arrA) && j < len(arrB) {
			useA = i < len(arrA) && arrA[i] < arrB[j]
		}

		if useA && aCnt == k {
			useA = false
		} else if !useA && bCnt == k {
			useA = true
		}

		if useA {
			res = append(res, arrA[i])
			i++

			aCnt++
			bCnt = 0
		} else {
			res = append(res, arrB[j])
			j++

			aCnt = 0
			bCnt++
		}
	}

	//for i < len(arrA) && aCnt != k {
	//	res = append(res, arrA[i])
	//	i++
	//
	//	aCnt++
	//}
	//
	//for j < len(arrB) && bCnt != k {
	//	res = append(res, arrB[j])
	//	j++
	//
	//	bCnt++
	//}

	fmt.Fprintln(writer, string(res))
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

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

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func sum(nums ...int) (sum int) {
	for _, num := range nums {
		sum += num
	}
	return
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int64) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := int64(5); i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int64) []int64 {
	factors := make([]int64, 0)

	for ftr := int64(2); ftr*ftr <= num; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > 1 {
		factors = append(factors, num)
	}

	return factors
}

package main

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

type CF1689A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1689A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1689A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1689A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1689A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1689A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1689A
Date: 2/10/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1689/A
Problem: CF1689A
**/
func (in *CF1689A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n, m, k := in.NextInt(), in.NextInt(), in.NextInt()
		g := in.NextString()
		h := in.NextString()

		a := make([]uint8, n)
		b := make([]uint8, m)

		for i := 0; i < n; i++ {
			a[i] = g[i]
		}

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

		for i := 0; i < m; i++ {
			b[i] = h[i]
		}

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

		sol := ""
		for i, j, p, q := 0, 0, 0, 0; ; {
			x := uint8('-')
			if i < n {
				x = a[i]
			}

			y := uint8('-')
			if j < m {
				y = b[j]
			}
			if x != '-' && y != '-' {
				if x < y {
					if p < k {
						sol += string(rune(x))
						p++
						q = 0
						i++
					} else {
						sol += string(rune(y))
						p = 0
						q = 1
						j++
					}
				} else {
					if q < k {
						sol += string(rune(y))
						q++
						j++
						p = 0
					} else {
						sol += string(rune(x))
						q = 0
						p = 1
						i++
					}
				}
			} else {
				break
			}
		}
		fmt.Println(sol)

	}
}

func NewCF1689A(r *bufio.Reader) *CF1689A {
	return &CF1689A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1689A(bufio.NewReader(os.Stdin)).Run()
}

package main

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var ntests int
	fmt.Fscan(scanner, &ntests)
	for iter := 0; iter < ntests; iter++ {
		var n, m, k int
		fmt.Fscan(scanner, &n, &m, &k)
		var rs1, rs2 string
		fmt.Fscan(scanner, &rs1, &rs2)
		s1 := []byte(rs1)
		s2 := []byte(rs2)
		sort.Slice(s1, func(i, j int) bool { return s1[i] < s1[j] })
		sort.Slice(s2, func(i, j int) bool { return s2[i] < s2[j] })
		res := make([]byte, n+m-1)
		last, reps := 1, 0
		var i int
		for i = 0; len(s1)*len(s2) != 0; i++ {
			if s1[0] <= s2[0] {
				if reps != k {
					if last == 1 {
						reps++
					} else {
						last, reps = 1, 1
					}
					res[i] = s1[0]
					s1 = s1[1:]
				} else {
					if last == 2 {
						last, reps = 1, 1
						res[i] = s1[0]
						s1 = s1[1:]
					} else {
						last, reps = 2, 1
						res[i] = s2[0]
						s2 = s2[1:]
					}
				}
			} else {
				if reps != k {
					if last == 2 {
						reps++
					} else {
						last, reps = 2, 1
					}
					res[i] = s2[0]
					s2 = s2[1:]
				} else {
					if last == 1 {
						last, reps = 2, 1
						res[i] = s2[0]
						s2 = s2[1:]
					} else {
						last, reps = 1, 1
						res[i] = s1[0]
						s1 = s1[1:]
					}
				}
			}
		}
		for j := 0; j < i; j++ {
			fmt.Fprintf(writer, "%c", res[j])
		}
		fmt.Fprintln(writer)
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func gi2() (int,int) { return gi(),gi() }
func gi3() (int,int,int) { return gi(),gi(),gi() }
func gi4() (int,int,int,int) { return gi(),gi(),gi(),gi() }
func gis(n int) []int  { res := make([]int,n); for i:=0;i<n;i++ { res[i] = gi() }; return res }
func gf() float64 { f,e := strconv.ParseFloat(gs(),64); if e != nil {panic(e)}; return f }
func gbs() []byte { return []byte(gs()) }
func gfs(n int) []float64  { res := make([]float64,n); for i:=0;i<n;i++ { res[i] = gf() }; return res }
func gss(n int) []string  { res := make([]string,n); for i:=0;i<n;i++ { res[i] = gs() }; return res }
func ia(m int) []int { return make([]int,m) }
func iai(m int,v int) []int { a := make([]int,m); for i:=0;i<m;i++ { a[i] = v }; return a }
func twodi(n int,m int,v int) [][]int {
	r := make([][]int,n); for i:=0;i<n;i++ { x := make([]int,m); for j:=0;j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill2(m int) ([]int,[]int) { a,b := ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i] = gi(),gi()}; return a,b }
func fill3(m int) ([]int,[]int,[]int) { a,b,c := ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i] = gi(),gi(),gi()}; return a,b,c }
func fill4(m int) ([]int,[]int,[]int,[]int) { a,b,c,d := ia(m),ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i],d[i] = gi(),gi(),gi(),gi()}; return a,b,c,d }
func abs(a int) int { if a < 0 { return -a }; return a }
func rev(a []int) { i,j := 0,len(a)-1; for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
func max(a,b int) int { if a > b { return a }; return b }
func min(a,b int) int { if a > b { return b }; return a }
func tern(cond bool, a int, b int) int { if cond { return a }; return b }
func terns(cond bool, a string, b string) string { if cond { return a }; return b }
func maxarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr(a []int) int { ans := 0; for _,aa := range(a) { ans += aa }; return ans }
func zeroarr(a []int) { for i:=0; i<len(a); i++ { a[i] = 0 } }
func powmod(a,e,mod int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint(a,e int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd(a,b int) int { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended(a,b int) (int,int,int) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv(a,m int) (int,bool) { g,x,_ := gcdExtended(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func makefact(n int,mod int) ([]int,[]int) {
	fact,factinv := make([]int,n+1),make([]int,n+1)
	fact[0] = 1; for i:=1;i<=n;i++ { fact[i] = fact[i-1] * i % mod }
	factinv[n] = powmod(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * (i+1) % mod }
	return fact,factinv
}
func vecintstring(a []int) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.Itoa(a) }; return strings.Join(astr," ") }
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N,M,K := gi(),gi(),gi(); A := gbs(); B := gbs()
		sort.Slice(A,func(i,j int) bool { return A[i] < A[j] } )
		sort.Slice(B,func(i,j int) bool { return B[i] < B[j] } )
		C := make([]byte,0,M+N); last := -1; lastcnt := 0; aidx := 0; bidx := 0
		for {
			if lastcnt == K && last == 0 {
				C = append(C,B[bidx]); bidx++; last,lastcnt = 1,1; if bidx == M { break }
			} else if lastcnt == K && last == 1 {
				C = append(C,A[aidx]); aidx++; last,lastcnt = 0,1; if aidx == N { break }
			} else if A[aidx] < B[bidx] {
				C = append(C,A[aidx]); aidx++; if last == 0 { lastcnt++ } else { last,lastcnt = 0,1 }; if aidx == N { break }
			} else {
				C = append(C,B[bidx]); bidx++; if last == 1 { lastcnt++ } else { last,lastcnt = 1,1 }; if bidx == M { break }
			}
		}
		fmt.Fprintln(wrtr,string(C))
	}
}

package main

import (
	"fmt"
)

func main() {
	var N int
	fmt.Scan(&N)

	for i := 0; i < N; i++ {
		var n, m, k int
		fmt.Scan(&n, &m, &k)
		var sn, sm []byte
		fmt.Scan(&sn, &sm)

		var n0, m0, kn, km int
		for n0 < n && m0 < m {
			nmin := sn[n0]
			mmin := sm[m0]
			for ni := n0; ni < n; ni++ {
				if sn[ni] < nmin {
					nmin = sn[ni]
					sn[ni] = sn[n0]
					sn[n0] = nmin
				}
			}
			for mi := m0; mi < m; mi++ {
				if sm[mi] < mmin {
					mmin = sm[mi]
					sm[mi] = sm[m0]
					sm[m0] = mmin
				}
			}
			if (km == k) || (nmin < mmin && kn < k) {
				fmt.Printf("%c", nmin)
				n0++
				kn++
				km = 0
			} else if (kn == k) || (nmin > mmin && km < k) {
				fmt.Printf("%c", mmin)
				m0++
				km++
				kn = 0
			}
		}
		fmt.Println()
	}
}

package main

import (
	"fmt"
	"sort"
	"strings"
)

func printslice(a []string) {
	for _, v := range a {
		fmt.Printf("%s\n", v)
	}
}

func fillSlice(a []string, n int) []string {
	var tmp string
	fmt.Scan(&tmp)
	for i := 0; i < len(tmp); i++ {
		a = append(a, string(tmp[i]))
	}

	return a
}

func solution() {
	results := make([]string, 0)
	var t, n, m, k int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		this_solution := make([]string, 0)
		fmt.Scan(&n, &m, &k)
		a := make([]string, 0)
		b := make([]string, 0)
		a = fillSlice(a, n)
		b = fillSlice(b, m)
		sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })
		sort.Slice(b, func(i, j int) bool { return b[i] < b[j] })

		var i, j, ka, kb int

		for i < n && j < m {
			if a[i] < b[j] {
				if ka < k {
					this_solution = append(this_solution, a[i])
					ka++
					kb = 0
					i++
				} else {
					this_solution = append(this_solution, b[j])
					ka = 0
					kb++
					j++
				}
			} else {
				if kb < k {
					this_solution = append(this_solution, b[j])
					ka = 0
					kb++
					j++
				} else {
					this_solution = append(this_solution, a[i])
					ka++
					kb = 0
					i++
				}
			}
		}
		results = append(results, strings.Join(this_solution, ""))
	}
	printslice(results)

}
func main() {
	solution()
}

package main

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

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, m, k int
		fmt.Fscan(in, &n, &m, &k)

		var s1, s2 string
		fmt.Fscan(in, &s1, &s2)

		m1, m2 := make([]rune, n), make([]rune, m)
		for i, ch := range s1 {
			m1[i] = ch
		}
		for i, ch := range s2 {
			m2[i] = ch
		}

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

		var buf bytes.Buffer
		var c0, c1 int
		var p0, p1 int
		for p0 < n && p1 < m {
			var ch rune
			if m1[p0] < m2[p1] {
				if c0 == k {
					ch = m2[p1]
					p1++
					c0, c1 = 0, 1
				} else {
					ch = m1[p0]
					p0++
					c0, c1 = c0+1, 0
				}
			} else {
				if c1 == k {
					ch = m1[p0]
					p0++
					c0, c1 = 1, 0
				} else {
					ch = m2[p1]
					p1++
					c0, c1 = 0, c1+1
				}
			}

			buf.WriteRune(ch)
		}
		fmt.Fprintln(out, buf.String())
	}
}

package main

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

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

	var testCases int
	Fscan(in, &testCases)

	for c := 0; c < testCases; c++ {
		var n, m, k int
		var a, b string
		Fscan(in, &n, &m, &k)
		Fscan(in, &a)
		Fscan(in, &b)

		Fprintln(out, solve(k, a, b))
	}
}

func solve(k int, a, b string) string {

	s1 := []rune(a)
	s2 := []rune(b)

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

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

	var ans []rune
	c1 := 0
	c2 := 0
	n := len(s1)
	m := len(s2)
	i := 0
	j := 0
	tryAgain := true
	for tryAgain && i < n && j < m {
		tryAgain = false
		if i >= n && c2 < k {
			ans = append(ans, take(s2, j)...)
			j++
			c2++
			c1 = 0
			tryAgain = true
			continue
		}

		if j >= m && c1 < k {
			ans = append(ans, take(s1, i)...)
			i++
			c1++
			c2 = 0
			tryAgain = true
			continue
		}

		if (s1[i] < s2[j] && c1 < k) || (s1[i] > s2[j] && c2 >= k) {
			ans = append(ans, take(s1, i)...)
			i++
			c1++
			c2 = 0
			tryAgain = true
		} else if c2 < k {
			ans = append(ans, take(s2, j)...)
			j++
			c2++
			c1 = 0
			tryAgain = true
		}
	}

	return string(ans)
}

func take(s []rune, idx int) []rune {
	if idx >= len(s) {
		return nil
	}
	return []rune{s[idx]}
}

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


package main

import "fmt"

type WayType bool

func (w WayType) String() string {
	if bool(w) == true {
		return "Rail"
	} else {
		return "Road"
	}
}

const (
	RAIL WayType = true
	ROAD WayType = false

	MAX_DIST = 100100100
)

type Town struct {
	VistTag bool
	MinDist int
}

var way [500][500]WayType
var towns [500]Town

func findMinDistWay(n int, wt WayType, tid int) int {
	if towns[tid].MinDist != 0 {
		return towns[tid].MinDist
	}
	//fmt.Printf("WT=%s - way[%d][1]=%s\n", wt, tid, way[tid][1])
	if way[tid][1] == wt {
		towns[tid].MinDist = 1
		return 1
	}

	towns[tid].VistTag = true
	minDist := MAX_DIST
	for i := 2; i <= n; i++ {
		if towns[i].VistTag {
			continue
		}
		//fmt.Printf("WT=%s -- way[%d][%d]=%s\n", wt, tid, i, way[tid][i])
		if way[tid][i] == wt {
			m := findMinDistWay(n, wt, i)
			if m < 0 {
				continue
			}
			m++
			if m < minDist {
				minDist = m
			}
		}
	}
	towns[tid].VistTag = false
	if minDist == MAX_DIST {
		towns[tid].MinDist = -1
	} else {
		towns[tid].MinDist = minDist
	}
	return towns[tid].MinDist
}

func main() {
	var n, m, x, y int
	fmt.Scan(&n, &m)

	for i := 0; i < m; i++ {
		fmt.Scan(&x, &y)
		way[x][y] = RAIL
		way[y][x] = RAIL
	}

	var ans int
	if way[1][n] == RAIL {
		//fmt.Println("WTF RAIL")
		ans = findMinDistWay(n, ROAD, n)
	} else {
		//fmt.Println("WTF ROAD")
		ans = findMinDistWay(n, RAIL, n)
	}
	if ans < 0 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

package main

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

type node struct {
	children [] int
	index    int
}

func main() {
	var n, k int
	fmt.Scan(&n, &k)

	graph := make([]node, n)
	for i, _ := range graph {
		graph[i] = node{index: i}
	}

	scan := bufio.NewScanner(os.Stdin)
	scan.Split(bufio.ScanWords)
	for i := 0; i < k; i++ {
		scan.Scan()
		from, _ := strconv.Atoi(scan.Text())
		from--

		scan.Scan()
		to, _ := strconv.Atoi(scan.Text())
		to--

		graph[from].children = append(graph[from].children, to)
		graph[to].children = append(graph[to].children, from)
	}

	minRailWay := getMinRailWay(graph)
	if minRailWay == 0 {
		fmt.Println(-1)
		return
	}

	minRoadWay := getMinRoadWay(graph)
	if minRoadWay == 0 {
		fmt.Println(-1)
		return
	}

	fmt.Println(getMax(minRailWay, minRoadWay))
}

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

func getMinRoadWay(graph [] node) int {
	distances := make([]int, len(graph))
	BFS_road(graph, distances)
	return distances[len(graph)-1]
}

func BFS_road(graph [] node, distances [] int) {
	visited := make([]bool, len(graph))
	queue := make([]int, 0)
	queue = append(queue, 0)

	for len(queue) > 0 {
		x := queue[0]
		visited[x] = true

		for i := 0; i < len(graph); i++ {
			if !contains(graph[x].children, i) && !visited[i] {
				distances[i] = distances[x] + 1
				visited[i] = true
				queue = append(queue, i)
			}
		}
		queue = queue[1:]
	}
}

func contains(array [] int, elem int) bool {
	for _, v := range array {
		if elem == v {
			return true
		}
	}
	return false
}

func getMinRailWay(graph [] node) int {
	distances := make([]int, len(graph))
	BFS(graph, distances)
	return distances[len(graph)-1]
}

func BFS(graph [] node, distances [] int) {
	visited := make([]bool, len(graph))
	queue := make([]int, 0)
	queue = append(queue, 0)

	for len(queue) > 0 {
		x := queue[0]
		visited[x] = true

		for _, v := range graph[x].children {
			if !visited[v] {
				distances[v] = distances[x] + 1
				visited[v] = true
				queue = append(queue, v)
			}
		}
		queue = queue[1:]
	}
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)
//defer writer.Flush()

const (
	//MaxScanTokenSize = 64 * 1024 // package default
	MaxScanTokenSize = 8 * 1024 * 1024 // 8M
)

func init() {
	scanner.Buffer(make([]byte, 0, MaxScanTokenSize), MaxScanTokenSize)
	scanner.Split(bufio.ScanWords)
}

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(size int) []int {
	a := make([]int, size)
	for i := 0; i < size; 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
}

func readFloat64() float64 {
	v, _ := strconv.ParseFloat(readString(), 64)
	return v
}

func readFloat64Array(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = readFloat64()
	}
	return res
}

type Edge struct {
	From int
	To int
	Cap int
	Flow int
}

type Graph struct {
	NNode int
	NEdge int
	Edges []Edge
	Nodes [][]int
}

func NewGraph(nNode, nEdge int) *Graph {
	g := &Graph{
		NNode: nNode,
		NEdge: nEdge,
		Edges: make([]Edge, 0, nEdge),
		Nodes: make([][]int, nNode, nNode),
	}
	return g
}

func (g *Graph) AddEdge(from, to, cap, flow int) {
	g.Nodes[from] = append(g.Nodes[from], len(g.Edges))
	g.Edges = append(g.Edges, Edge{from, to, cap, flow})
	g.Nodes[to] = append(g.Nodes[to], len(g.Edges))
	g.Edges = append(g.Edges, Edge{to, from, cap, flow})
}

func (g *Graph) Show() {
	fmt.Printf("n node = %d, n edge = %d\n", g.NNode, g.NEdge)
	for i, cur := range g.Nodes {
		fmt.Printf("[%d]", i)
		for _, next := range cur {
			fmt.Printf(" %d", g.Edges[next].To)
		}
		fmt.Println()
	}
}

type QueueStack struct {
	data []interface{}
}

func (q *QueueStack) size() int {
	return len(q.data)
}

func (q *QueueStack) push(v interface{}) {
	q.data = append(q.data, v)
}

func (q *QueueStack) popFront() interface{} {
	v := q.data[0]
	q.data = q.data[1:]
	return v
}

func (q *QueueStack) pop() interface{} {
	last := len(q.data) - 1
	v := q.data[last]
	q.data = q.data[:last]
	return v
}

func spfa(g *Graph, from, to int) int {
	n := g.NNode
	dist := make([]int, n, n)
	dist[0] = 0
	for i := 1; i < n; i++ {
		dist[i] = n
	}

	q := &QueueStack{}
	q.push(from)
	for q.size() > 0 {
		cur := q.pop().(int)
		for _, ie := range g.Nodes[cur] {
			e := g.Edges[ie]
			if dist[cur] + 1 < dist[e.To] {
				dist[e.To] = dist[cur] + 1
				q.push(e.To)
			}
		}
	}

	return dist[to]
}

func main() {
	defer writer.Flush()

	n, m := readInt(), readInt()

	gFull := make([][]int, n, n)
	for i := 0; i < n; i++ {
		gFull[i] = make([]int, n, n)
	}

	g := NewGraph(n, m)
	for i := 0; i < m; i++ {
		x, y := readInt(), readInt()
		x--
		y--
		g.AddEdge(x, y, 0, 0)
		gFull[x][y] = 1
		gFull[y][x] = 1
	}

	d1 := spfa(g, 0, n - 1)

	if d1 == n {
		fmt.Fprintf(writer, "-1\n")
		return
	}

	g = NewGraph(n, n * (1 + n) / 2 - m)
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if gFull[i][j] == 0 {
				g.AddEdge(i, j, 0, 0)
			}
		}
	}

	d2 := spfa(g, 0, n - 1)
	if d2 == n {
		fmt.Fprintf(writer, "-1\n")
		return
	}

	ans := d1
	if d1 < d2 {
		ans = d2
	}
	fmt.Fprintf(writer, "%d\n", ans)
}

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

package main

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

type Edge struct {
	from int
	to   int
}

type QueueItem struct {
	town int
	d    int
}

func bfs(n int, matrix [][]int, flag int) int {
	queue := []QueueItem{{1, 0}}
	visited := make(map[int]bool)
	visited[1] = true
	for len(queue) > 0 {
		current := queue[0]
		queue = queue[1:]
		if current.town == n {
			return current.d
		}
		for v := 1; v <= n; v++ {
			if !visited[v] && matrix[current.town-1][v-1] == flag {
				visited[v] = true
				queue = append(queue, QueueItem{v, current.d + 1})
			}
		}
	}
	return -1
}

func createMatrix(n int, edges []Edge) [][]int {
	adjMatrix := make([][]int, n)
	for i := 0; i < n; i++ {
		adjMatrix[i] = make([]int, n)
	}
	for _, edge := range edges {
		adjMatrix[edge.to-1][edge.from-1] = 1
		adjMatrix[edge.from-1][edge.to-1] = 1
	}
	return adjMatrix
}

func Solve(n int, edges []Edge) int {
	matrix := createMatrix(n, edges)
	if matrix[0][n-1] == 1 {
		return bfs(n, matrix, 0)
	}
	return bfs(n, matrix, 1)
}

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

	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	edges := make([]Edge, m)
	for i := 0; i < m; i++ {
		fmt.Fscanf(reader, "%d %d\n", &edges[i].from, &edges[i].to)
	}

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

package main

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

type WayType bool

func (w WayType) String() string {
	if bool(w) == true {
		return "Rail"
	} else {
		return "Road"
	}
}

const (
	RAIL WayType = true
	ROAD WayType = false

	MAX_DIST = 100100100
)

type Town struct {
	VistTag bool
	MinDist int
}

var way [500][500]WayType
var towns [500]Town

func findMinDistWay(n int, wt WayType, tid int) int {
	if towns[tid].MinDist != 0 {
		return towns[tid].MinDist
	}
	//fmt.Printf("WT=%s - way[%d][1]=%s\n", wt, tid, way[tid][1])
	if way[tid][1] == wt {
		towns[tid].MinDist = 1
		return 1
	}

	towns[tid].VistTag = true
	minDist := MAX_DIST
	for i := 2; i <= n; i++ {
		if towns[i].VistTag {
			continue
		}
		//fmt.Printf("WT=%s -- way[%d][%d]=%s\n", wt, tid, i, way[tid][i])
		if way[tid][i] == wt {
			m := findMinDistWay(n, wt, i)
			if m < 0 {
				continue
			}
			m++
			if m < minDist {
				minDist = m
			}
		}
	}
	towns[tid].VistTag = false
	if minDist == MAX_DIST {
		towns[tid].MinDist = -1
	} else {
		towns[tid].MinDist = minDist
	}
	return towns[tid].MinDist
}

func main() {
	var n, m, x, y int
	in := bufio.NewReader(os.Stdin)

	fmt.Fscan(in, &n, &m)

	for i := 0; i < m; i++ {
		fmt.Fscan(in, &x, &y)
		way[x][y] = RAIL
		way[y][x] = RAIL
	}

	var ans int
	if way[1][n] == RAIL {
		//fmt.Println("WTF RAIL")
		ans = findMinDistWay(n, ROAD, n)
	} else {
		//fmt.Println("WTF ROAD")
		ans = findMinDistWay(n, RAIL, n)
	}
	if ans < 0 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)
//defer writer.Flush()

const (
	//MaxScanTokenSize = 64 * 1024 // package default
	MaxScanTokenSize = 8 * 1024 * 1024 // 8M
)

func init() {
	scanner.Buffer(make([]byte, 0, MaxScanTokenSize), MaxScanTokenSize)
	scanner.Split(bufio.ScanWords)
}

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(size int) []int {
	a := make([]int, size)
	for i := 0; i < size; 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
}

func readFloat64() float64 {
	v, _ := strconv.ParseFloat(readString(), 64)
	return v
}

func readFloat64Array(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = readFloat64()
	}
	return res
}

type Edge struct {
	From int
	To int
	Cap int
	Flow int
}

type Graph struct {
	NNode int
	NEdge int
	Edges []Edge
	Nodes [][]int
}

func NewGraph(nNode, nEdge int) *Graph {
	g := &Graph{
		NNode: nNode,
		NEdge: nEdge,
		Edges: make([]Edge, 0, nEdge),
		Nodes: make([][]int, nNode, nNode),
	}
	return g
}

func (g *Graph) AddEdge(from, to, cap, flow int) {
	g.Nodes[from] = append(g.Nodes[from], len(g.Edges))
	g.Edges = append(g.Edges, Edge{from, to, cap, flow})
	g.Nodes[to] = append(g.Nodes[to], len(g.Edges))
	g.Edges = append(g.Edges, Edge{to, from, cap, flow})
}

func (g *Graph) Show() {
	fmt.Printf("n node = %d, n edge = %d\n", g.NNode, g.NEdge)
	for i, cur := range g.Nodes {
		fmt.Printf("[%d]", i)
		for _, next := range cur {
			fmt.Printf(" %d", g.Edges[next].To)
		}
		fmt.Println()
	}
}

type QueueStack struct {
	data []interface{}
}

func (q *QueueStack) size() int {
	return len(q.data)
}

func (q *QueueStack) push(v interface{}) {
	q.data = append(q.data, v)
}

func (q *QueueStack) popFront() interface{} {
	v := q.data[0]
	q.data = q.data[1:]
	return v
}

func (q *QueueStack) pop() interface{} {
	last := len(q.data) - 1
	v := q.data[last]
	q.data = q.data[:last]
	return v
}

func spfa(g *Graph, from, to int) int {
	n := g.NNode
	dist := make([]int, n, n)
	dist[0] = 0
	for i := 1; i < n; i++ {
		dist[i] = n
	}

	q := &QueueStack{}
	q.push(from)
	for q.size() > 0 {
		cur := q.pop().(int)
		for _, ie := range g.Nodes[cur] {
			e := g.Edges[ie]
			if dist[cur] + 1 < dist[e.To] {
				dist[e.To] = dist[cur] + 1
				q.push(e.To)
			}
		}
	}

	return dist[to]
}

func main() {
	defer writer.Flush()

	n, m := readInt(), readInt()

	gFull := make([][]int, n, n)
	for i := 0; i < n; i++ {
		gFull[i] = make([]int, n, n)
	}

	g := NewGraph(n, m)
	for i := 0; i < m; i++ {
		x, y := readInt(), readInt()
		x--
		y--
		g.AddEdge(x, y, 0, 0)
		gFull[x][y] = 1
		gFull[y][x] = 1
	}
	g.Show()

	d1 := spfa(g, 0, n - 1)

	if d1 == n {
		fmt.Fprintf(writer, "-1\n")
		return
	}

	g = NewGraph(n, n * (1 + n) / 2 - m)
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if gFull[i][j] == 0 {
				g.AddEdge(i, j, 0, 0)
			}
		}
	}

	d2 := spfa(g, 0, n - 1)
	if d2 == n {
		fmt.Fprintf(writer, "-1\n")
		return
	}

	ans := d1
	if d1 < d2 {
		ans = d2
	}
	fmt.Fprintf(writer, "%d\n", ans)
}


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


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


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

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 (
	"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() {
	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"
	"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 (
	"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 (
	"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++
		}
	}
}