Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He was so sad that he punched some kind of scoreboard with numbers. The numbers are displayed in the same way as on an electronic clock: each digit position consists of $$$7$$$ segments, which can be turned on or off to display different numbers. The picture shows how all $$$10$$$ decimal digits are displayed:   After the punch, some segments stopped working, that is, some segments might stop glowing if they glowed earlier. But Denis remembered how many sticks were glowing and how many are glowing now. Denis broke exactly $$$k$$$ segments and he knows which sticks are working now. Denis came up with the question: what is the maximum possible number that can appear on the board if you turn on exactly $$$k$$$ sticks (which are off now)? It is allowed that the number includes leading zeros.

The first line contains integer $$$n$$$ $$$(1 \leq n \leq 2000)$$$  — the number of digits on scoreboard and $$$k$$$ $$$(0 \leq k \leq 2000)$$$  — the number of segments that stopped working. The next $$$n$$$ lines contain one binary string of length $$$7$$$, the $$$i$$$-th of which encodes the $$$i$$$-th digit of the scoreboard. Each digit on the scoreboard consists of $$$7$$$ segments. We number them, as in the picture below, and let the $$$i$$$-th place of the binary string be $$$0$$$ if the $$$i$$$-th stick is not glowing and $$$1$$$ if it is glowing. Then a binary string of length $$$7$$$ will specify which segments are glowing now.    Thus, the sequences "1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011" encode in sequence all digits from $$$0$$$ to $$$9$$$ inclusive.

Output a single number consisting of $$$n$$$ digits  — the maximum number that can be obtained if you turn on exactly $$$k$$$ sticks or $$$-1$$$, if it is impossible to turn on exactly $$$k$$$ sticks so that a correct number appears on the scoreboard digits.

NoteIn the first test, we are obliged to include all $$$7$$$ sticks and get one $$$8$$$ digit on the scoreboard.In the second test, we have sticks turned on so that units are formed. For $$$5$$$ of additionally included sticks, you can get the numbers $$$07$$$, $$$18$$$, $$$34$$$, $$$43$$$, $$$70$$$, $$$79$$$, $$$81$$$ and $$$97$$$, of which we choose the maximum  — $$$97$$$.In the third test, it is impossible to turn on exactly $$$5$$$ sticks so that a sequence of numbers appears on the scoreboard.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1341D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	ds := [10]string{"1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"}

	var n, k int
	var s []byte
	Fscan(in, &n, &k)
	a := make([][10]int, n)
	for i := range a {
		Fscan(in, &s)
		for j, d := range ds {
			for k, b := range s {
				if b > d[k] {
					a[i][j] = 1e9
					break
				}
				a[i][j] += int(d[k] - b)
			}
		}
	}

	dp := make([][]int8, n)
	for i := range dp {
		dp[i] = make([]int8, k+1)
		for j := range dp[i] {
			dp[i][j] = -1
		}
	}
	ans := make([]byte, n)
	var f func(int, int) int8
	f = func(p, left int) (res int8) {
		if p >= n {
			if left > 0 {
				return
			}
			return 1
		}
		v := &dp[p][left]
		if *v >= 0 {
			return *v
		}
		defer func() { *v = res }()
		for i := 9; i >= 0; i-- {
			if a[p][i] <= left {
				ans[p] = byte('0' + i)
				if f(p+1, left-a[p][i]) == 1 {
					return 1
				}
			}
		}
		return
	}
	if f(0, k) == 0 {
		Fprint(_w, -1)
	} else {
		Fprint(_w, string(ans))
	}
}

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

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

var digits = []string{"1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"}

func main() {
	defer writer.Flush()
	n, k := reader.NextInt64(), reader.NextInt64()
	ss := make([]string, n)
	for i := int64(0); i < n; i++ {
		ss[i] = reader.NextString()
	}
	writer.Printf("%s\n", sol(k, ss))
}

func sol(k int64, ss []string) string {
	dist := make([][10]int64, len(ss))
	for i := range ss {
		for di, d := range digits {
			for j := range d {
				if ss[i][j] == '1' && d[j] == '0' {
					// not possible
					dist[i][di] = -1
					break
				}
				if ss[i][j] == '0' && d[j] == '1' {
					dist[i][di]++
				}
			}
		}
	}

	dp := make([][]bool, len(ss)+1)
	for i := range dp {
		dp[i] = make([]bool, k+1)
	}
	dp[len(ss)][0] = true
	for i := int64(len(ss)); i > 0; i-- {
		for j := int64(0); j <= k; j++ {
			if dp[i][j] {
				for d := range digits {
					nextDist := dist[i-1][d]
					if nextDist == -1 {
						continue
					}
					if j+nextDist <= k {
						dp[i-1][j+nextDist] = true
					}
				}
			}
		}
	}

	if !dp[0][k] {
		return "-1"
	}

	res := ""
	for i := 0; i < len(dp)-1; i++ {
		for d := int64(9); d >= 0; d-- {
			if dist[i][d] != -1 && k >= dist[i][d] && dp[i+1][k-dist[i][d]] {
				res += string(d + '0')
				k -= dist[i][d]
				break
			}
		}
	}
	if res == "" {
		return "-1"
	}
	return res
}

package main

import (
	"fmt"
	"sort"
)

type data struct {
	id int
	w  int
}
type datas []data

func (arr datas) Len() int {
	return len(arr)
}
func (arr datas) Less(i, j int) bool {
	return arr[i].id > arr[j].id
}

func (arr datas) Swap(i, j int) {
	arr[i], arr[j] = arr[j], arr[i]
}

var f [2002][2002]int
var a [2002]int
var s string
var nw = [11]int{119, 18, 93, 91, 58, 107, 111, 82, 127, 123}
var D [128]datas
var ans [2002]int

func init_() {
	var base [8]int
	for num := 0; num < 128; num++ {
		for i := 0; i < 7; i++ {
			if (num & (1 << i)) == 0 {
				base[i] = 0
			} else {
				base[i] = 1
			}
		}
		for k := 0; k <= 9; k++ {
			sum := 0
			for i := 0; i < 7; i++ {
				if (nw[k]&(1<<i)) == 0 && base[i] == 1 {
					sum = -1
					break
				}
				if (nw[k]&(1<<i)) > 0 && base[i] == 0 {
					sum++
				}
			}
			if sum >= 0 {
				D[num] = append(D[num], data{k, sum})
			}
		}
		if len(D[num]) > 0 {
			sort.Sort(D[num])
		}
	}

	for i := 0; i <= 2000; i++ {
		for j := 0; j <= 2000; j++ {
			f[i][j] = -1
		}
	}
}

func find(n int, i int, k int) bool {
	if i > n {
		return k == 0
	}
	if f[i][k] >= 0 {
		return f[i][k] == 1
	}
	for _, dt := range D[a[i]] {
		if k >= dt.w && find(n, i+1, k-dt.w) {
			ans[i] = dt.id
			f[i][k] = 1
			return true
		}
	}
	f[i][k] = 0
	return false
}

func main() {
	var n, k int
	init_()

	fmt.Scanf("%d %d\n", &n, &k)
	for i := 1; i <= n; i++ {
		fmt.Scanf("%s\n", &s)
		num := 0
		for j := 0; j < 7; j++ {
			if s[j] == '1' {
				num += 1
			}
			num <<= 1
		}
		num >>= 1
		a[i] = num
	}

	/*
		for i := 1; i <= n; i++ {
			fmt.Printf("%d\n", i)
			for _, dt := range D[a[i]] {
				fmt.Printf("%d %d\n", dt.id, dt.w)
			}
		}
		for i := 1; i <= n; i++ {
			for j := 0; j <= k; j++ {
				fmt.Printf("f[%d][%d]=%d\n", i, j, f[i][j])
			}
		}
	*/

	res := find(n, 1, k)
	if res {
		for i := 1; i <= n; i++ {
			fmt.Printf("%d", ans[i])
		}
		fmt.Printf("\n")
	} else {
		fmt.Printf("-1\n")
	}

}

/*
URL:
https://codeforces.com/problemset/problem/1340/B
*/

package main

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

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*******************************************************************/

const (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

var (
	n, k int
	D    []string

	dpf     [2000 + 50][2000 + 50]bool
	samples [10]string
)

func main() {
	n, k = ReadInt2()
	for i := 0; i < n; i++ {
		str := ReadString()
		D = append(D, str)
	}
	D = ReverseStrs(D)

	samples = [10]string{
		"1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011",
	}

	dpf[0][0] = true
	for i := 0; i < n; i++ {
		nums := [10]int{}
		for d := 0; d < 10; d++ {
			nums[d] = -1
		}

		str := D[i]
		for d := 0; d < 10; d++ {
			to := samples[d]
			ok, num := canMake(str, to)
			if ok {
				nums[d] = num
			}
		}
		// PrintfDebug("from: %s, nums: %v\n", str, nums)

		// jは遷移元
		for j := 0; j <= k; j++ {
			if !dpf[i][j] {
				continue
			}

			for d := 0; d < 10; d++ {
				if nums[d] < 0 {
					continue
				}

				num := nums[d]
				dpf[i+1][j+num] = true
			}
		}
	}

	if dpf[n][k] {
		answers := []rune{}
		nokori := k
		for i := n - 1; i >= 0; i-- {
			nums := [10]int{}
			for d := 0; d < 10; d++ {
				nums[d] = -1
			}

			str := D[i]
			for d := 0; d < 10; d++ {
				to := samples[d]
				ok, num := canMake(str, to)
				if ok {
					nums[d] = num
				}
			}

			maxi := 0
			for d := 0; d < 10; d++ {
				num := nums[d]
				if num >= 0 && nokori-num >= 0 {
					if dpf[i][nokori-num] {
						maxi = d
					}
				}
			}
			nokori -= nums[maxi]

			answers = append(answers, '0'+rune(maxi))
		}

		// fmt.Println(string(Reverse(answers)))
		fmt.Println(string(answers))
	} else {
		fmt.Println(-1)
	}
}

func Reverse(A []rune) []rune {
	res := []rune{}

	n := len(A)
	for i := n - 1; i >= 0; i-- {
		res = append(res, A[i])
	}

	return res
}

func ReverseStrs(A []string) []string {
	res := []string{}

	n := len(A)
	for i := n - 1; i >= 0; i-- {
		res = append(res, A[i])
	}

	return res
}

// func main() {
// 	n, k = ReadInt2()
// 	for i := 0; i < n; i++ {
// 		str := ReadString()
// 		D = append(D, str)
// 	}
// 	samples = [10]string{
// 		"1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011",
// 	}
// 	// for d := 0; d < 10; d++ {
// 	// 	_, num := canMake("1000000", samples[d])
// 	// 	PrintfDebug("digit %d: %d\n", d, num)
// 	// }

// 	dpf[0][0] = true
// 	for i := 0; i < n; i++ {
// 		nums := [10]int{}
// 		for d := 0; d < 10; d++ {
// 			nums[d] = -1
// 		}

// 		str := D[i]
// 		for d := 0; d < 10; d++ {
// 			to := samples[d]
// 			ok, num := canMake(str, to)
// 			if ok {
// 				nums[d] = num
// 			}
// 		}
// 		// PrintfDebug("from: %s, nums: %v\n", str, nums)

// 		// jは遷移元
// 		for j := 0; j <= k; j++ {
// 			if !dpf[i][j] {
// 				continue
// 			}

// 			for d := 0; d < 10; d++ {
// 				if nums[d] < 0 {
// 					continue
// 				}

// 				num := nums[d]
// 				dstr := strconv.Itoa(d)
// 				aft := dp[i][j] + dstr
// 				if len(dp[i][j]) == i && dp[i+1][j+num] < aft {
// 					dp[i+1][j+num] = aft
// 					dpf[i+1][j+num] = true
// 					// PrintfDebug("aft: %s, bef: %s\n", dp[i+1][j+num], dp[i][j])
// 				}
// 			}
// 		}
// 	}

// 	// for i := 0; i <= n; i++ {
// 	// 	for j := 0; j <= k; j++ {
// 	// 		PrintfDebug("dp[%d][%d]: %s\n", i, j, dp[i][j])
// 	// 	}
// 	// }

// 	if len(dp[n][k]) == n {
// 		fmt.Println(dp[n][k])
// 	} else {
// 		fmt.Println(-1)
// 	}
// }

func canMake(from, to string) (bool, int) {
	res := 0
	for i := 0; i < len(from); i++ {
		if from[i] == '1' && to[i] == '0' {
			return false, -1
		}
		if from[i] == '0' && to[i] == '1' {
			res++
		}
	}

	return true, res
}

/*******************************************************************/

/*********** I/O ***********/

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

func readInt64() int64 {
	i, err := strconv.ParseInt(ReadString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// ReadIntSlice returns an integer slice that has n integers.
func ReadIntSlice(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt()
	}
	return b
}

// ReadInt64Slice returns as int64 slice that has n integers.
func ReadInt64Slice(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt64()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Debugging ***********/

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

package main

import (
	"fmt"
	"sort"
)

type data struct {
	id int
	w  int
}
type datas []data

func (arr datas) Len() int {
	return len(arr)
}
func (arr datas) Less(i, j int) bool {
	return arr[i].id > arr[j].id
}

func (arr datas) Swap(i, j int) {
	arr[i], arr[j] = arr[j], arr[i]
}

var f [2002][2002]int
var a [2002]int
var s string
var nw = [11]int{119, 18, 93, 91, 58, 107, 111, 82, 127, 123}
var D [128]datas
var ans [2002]int

func init_() {
	var base [8]int
	for num := 0; num < 128; num++ {
		for i := 0; i < 7; i++ {
			if (num & (1 << i)) == 0 {
				base[i] = 0
			} else {
				base[i] = 1
			}
		}
		for k := 0; k <= 9; k++ {
			sum := 0
			for i := 0; i < 7; i++ {
				if (nw[k]&(1<<i)) == 0 && base[i] == 1 {
					sum = -1
					break
				}
				if (nw[k]&(1<<i)) > 0 && base[i] == 0 {
					sum++
				}
			}
			if sum >= 0 {
				D[num] = append(D[num], data{k, sum})
			}
		}
		if len(D[num]) > 0 {
			sort.Sort(D[num])
		}
	}

	for i := 1; i <= 2000; i++ {
		for j := 1; j <= 2000; j++ {
			f[i][j] = -1
		}
	}
	f[0][0] = -1
}

func find(n int, k int) bool {
	if n == 0 {
		return k == 0
	}
	if f[n][k] >= 0 {
		return f[n][k] == 1
	}
	for _, dt := range D[a[n]] {
		if k >= dt.w && find(n-1, k-dt.w) {
			ans[n] = dt.id
			f[n][k] = 1
			return true
		}
	}
	f[n][k] = 0
	return false
}

func main() {
	var n, k int
	init_()

	fmt.Scanf("%d %d\n", &n, &k)
	for i := 1; i <= n; i++ {
		fmt.Scanf("%s\n", &s)
		num := 0
		for j := 0; j < 7; j++ {
			if s[j] == '1' {
				num += 1
			}
			num <<= 1
		}
		num >>= 1
		a[i] = num
	}

	res := find(n, k)
	if res {
		for i := n; i >= 1; i-- {
			fmt.Printf("%d", ans[i])
		}
		fmt.Printf("\n")
	} else {
		fmt.Printf("-1\n")
	}
}


In the Bus of Characters there are $$$n$$$ rows of seat, each having $$$2$$$ seats. The width of both seats in the $$$i$$$-th row is $$$w_i$$$ centimeters. All integers $$$w_i$$$ are distinct.Initially the bus is empty. On each of $$$2n$$$ stops one passenger enters the bus. There are two types of passengers:   an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it;  an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it. You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of rows in the bus. The second line contains the sequence of integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le 10^{9}$$$), where $$$w_i$$$ is the width of each of the seats in the $$$i$$$-th row. It is guaranteed that all $$$w_i$$$ are distinct. The third line contains a string of length $$$2n$$$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $$$j$$$-th character is '0', then the passenger that enters the bus on the $$$j$$$-th stop is an introvert. If the $$$j$$$-th character is '1', the the passenger that enters the bus on the $$$j$$$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $$$n$$$), and for each extrovert there always is a suitable row.

Print $$$2n$$$ integers — the rows the passengers will take. The order of passengers should be the same as in input.

NoteIn the first example the first passenger (introvert) chooses the row $$$2$$$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $$$1$$$, because it is the only empty row now. The third passenger (extrovert) chooses the row $$$1$$$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $$$2$$$, because it is the only row with an empty place.

package main

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

type row struct {
	width int
	row   int
}
type rowSorter []row

func (slice rowSorter) Len() int {
	return len(slice)
}

func (slice rowSorter) Less(i, j int) bool {
	return slice[i].width < slice[j].width
}

func (slice rowSorter) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

func main() {
	/*xm := map[int]struct{}{}
	fmt.Println(200000)
	for i := 0; i < 200000; i++ {
		ok := true
		var z int
		for ok == true {
			z = rand.Intn(50000000)
			_, ok = xm[z]
		}
		fmt.Printf("%d ", z)
	}
	fmt.Println()
	for i := 0; i < 200000; i++ {
		fmt.Print("0")
	}
	for i := 0; i < 200000; i++ {
		fmt.Print("1")
	}
	os.Exit(0)
	*/
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]byte, 100*1024*1024), 100*1024*1024)

	scanner.Scan()
	var x int
	fmt.Sscan(scanner.Text(), &x)

	scanner.Scan()
	s := strings.Split(scanner.Text(), " ")
	w := make([]row, x)
	for i, v := range s {
		vv, _ := strconv.Atoi(v)
		w[i] = row{vv, i + 1}
	}
	sort.Sort(rowSorter(w))
	ext := make([]int, x)
	count := 0
	windex := 0
	scanner.Scan()
	out := make([]string, x*2)
	ocount := 0
	for i, v := range scanner.Text() {

		if v == 48 {
			out[ocount] = (strconv.Itoa(w[windex].row))
			ocount++
			if i < ((2 * x) - 1) {
				fmt.Print(" ")
			}
			ext[count] = w[windex].row
			count++
			windex++
		} else if v == 49 {
			out[ocount] = (strconv.Itoa(ext[count-1]))
			ocount++
			if i < ((2 * x) - 1) {
				fmt.Print(" ")
			}
			count -= 1
		}
	}
	fmt.Println(strings.Join(out, " "))
}

package main

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

type row struct {
	width int
	row   int
}
type rowSorter []row

func (slice rowSorter) Len() int {
	return len(slice)
}

func (slice rowSorter) Less(i, j int) bool {
	return slice[i].width < slice[j].width
}

func (slice rowSorter) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

func main() {
	var x int
	fmt.Scan(&x)
	w := make([]row, x)
	for i := range w {
		var vv int
		fmt.Scan(&vv)
		w[i] = row{vv, i + 1}
	}

	sort.Sort(rowSorter(w))

	ext := []int{}
	in := bufio.NewReader(os.Stdin)
	for i := 0; i < 2*x; i++ {
		v, _ := in.ReadByte()
		if v == 48 {
			fmt.Print(strconv.Itoa(w[0].row))
			if i < ((2 * x) - 1) {
				fmt.Print(" ")
			}
			ext = append(ext, w[0].row)
			w = w[1:]
		} else if v == 49 {
			fmt.Print(strconv.Itoa(ext[len(ext)-1]))
			if i < ((2 * x) - 1) {
				fmt.Print(" ")
			}
			ext = ext[:len(ext)-1]
		}
	}
	fmt.Println()
}


Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.Omkar currently has $$$n$$$ supports arranged in a line, the $$$i$$$-th of which has height $$$a_i$$$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $$$1$$$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $$$1$$$ to each of their heights. Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!An array $$$b$$$ is a subsegment of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.An array $$$b_1, b_2, \dots, b_n$$$ is called nondecreasing if $$$b_i\le b_{i+1}$$$ for every $$$i$$$ from $$$1$$$ to $$$n-1$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of supports Omkar has. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(0 \leq a_{i} \leq 10^9)$$$ — the heights of the supports. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide.

NoteThe subarray with which Omkar performs the operation is bolded.In the first test case:First operation:$$$[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]$$$Second operation:$$$[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]$$$Third operation:$$$[5, \textbf{4}, \textbf{4}, 5] \to [5, \textbf{5}, \textbf{5}, 5]$$$In the third test case, the array is already nondecreasing, so Omkar does $$$0$$$ operations.

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

var err error

func next() (n string) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return ""
		}
	}
}

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextDouble() (n float64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func Fill(a []int, v int) {
	for i := range a {
		a[i] = v
	}
}

func FillB(a []bool, v bool) {
	for i := range a {
		a[i] = v
	}
}

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

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

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

const (
	oo  = 100000000
	mod = 1000000007
)

func mult(a, b int64) int64 {
	return (a * b) % mod
}
func add(a, b int64) int64 {
	return (a + b) % mod
}
func sub(a, b int64) int64 {
	return (a - b + mod) % mod
}

var (
	adj   [][]int
	depth []int
)

func pow(a, b int64) int64 {
	if b == 0 {
		return 1
	}
	res := pow(a, b/2)
	res = mult(res, res)
	if b%2 == 1 {
		res = mult(res, a)
	}
	return res
}

func solve() {
	n := nextInt()
	prev := nextInt()
	var res int64
	for i := 1; i < n; i++ {
		x := nextInt()
		if x < prev {
			res += int64(prev - x)
		}
		prev = x
	}
	printf("%d\n", res)
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	out = bufio.NewWriterSize(os.Stdout, 8192)
	if false {
		file1, err := os.Open("input.txt")
		if err != nil {
			log.Fatal(err)
		}
		file2, err := os.Create("output.txt")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file1, 8192)
		out = bufio.NewWriterSize(file2, 8192)
	}
	defer out.Flush()

	// start := time.Now()

	for t, i := nextInt(), 1; t > 0; t, i = t-1, i+1 {
		// printf("Case %d: ", i)
		solve()
	}

	// printf("%v\n", time.Now().Sub(start))
}

package main

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

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

	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--
		n := readNum(reader)
		A := readNNums(reader, n)
		res := solve(n, A)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}
	fmt.Print(buf.String())
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(n int, A []int) int64 {
	B := make([]int64, n)
	for i := 0; i < n; i++ {
		B[i] = int64(A[i])
	}
	var cnt int64

	for i := 1; i < n; i++ {
		B[i] += cnt
		if B[i] < B[i-1] {
			cnt += B[i-1] - B[i]
			B[i] = B[i-1]
		}
	}

	return cnt
}

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

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buffer := make([]byte, 1024*1024)
	scanner.Buffer(buffer, 3*1024*1024)
	scanner.Split(bufio.ScanWords)

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

	for t := input(); t > 0; t-- {
		n := input()
		a := make([]uint64, n)
		m := make([]uint64, n-1)

		for i := range a {
			a[i] = input()
		}

		var i, cost uint64
		for i = 1; i < n; i++ {
			if a[i] < a[i-1] {
				m[i-1] = a[i-1] - a[i]
			}
		}

		for i := range m {
			cost += m[i]
		}

		fmt.Println(cost)
	}

}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var a, aPrev, n int64
		count := int64(0)
		fmt.Fscan(in, &n)
		for j := int64(0); j < n; j++ {
			aPrev = a
			fmt.Fscan(in, &a)
			if j == 0 {
				continue
			}
			if aPrev > a {
				count += aPrev - a
			}
		}
		fmt.Println(count)
	}
}

package main

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

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	var t, n int

	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var ans int64
		fmt.Fscan(input, &n)
		arr := make([]int64, n)

		for i := 0; i < n; i++ {
			fmt.Fscan(input, &arr[i])

			if i > 0 && arr[i] < arr[i-1] {
				ans += arr[i-1] - arr[i]
			}
		}

		fmt.Println(ans)
	}
}

package main
import (
        "fmt"
        "os"
        "bufio"
)
func main(){
    var t, n, a, b int
    in := bufio.NewReader(os.Stdin)
    out := os.Stdout
    fmt.Fscan(in, &t)
    for ; t > 0; t-- {
        var ans int64 = 0
        fmt.Fscan(in, &n)
        fmt.Fscan(in, &a)
        n--
        for ; n > 0; n-- {
            fmt.Fscan(in, &b)
            if a > b {
                ans += int64(a-b)
            }
            a = b
        }
        fmt.Fprintln(out, ans)
    }
}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

var (
	writer  *bufio.Writer
	scanner *bufio.Scanner
)

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

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

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		n := sint64()
		a := make([]int64, n)
		for i := range a {
			a[i] = sint64()
		}
		printf("%d\n", sol(n, a))
	}
}

func sol(n int64, a []int64) int64 {
	ret := int64(0)
	for i := n-1; i > 0; i-- {
		if a[i] < a[i-1] {
			ret += a[i-1] - a[i]
		}
	}
	return ret
}

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

var err error

func next() (n string) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return ""
		}
	}
}

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextDouble() (n float64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func Fill(a []int, v int) {
	for i := range a {
		a[i] = v
	}
}

func FillB(a []bool, v bool) {
	for i := range a {
		a[i] = v
	}
}

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

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

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

const (
	oo  = 100000000
	mod = 1000000007
)

func mult(a, b int64) int64 {
	return (a * b) % mod
}
func add(a, b int64) int64 {
	return (a + b) % mod
}
func sub(a, b int64) int64 {
	return (a - b + mod) % mod
}

var (
	adj   [][]int
	depth []int
)

func pow(a, b int64) int64 {
	if b == 0 {
		return 1
	}
	res := pow(a, b/2)
	res = mult(res, res)
	if b%2 == 1 {
		res = mult(res, a)
	}
	return res
}

func solve() {
	n := nextInt()
	ranges := [][2]int{}
	min := nextInt()
	max := min
	for i := 1; i < n; i++ {
		x := nextInt()
		if x >= max {
			max = x
		} else {
			ranges = append(ranges, [2]int{min, max})
			min, max = x, x
		}
	}
	ranges = append(ranges, [2]int{min, max})
	res := 0
	for i := len(ranges) - 1; i > 0; i-- {
		add := Max(0, ranges[i-1][1]-ranges[i][0])
		res += add
	}
	printf("%d\n", res)
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	out = bufio.NewWriterSize(os.Stdout, 8192)
	if false {
		file1, err := os.Open("input.txt")
		if err != nil {
			log.Fatal(err)
		}
		file2, err := os.Create("output.txt")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file1, 8192)
		out = bufio.NewWriterSize(file2, 8192)
	}
	defer out.Flush()

	// start := time.Now()

	for t, i := nextInt(), 1; t > 0; t, i = t-1, i+1 {
		// printf("Case %d: ", i)
		solve()
	}

	// printf("%v\n", time.Now().Sub(start))
}

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

var err error

func next() (n string) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return ""
		}
	}
}

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextDouble() (n float64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func Fill(a []int, v int) {
	for i := range a {
		a[i] = v
	}
}

func FillB(a []bool, v bool) {
	for i := range a {
		a[i] = v
	}
}

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

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

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

const (
	oo  = 100000000
	mod = 1000000007
)

func mult(a, b int64) int64 {
	return (a * b) % mod
}
func add(a, b int64) int64 {
	return (a + b) % mod
}
func sub(a, b int64) int64 {
	return (a - b + mod) % mod
}

var (
	adj   [][]int
	depth []int
)

func pow(a, b int64) int64 {
	if b == 0 {
		return 1
	}
	res := pow(a, b/2)
	res = mult(res, res)
	if b%2 == 1 {
		res = mult(res, a)
	}
	return res
}

func solve() {
	n := nextInt()
	prev := nextInt()
	res := 0
	for i := 1; i < n; i++ {
		x := nextInt()
		if x < prev {
			res += prev - x
		}
		prev = x
	}
	printf("%d\n", res)
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	out = bufio.NewWriterSize(os.Stdout, 8192)
	if false {
		file1, err := os.Open("input.txt")
		if err != nil {
			log.Fatal(err)
		}
		file2, err := os.Create("output.txt")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file1, 8192)
		out = bufio.NewWriterSize(file2, 8192)
	}
	defer out.Flush()

	// start := time.Now()

	for t, i := nextInt(), 1; t > 0; t, i = t-1, i+1 {
		// printf("Case %d: ", i)
		solve()
	}

	// printf("%v\n", time.Now().Sub(start))
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buffer := make([]byte, 1024*1024)
	scanner.Buffer(buffer, 3*1024*1024)
	scanner.Split(bufio.ScanWords)

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

	for t := input(); t > 0; t-- {
		n := input()
		a := make([]uint64, n)

		for i := range a {
			a[i] = input()
		}

		var max, cost, i uint64

		max = a[0]

		for i = 1; i < n; i++ {
			if a[i] < max {
				cost = max - a[i]
			} else {
				max = a[i]
			}
		}

		fmt.Println(cost)
	}

}

package main

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

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	var t, n int

	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var ans, mx, mn, zp, fl int64
		fmt.Fscan(input, &n)
		arr := make([]int64, n)

		id := 0
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &arr[i])
			if arr[i] > mx {
				mx = arr[i]
				id = i
			}
		}

		mn = mx
		for i := id + 1; i < n; i++ {
			if arr[i] < mn {
				mn = arr[i]
			}
		}

		ans = mx - mn
		zp = ans
		fl = 0

		for i := 0; i < id; i++ {
			if arr[i] > arr[i+1] {
				fl += (arr[i] - arr[i+1])
				arr[i+1] = arr[i]
			}
		}

		if fl >= zp {
			fl -= zp
		}

		fmt.Println(ans - fl)
	}
}


You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red.Find the minimum possible number of moves required to make the colors of all edges equal.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of vertices and edges, respectively. The following m lines provide the description of the edges, as the i-th of them contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the indices of the vertices connected by the i-th edge, and a character ci () providing the initial color of this edge. If ci equals 'R', then this edge is initially colored red. Otherwise, ci is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges.

If there is no way to make the colors of all edges equal output  - 1 in the only line of the output. Otherwise first output k — the minimum number of moves required to achieve the goal, then output k integers a1, a2, ..., ak, where ai is equal to the index of the vertex that should be used at the i-th move. If there are multiple optimal sequences of moves, output any of them.

package main

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

var stdin *bufio.Reader
var stdout *bufio.Writer

func init() {
	stdin = bufio.NewReader(os.Stdin)
    stdout = bufio.NewWriter(os.Stdout)
}

type Edge struct {
    from, to int
    color rune
}

var edges [][]Edge
var visit []int
var list [][]int

func dfs(node int, flip int, color rune) bool {

    //fmt.Fprintf(stdout, "%v %v %v %v\n", node, visit[node], flip, color)
    if visit[node] != 0 {
        return visit[node] == flip
    }

    visit[node] = flip
    list[flip] = append(list[flip], node)

    for _, edge := range edges[node] {
        if (flip == 2 && edge.color == color) || (flip == 1 && edge.color != color) {
            if dfs(edge.to, 2, color) == false {
                return false
            }
        } else {
            if dfs(edge.to, 1, color) == false {
                return false
            }
        }
    }
    return true
}

func try(color rune) (res []int, ok bool) {
    visit   = make([]int, len(edges))
    list    = make([][]int, 3)

    for i := 0; i < len(visit); i++ {
        if visit[i] != 0 {
            continue
        }

        list[1] = make([]int, 0)
        list[2] = make([]int, 0)

        if dfs(i, 1, color) == false {
            return res, false
        }

        if len(list[1]) <= len(list[2]) {
            for _, n := range list[1] {
                res = append(res, n)
            }
        } else {
            for _, n := range list[2] {
                res = append(res, n)
            }
        }
    }

    return res, true
}

func main() {

    n, m := 0, 0
    fmt.Fscanf(stdin, "%d%d\n", &n, &m)

    edges = make([][]Edge, n)

    for i := 0; i < m; i++ {
        var from, to int
        var color rune
        fmt.Fscanf(stdin, "%d%d %c\n", &from, &to, &color)
        from--
        to--

        edges[from] = append(edges[from], Edge{from, to, color})
        edges[to] = append(edges[to], Edge{to, from, color})
    }

    v1, ok1 := try('R')
    v2, ok2 := try('B')

    if ok1 == false && ok2 == false {
        fmt.Fprintf(stdout, "-1\n")
    } else {
        var v []int
        if ok1 == true {
            v = v1
        } else {
            v = v2
        }

        if ok2 == true && len(v) > len(v2) {
            v = v2
        }
        fmt.Fprintf(stdout, "%v\n", len(v))
        for _, vv := range v {
            fmt.Fprintf(stdout, "%v ", vv + 1)
        }
        fmt.Fprintf(stdout, "\n")
    }

    stdout.Flush()
}

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

func readString() string {
	if !in.Scan() {
		panic(in.Err())
	}
	return in.Text()
}

type edge struct {
	to int
	c  bool
}

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

	n := readInt()
	m := readInt()
	edges := make([][]edge, n+1)
	for i := 0; i < m; i++ {
		u := readInt()
		v := readInt()
		c := readString() == "R"
		edges[u] = append(edges[u], edge{v, c})
		edges[v] = append(edges[v], edge{u, c})
	}
	val := make([]int, n+1)
	last := 0
	canTrue := true
	canFalse := true
	var solTrue, solFalse []int
	for i := 1; i <= n; i++ {
		if val[i] > 0 {
			continue
		}
		try := func(want, set bool) ([]int, bool) {
			var ret []int
			last += 2
			var st []int
			st = append(st, i)
			if set {
				val[i] = last
				ret = append(ret, i)
			} else {
				val[i] = last - 1
			}
			for len(st) > 0 {
				v := st[len(st)-1]
				st = st[:len(st)-1]
				isSet := val[v] == last
				for _, e := range edges[v] {
					cur := e.c
					if isSet {
						cur = !cur
					}
					ws := cur != want
					switch val[e.to] {
					case last:
						if !ws {
							return nil, false
						}
					case last - 1:
						if ws {
							return nil, false
						}
					default:
						if ws {
							val[e.to] = last
							ret = append(ret, e.to)
						} else {
							val[e.to] = last - 1
						}
						st = append(st, e.to)
					}
				}
			}
			return ret, true
		}
		for _, c := range []struct {
			val bool
			can *bool
			sol *[]int
		}{
			{true, &canTrue, &solTrue},
			{false, &canFalse, &solFalse},
		} {
			if !*c.can {
				continue
			}
			sol1, can1 := try(c.val, false)
			sol2, can2 := try(c.val, true)
			*c.can = can1 || can2
			if !*c.can {
				continue
			}
			if can1 && can2 {
				if len(sol1) < len(sol2) {
					*c.sol = append(*c.sol, sol1...)
				} else {
					*c.sol = append(*c.sol, sol2...)
				}
			} else {
				if can1 {
					*c.sol = append(*c.sol, sol1...)
				} else {
					*c.sol = append(*c.sol, sol2...)
				}
			}
		}
	}
	if !canTrue && !canFalse {
		fmt.Println("-1")
		return
	}
	var sol []int
	if canTrue && canFalse {
		if len(solTrue) < len(solFalse) {
			sol = solTrue
		} else {
			sol = solFalse
		}
	} else {
		if canFalse {
			sol = solFalse
		} else {
			sol = solTrue
		}
	}
	fmt.Fprintln(out, len(sol))
	for i := range sol {
		fmt.Fprintln(out, sol[i])
	}
}

package main

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

var stdin *bufio.Reader
var stdout *bufio.Writer

func init() {
	stdin = bufio.NewReader(os.Stdin)
    stdout = bufio.NewWriter(os.Stdout)
}

type Edge struct {
    from, to int
    color rune
}

var edges [][]Edge
var visit []int
var list [][]int

func dfs(node int, flip int, color rune) bool {

    //fmt.Fprintf(stdout, "%v %v %v %v\n", node, visit[node], flip, color)
    if visit[node] != 0 {
        return visit[node] == flip
    }

    visit[node] = flip
    list[flip] = append(list[flip], node)

    for _, edge := range edges[node] {
        if (flip == 2 && edge.color == color) || (flip == 1 && edge.color != color) {
            if dfs(edge.to, 2, color) == false {
                return false
            }
        } else {
            if dfs(edge.to, 1, color) == false {
                return false
            }
        }
    }
    return true
}

func try(color rune) (res []int, ok bool) {
    visit   = make([]int, len(edges))
    list    = make([][]int, 3)

    for i := 0; i < len(visit); i++ {
        if visit[i] != 0 {
            continue
        }

        list[1] = make([]int, 0)
        list[2] = make([]int, 0)

        if dfs(i, 1, color) == false {
            return res, false
        }

        if len(list[1]) <= len(list[2]) {
            for _, n := range list[1] {
                res = append(res, n)
            }
        } else {
            for _, n := range list[2] {
                res = append(res, n)
            }
        }
    }

    return res, true
}

func main() {

    n, m := 0, 0
    fmt.Fscanf(stdin, "%d%d\n", &n, &m)

    edges = make([][]Edge, n)

    for i := 0; i < m; i++ {
        var from, to int
        var color rune
        fmt.Fscanf(stdin, "%d%d %c\n", &from, &to, &color)
        from--
        to--

        edges[from] = append(edges[from], Edge{from, to, color})
        edges[to] = append(edges[to], Edge{to, from, color})
    }

    v1, ok1 := try('R')
    v2, ok2 := try('B')

    if ok1 == false && ok2 == false {
        fmt.Fprintf(stdout, "-1\n")
    } else {
        var v []int
        if ok1 == true {
            v = v1
        }

        if ok2 == true && len(v) > len(v2) {
            v = v2
        }
        fmt.Fprintf(stdout, "%v\n", len(v))
        for _, vv := range v {
            fmt.Fprintf(stdout, "%v ", vv + 1)
        }
        fmt.Fprintf(stdout, "\n")
    }

    stdout.Flush()
}

package main

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

var stdin *bufio.Reader
var stdout *bufio.Writer

func init() {
	stdin = bufio.NewReader(os.Stdin)
    stdout = bufio.NewWriter(os.Stdout)
}

type Edge struct {
    from, to int
    color rune
}

var edges [][]Edge
var visit []int
var list [][]int

func dfs(node int, flip int, color rune) bool {

    //fmt.Fprintf(stdout, "%v %v %v %v\n", node, visit[node], flip, color)
    if visit[node] != 0 {
        return visit[node] == flip
    }

    visit[node] = flip
    list[flip] = append(list[flip], node)

    for _, edge := range edges[node] {
        if (flip == 2 && edge.color == color) || (flip == 1 && edge.color != color) {
            if dfs(edge.to, 2, color) == false {
                return false
            }
        } else {
            if dfs(edge.to, 1, color) == false {
                return false
            }
        }
    }
    return true
}

func try(color rune) (res []int, ok bool) {
    visit   = make([]int, len(edges))
    list    = make([][]int, 3)

    for i := 0; i < len(visit); i++ {
        if visit[i] != 0 {
            continue
        }

        list[1] = make([]int, 0)
        list[2] = make([]int, 0)

        if dfs(i, 1, color) == false {
            return res, false
        }

        if len(list[1]) <= len(list[2]) {
            for _, n := range list[1] {
                res = append(res, n)
            }
        } else {
            for _, n := range list[2] {
                res = append(res, n)
            }
        }
    }

    return res, true
}

func main() {

    n, m := 0, 0
    fmt.Fscanf(stdin, "%d%d\n", &n, &m)

    edges = make([][]Edge, n)

    for i := 0; i < m; i++ {
        var from, to int
        var color rune
        fmt.Fscanf(stdin, "%d%d %c\n", &from, &to, &color)
        from--
        to--

        edges[from] = append(edges[from], Edge{from, to, color})
        edges[to] = append(edges[to], Edge{to, from, color})
    }

    v1, ok1 := try('R')
    v2, ok2 := try('B')

    if ok1 == false && ok2 == false {
        fmt.Fprintf(stdout, "-1\n")
    } else {
        v := v1
        if len(v) > len(v2) {
            v = v2
        }
        fmt.Fprintf(stdout, "%v\n", len(v))
        for _, vv := range v {
            fmt.Fprintf(stdout, "%v ", vv + 1)
        }
        fmt.Fprintf(stdout, "\n")
    }

    stdout.Flush()
}

package main

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

var stdin *bufio.Reader
var stdout *bufio.Writer

func init() {
	stdin = bufio.NewReader(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

type Point struct {
	x, y int
}

type Vector struct {
	dx, dy int
}

func main() {
	n, count := 0, 0
	fmt.Fscanf(stdin, "%d\n", &n)

	points := make([]Point, n)
	vectors := make(map[Vector]int)

	for i := 0; i < n; i++ {
		fmt.Fscanf(stdin, "%d%d\n", &points[i].x, &points[i].y)
	}

	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			var vector Vector

			if points[i].x > points[j].x || (points[i].x == points[j].x && points[i].y >= points[j].y) {
				vector = Vector{points[i].x - points[j].x, points[i].y - points[j].y}
			} else {
				vector = Vector{points[j].x - points[i].x, points[j].y - points[i].y}
			}
			count += vectors[vector]
			vectors[vector]++
		}
	}
	fmt.Fprintf(stdout, "%d\n", count / 2)

	stdout.Flush()
}


Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.

The first line contains two integer numbers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105) — the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0 ≤ ci ≤ 109) — the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≤ xi, yi ≤ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.

Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.

NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.

package main

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

func solve() {
	n := readInt()
	m := readInt()
	a := readIntArray(n)
	g := make([][]int, n)
	for i := 0; i < n; i++ {
		g[i] = make([]int, 0)
	}
	for i := 0; i < m; i++ {
		u := readInt() - 1
		v := readInt() - 1
		g[u] = append(g[u], v)
		g[v] = append(g[v], u)
	}
	vis := make([]bool, n)
	ans := int64(0)
	for i := 0; i < n; i++ {
		if !vis[i] {
			ans += dfs(g, vis, i, a)
		}
	}
	fmt.Println(ans)
}

func dfs(g [][]int, vis []bool, u int, a []int) int64 {
	vis[u] = true
	ans := int64(a[u])
	for _, v := range g[u] {
		if !vis[v] {
			ans = min(ans, dfs(g, vis, v, a))
		}
	}

	return ans
}

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

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

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

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

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

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

package main

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

func solve() {
	n := readInt()
	m := readInt()
	a := readIntArray(n)
	g := make([][]int, n)
	for i := 0; i < n; i++ {
		g[i] = make([]int, 0)
	}
	for i := 0; i < m; i++ {
		u := readInt() - 1
		v := readInt() - 1
		g[u] = append(g[u], v)
		g[v] = append(g[v], u)
	}
	vis := make([]bool, n)
	ans := 0
	for i := 0; i < n; i++ {
		if !vis[i] {
			ans += dfs(g, vis, i, a)
		}
	}
	fmt.Println(ans)
}

func dfs(g [][]int, vis []bool, u int, a []int) int {
	vis[u] = true
	ans := a[u]
	for _, v := range g[u] {
		if !vis[v] {
			ans = min(ans, dfs(g, vis, v, a))
		}
	}

	return ans
}

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

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

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

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

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

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


Soroush and Keshi each have a labeled and rooted tree on $$$n$$$ vertices. Both of their trees are rooted from vertex $$$1$$$.Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph on $$$n$$$ vertices.They add an edge between vertices $$$u$$$ and $$$v$$$ in the memorial graph if both of the following conditions hold:   One of $$$u$$$ or $$$v$$$ is the ancestor of the other in Soroush's tree.  Neither of $$$u$$$ or $$$v$$$ is the ancestor of the other in Keshi's tree. Here vertex $$$u$$$ is considered ancestor of vertex $$$v$$$, if $$$u$$$ lies on the path from $$$1$$$ (the root) to the $$$v$$$.Popping out of nowhere, Mashtali tried to find the maximum clique in the memorial graph for no reason. He failed because the graph was too big. Help Mashtali by finding the size of the maximum clique in the memorial graph.As a reminder, clique is a subset of vertices of the graph, each two of which are connected by an edge.

The first line contains an integer $$$t$$$ $$$(1\le t\le 3 \cdot 10^5)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(2\le n\le 3 \cdot 10^5)$$$. The second line of each test case contains $$$n-1$$$ integers $$$a_2, \ldots, a_n$$$ $$$(1 \le a_i < i)$$$, $$$a_i$$$ being the parent of the vertex $$$i$$$ in Soroush's tree. The third line of each test case contains $$$n-1$$$ integers $$$b_2, \ldots, b_n$$$ $$$(1 \le b_i < i)$$$, $$$b_i$$$ being the parent of the vertex $$$i$$$ in Keshi's tree. It is guaranteed that the given graphs are trees. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case print a single integer — the size of the maximum clique in the memorial graph.

NoteIn the first and third test cases, you can pick any vertex.In the second test case, one of the maximum cliques is $$$\{2, 3, 4, 5\}$$$.In the fourth test case, one of the maximum cliques is $$$\{3, 4, 6\}$$$.

package main

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

// github.com/EndlessCheng/codeforces-go
type node struct {
	lr       [2]*node
	priority uint
	key      int
}

func (o *node) cmp(b int) int {
	switch {
	case b < o.key:
		return 0
	case b > o.key:
		return 1
	default:
		return -1
	}
}

func (o *node) rotate(d int) *node {
	x := o.lr[d^1]
	o.lr[d^1] = x.lr[d]
	x.lr[d] = o
	return x
}

type treap struct {
	rd   uint
	root *node
}

func (t *treap) fastRand() uint {
	t.rd ^= t.rd << 13
	t.rd ^= t.rd >> 17
	t.rd ^= t.rd << 5
	return t.rd
}

func (t *treap) _put(o *node, key int) *node {
	if o == nil {
		return &node{priority: t.fastRand(), key: key}
	}
	if d := o.cmp(key); d >= 0 {
		o.lr[d] = t._put(o.lr[d], key)
		if o.lr[d].priority > o.priority {
			o = o.rotate(d ^ 1)
		}
	}
	return o
}

func (t *treap) put(key int) { t.root = t._put(t.root, key) }

func (t *treap) _delete(o *node, key int) *node {
	if o == nil {
		return nil
	}
	if d := o.cmp(key); d >= 0 {
		o.lr[d] = t._delete(o.lr[d], key)
	} else {
		if o.lr[1] == nil {
			return o.lr[0]
		}
		if o.lr[0] == nil {
			return o.lr[1]
		}
		d = 0
		if o.lr[0].priority > o.lr[1].priority {
			d = 1
		}
		o = o.rotate(d)
		o.lr[d] = t._delete(o.lr[d], key)
	}
	return o
}

func (t *treap) delete(key int) { t.root = t._delete(t.root, key) }

func (t *treap) lowerBound(key int) (lb *node) {
	for o := t.root; o != nil; {
		switch c := o.cmp(key); {
		case c == 0:
			lb = o
			o = o.lr[0]
		case c > 0:
			o = o.lr[1]
		default:
			return o
		}
	}
	return
}

func (t *treap) prev(key int) (prev *node) {
	for o := t.root; o != nil; {
		if o.cmp(key) <= 0 {
			o = o.lr[0]
		} else {
			prev = o
			o = o.lr[1]
		}
	}
	return
}

func CF1528C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	rd := uint(time.Now().UnixNano())/2 + 1

	var T, n, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		g1 := make([][]int, n)
		g2 := make([][]int, n)
		for w := 1; w < n; w++ {
			Fscan(in, &v)
			v--
			g1[v] = append(g1[v], w)
		}
		for w := 1; w < n; w++ {
			Fscan(in, &v)
			v--
			g2[v] = append(g2[v], w)
		}

		l := make([]int, n)
		r := make([]int, n)
		at := make([]int, n+1)
		ts := 0
		var f2 func(int)
		f2 = func(v int) {
			ts++
			l[v] = ts
			at[ts] = v
			for _, w := range g2[v] {
				f2(w)
			}
			r[v] = ts
		}
		f2(0)

		ans, sz := 0, 0
		t := &treap{rd: rd}
		var f func(int)
		f = func(v int) {
			lb := t.lowerBound(l[v])
			if lb == nil || lb.key > r[v] {
				t.put(l[v])
				sz++
				defer func() { t.delete(l[v]); sz-- }()
				if o := t.prev(l[v]); o != nil {
					if pa := at[o.key]; l[pa] < l[v] && l[v] <= r[pa] {
						t.delete(l[pa])
						sz--
						defer func() { t.put(l[pa]); sz++ }()
					}
				}
				if sz > ans {
					ans = sz
				}
			}
			for _, w := range g1[v] {
				f(w)
			}
		}
		f(0)
		Fprintln(out, ans)
	}
}

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


You have an axis-aligned rectangle room with width $$$W$$$ and height $$$H$$$, so the lower left corner is in point $$$(0, 0)$$$ and the upper right corner is in $$$(W, H)$$$.There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in $$$(x_1, y_1)$$$, and the upper right corner in $$$(x_2, y_2)$$$.You want to place another rectangular table in this room with width $$$w$$$ and height $$$h$$$ with the width of the table parallel to the width of the room.The problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though).You can't rotate any of the tables, but you can move the first table inside the room.   Example of how you may move the first table. What is the minimum distance you should move the first table to free enough space for the second one?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of the test cases. The first line of each test case contains two integers $$$W$$$ and $$$H$$$ ($$$1 \le W, H \le 10^8$$$) — the width and the height of the room. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$0 \le x_1 < x_2 \le W$$$; $$$0 \le y_1 < y_2 \le H$$$) — the coordinates of the corners of the first table. The third line contains two integers $$$w$$$ and $$$h$$$ ($$$1 \le w \le W$$$; $$$1 \le h \le H$$$) — the width and the height of the second table.

For each test case, print the minimum distance you should move the first table, or $$$-1$$$ if there is no way to free enough space for the second table. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.

NoteThe configuration of the first test case is shown in the picture. But the movement of the first table is not optimal. One of the optimal movement, for example, is to move the table by $$$(0, -1)$$$, so the lower left corner will move from $$$(2, 1)$$$ to $$$(2, 0)$$$. Then you can place the second table at $$$(0, 3)-(4, 5)$$$.In the second test case, there is no way to fit both tables in the room without intersecting.In the third test case, you can move the first table by $$$(0, 2)$$$, so the lower left corner will move from $$$(0, 3)$$$ to $$$(0, 5)$$$.

package main

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

func main() {

	r := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		var W, H int
		fmt.Fscan(r, &W, &H)

		var x1, y1, x2, y2 int
		fmt.Fscan(r, &x1, &y1, &x2, &y2)

		var w, h int
		fmt.Fscan(r, &w, &h)

		ans := solve(W, H, x1, y1, x2, y2, w, h)
		fmt.Printf("%.6f", ans)
		fmt.Println()
	}
}

func solve(W, H, x1, y1, x2, y2, w, h int) float64 {
	if w <= x1 || w <= W - x2{
		return 0
	}
	if h <= y1 || h <= H - y2 {
		return 0
	}

	var dx1 int
	var dy1 int
	var dx2 int
	var dy2 int

	if w + (x2 - x1) <= W {
		dx1 = w - x1
	} else {
		dx1 = -1
	}

	if w + (x2 - x1) <= W {
		dx2 = x2 - (W - w)

	} else {
		dx2 = -1
	}

	if h + (y2 - y1) <= H {
		dy1 = h - y1
	} else {
		dy1 = -1
	}

	if h + (y2 - y1) <= H {
		dy2 = y2 - (H - h)
	} else {
		dy2 = -1
	}

	if dx1 == -1 && dy1 == -1{
		return -1
	}
	if dx1 == -1{
		return min(float64(dy1), float64(dy2))
	}
	if dy1 == -1 {
		return min(float64(dx1), float64(dx2))
	}

	a := min(min(float64(dy1), float64(dy2)), min(float64(dx1), float64(dx2)))

	d1 := math.Sqrt(math.Pow(float64(dx1), 2) + math.Pow(float64(dy1), 2))
	d2 := math.Sqrt(math.Pow(float64(dx1), 2) + math.Pow(float64(dy2), 2))
	d3 := math.Sqrt(math.Pow(float64(dx2), 2) + math.Pow(float64(dy1), 2))
	d4 := math.Sqrt(math.Pow(float64(dx2), 2) + math.Pow(float64(dy2), 2))

	return min(a, min(d1, min(d2, min(d3, d4))))
}

func min(f1, f2 float64) float64 {
	if f1 < f2 {
		return f1
	}
	return f2
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"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 w, h int
		fmt.Fscan(in, &w, &h)

		var x1, y1, x2, y2 int
		fmt.Fscan(in, &x1, &y1, &x2, &y2)

		var bw, bh int
		fmt.Fscan(in, &bw, &bh)

		m := math.MaxInt

		for i := 0; i < 4; i++ {
			switch i {
			case 0: // x1 overlap
				ol := bw - x1
				if ol <= 0 {
					m = 0
					break
				}

				if ol < m && x2+ol <= w {
					m = ol
				}
			case 1: // y1 overlap
				ol := bh - y1
				if ol <= 0 {
					m = 0
					break
				}

				if ol < m && y2+ol <= h {
					m = ol
				}
			case 2: // x2 overlap
				ol := x2 - (w - bw)
				if ol <= 0 {
					m = 0
					break
				}

				if ol < m && x1-ol >= 0 {
					m = ol
				}
			case 3: // y2 overlap
				ol := y2 - (h - bh)
				if ol <= 0 {
					m = 0
					break
				}

				if ol < m && y1-ol >= 0 {
					m = ol
				}
			}
		}

		if m == math.MaxInt {
			fmt.Fprintln(out, -1)
		} else {
			fmt.Fprintf(out, "%d.000000000\n", m)
		}
	}
}

package main

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

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

var t int

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

	for o := 0; o < t; o++ {
		var W, H int
		var x1, y1, x2, y2 int
		var w, h int

		fmt.Fscan(input, &W, &H)
		fmt.Fscan(input, &x1, &y1, &x2, &y2)
		fmt.Fscan(input, &w, &h)

		var leftEMPTY, rightEMPTY, upEMPTY, downEMPTY int
		leftEMPTY = x1
		downEMPTY = y1
		rightEMPTY = W - x2
		upEMPTY = H - y2

		var ans int
		var leftNEED, rightNEED, upNEED, downNEED int
		leftNEED = w - leftEMPTY
		rightNEED = w - rightEMPTY
		upNEED = h - upEMPTY
		downNEED = h - downEMPTY
		if leftNEED <= 0 || rightNEED <= 0 || upNEED <= 0 || downNEED <= 0 {
			ans = 0
		} else {
			ARR := make([]int, 0)
			if leftEMPTY >= rightNEED {
				ARR = append(ARR, rightNEED)
				ARR = append(ARR, leftNEED)

			}
			if upEMPTY >= downNEED {
				ARR = append(ARR, upNEED)
				ARR = append(ARR, downNEED)
			}

			if len(ARR) == 0 {
				ans = -1
			} else {
				sort.Ints(ARR)
				ans = ARR[0]
			}

		}
		if ans == -1 {
			fmt.Println(-1)
		} else {
			wee := strconv.Itoa(ans)
			wee = wee + ".000000"
			fmt.Println(wee)
		}

	}

}

package main

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

func main() {

	r := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		var W, H int
		fmt.Fscan(r, &W, &H)

		var x1, y1, x2, y2 int
		fmt.Fscan(r, &x1, &y1, &x2, &y2)

		var w, h int
		fmt.Fscan(r, &w, &h)

		ans := solve(W, H, x1, y1, x2, y2, w, h)
		fmt.Printf("%.6f", ans)
		fmt.Println()
	}
}

func solve(W, H, x1, y1, x2, y2, w, h int) float64 {
	if w <= x1 || w <= W - x2{
		return 0
	}
	if h <= y1 || h <= H - y2 {
		return 0
	}

	var dx1 int
	var dy1 int
	var dx2 int
	var dy2 int

	if w + (x2 - x1) <= W {
		dx1 = w - x1
	} else {
		dx1 = -1
	}

	if w + (x2 - x1) <= W {
		dx2 = x2 - (W - w)

	} else {
		dx2 = -1
	}

	if h + (y2 - y1) <= H {
		dy1 = h - y1
	} else {
		dy1 = -1
	}

	if h + (y2 - y1) <= H {
		dy2 = y2 - (H - h)
	} else {
		dy2 = -1
	}

	if dx1 == -1 && dy1 == -1{
		return -1
	}
	if dx1 == -1{
		return min(float64(dy1), float64(dy2))
	}
	if dy1 == -1 {
		return min(float64(dx1), float64(dx2))
	}

	d1 := math.Sqrt(math.Pow(float64(dx1), 2) + math.Pow(float64(dy1), 2))
	d2 := math.Sqrt(math.Pow(float64(dx1), 2) + math.Pow(float64(dy2), 2))
	d3 := math.Sqrt(math.Pow(float64(dx2), 2) + math.Pow(float64(dy1), 2))
	d4 := math.Sqrt(math.Pow(float64(dx2), 2) + math.Pow(float64(dy2), 2))

	return min(d1, min(d2, min(d3, d4)))
}

func min(f1, f2 float64) float64 {
	if f1 < f2 {
		return f1
	}
	return f2
}