You are given a tree consisting of $$$n$$$ vertices. A tree is an undirected connected acyclic graph.    Example of a tree. You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples $$$(x, y, z)$$$ such that $$$x \neq y, y \neq z, x \neq z$$$, $$$x$$$ is connected by an edge with $$$y$$$, and $$$y$$$ is connected by an edge with $$$z$$$. The colours of $$$x$$$, $$$y$$$ and $$$z$$$ should be pairwise distinct. Let's call a painting which meets this condition good.You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.

The first line contains one integer $$$n$$$ $$$(3 \le n \le 100\,000)$$$ — the number of vertices. The second line contains a sequence of integers $$$c_{1, 1}, c_{1, 2}, \dots, c_{1, n}$$$ $$$(1 \le c_{1, i} \le 10^{9})$$$, where $$$c_{1, i}$$$ is the cost of painting the $$$i$$$-th vertex into the first color. The third line contains a sequence of integers $$$c_{2, 1}, c_{2, 2}, \dots, c_{2, n}$$$ $$$(1 \le c_{2, i} \le 10^{9})$$$, where $$$c_{2, i}$$$ is the cost of painting the $$$i$$$-th vertex into the second color. The fourth line contains a sequence of integers $$$c_{3, 1}, c_{3, 2}, \dots, c_{3, n}$$$ $$$(1 \le c_{3, i} \le 10^{9})$$$, where $$$c_{3, i}$$$ is the cost of painting the $$$i$$$-th vertex into the third color. Then $$$(n - 1)$$$ lines follow, each containing two integers $$$u_j$$$ and $$$v_j$$$ $$$(1 \le u_j, v_j \le n, u_j \neq v_j)$$$ — the numbers of vertices connected by the $$$j$$$-th undirected edge. It is guaranteed that these edges denote a tree.

If there is no good painting, print $$$-1$$$. Otherwise, print the minimum cost of a good painting in the first line. In the second line print $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(1 \le b_i \le 3)$$$, where the $$$i$$$-th integer should denote the color of the $$$i$$$-th vertex. If there are multiple good paintings with minimum cost, print any of them.

NoteAll vertices should be painted in different colors in the first example. The optimal way to do it is to paint the first vertex into color $$$1$$$, the second vertex — into color $$$3$$$, and the third vertex — into color $$$2$$$. The cost of this painting is $$$3 + 2 + 1 = 6$$$.

package main

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

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

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

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

	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
}

/*********** DP sub-functions ***********/

// ChMin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// DigitNumOfDecimal returns digits number of n.
// n is non negative number.
func DigitNumOfDecimal(n int) int {
	res := 0

	for n > 0 {
		n /= 10
		res++
	}

	return res
}

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int) int {
	return (a + (b - 1)) / b
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

/********** 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 MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n int
var C [4][]int
var edges [100000 + 5][]int
var degins [100000 + 5]int
var howto [20][100000 + 5]int
var orders [100000 + 5]int

func main() {
	n = ReadInt()
	C[1] = ReadIntSlice(n)
	C[2] = ReadIntSlice(n)
	C[3] = ReadIntSlice(n)
	for i := 0; i < n-1; i++ {
		u, v := ReadInt2()
		u--
		v--
		edges[u] = append(edges[u], v)
		edges[v] = append(edges[v], u)
	}

	for i := 0; i < n; i++ {
		for _, e := range edges[i] {
			degins[e]++
		}
	}

	for i := 0; i < n; i++ {
		if degins[i] > 2 {
			fmt.Println(-1)
			return
		}
	}

	roots := []int{}
	for i := 0; i < n; i++ {
		if degins[i] == 1 {
			roots = append(roots, i)
		}
	}

	dfs(roots[0], -1, 0)

	temp := [][]int{
		[]int{1, 2, 3}, []int{1, 3, 2},
		[]int{2, 1, 3}, []int{2, 3, 1},
		[]int{3, 1, 2}, []int{3, 2, 1},
	}
	for i := 0; i < 6; i++ {
		for j := 0; j < n; j++ {
			howto[i][orders[j]] = temp[i][j%3]
		}
	}
	for i := 6; i < 12; i++ {
		for j := 0; j < n; j++ {
			howto[i][orders[n-1-j]] = temp[i-6][j%3]
		}
	}

	ans := int64(1 << 60)
	ansOrderIdx := -1
	for i := 0; i < 12; i++ {
		tmpAns := int64(0)

		for j := 0; j < n; j++ {
			c := howto[i][j]
			tmpAns += int64(C[c][j])
		}

		if ans >= tmpAns {
			ans = tmpAns
			ansOrderIdx = i
		}
	}

	fmt.Println(ans)
	for i := 0; i < n; i++ {
		if i == n-1 {
			fmt.Println(howto[ansOrderIdx][i])
		} else {
			fmt.Printf("%d ", howto[ansOrderIdx][i])
		}
	}
}

func dfs(cid, pid, curIdx int) {
	orders[curIdx] = cid
	for _, e := range edges[cid] {
		if e == pid {
			continue
		}
		dfs(e, cid, curIdx+1)
	}
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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

package main

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

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

	var n int
	Fscan(in, &n)
	c := [3][]int64{}
	for i := range c {
		c[i] = make([]int64, n)
		for j := range c[i] {
			Fscan(in, &c[i][j])
		}
	}
	g := make([][]int, n)
	deg := make([]int, n)
	for m := n - 1; m > 0; m-- {
		var v, w int
		Fscan(in, &v, &w)
		v--
		w--
		deg[v]++
		deg[w]++
		if deg[v] > 2 || deg[w] > 2 {
			Fprint(out, -1)
			return
		}
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	vs := make([]int, 0, n)
	for i, d := range deg {
		if d == 1 {
			vs = append(vs, i, g[i][0])
			for prev, v := i, g[i][0]; len(g[v]) == 2; {
				for _, w := range g[v] {
					if w != prev {
						vs = append(vs, w)
						prev, v = v, w
						break
					}
				}
			}
			break
		}
	}
	minAns, orderIdxAns := int64(1e18), 0
	orders := [6][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}}
	for i, order := range orders {
		sum := int64(0)
		for j, v := range vs {
			sum += c[order[j%3]][v]
		}
		if sum < minAns {
			minAns = sum
			orderIdxAns = i
		}
	}
	Fprintln(out, minAns)
	ans := make([]interface{}, n)
	order := orders[orderIdxAns]
	for i, v := range vs {
		ans[v] = order[i%3] + 1
	}
	Fprint(out, ans...)
}

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

package main

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

type point struct {
	x, y int
}

var ans int64

const (
	mod = int(1e9 + 7)
)

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

var edge [][]int
var c [][]int
var color []int

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	c1, c2, c3 := make([]int, n), make([]int, n), make([]int, n)
	edge = make([][]int, n)
	for i := 0; i < n; i++ {
		edge[i] = make([]int, 0)
		fmt.Fscanf(in, "%d", &c1[i])
	}
	fmt.Fscanf(in, "\n")
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d", &c2[i])
	}
	fmt.Fscanf(in, "\n")
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d", &c3[i])
	}
	fmt.Fscanf(in, "\n")
	for i := 0; i < n-1; i++ {
		a, b := 0, 0
		fmt.Fscanf(in, "%d %d\n", &a, &b)
		a--
		b--
		//fmt.Println(a, b)
		edge[a] = append(edge[a], b)
		edge[b] = append(edge[b], a)
	}
	c = make([][]int, 3)
	c[0] = c1
	c[1] = c2
	c[2] = c3
	start := 0
	for i := 0; i < n; i++ {
		if len(edge[i]) > 2 {
			fmt.Fprintf(out, "-1\n")
			return
		}
		if len(edge[i]) == 1 {
			start = i
		}
	}
	ansColor := make([]int, n)
	color = make([]int, n)
	ans := solve(start, -1, []int{0, 1, 2}, 0)
	copy(ansColor, color)
	if ans > solve(start, -1, []int{0, 2, 1}, 0) {
		ans = solve(start, -1, []int{0, 2, 1}, 0)
		copy(ansColor, color)
	}
	if ans > solve(start, -1, []int{1, 0, 2}, 0) {
		ans = solve(start, -1, []int{1, 0, 2}, 0)
		copy(ansColor, color)
	}
	if ans > solve(start, -1, []int{1, 2, 0}, 0) {
		ans = solve(start, -1, []int{1, 2, 0}, 0)
		copy(ansColor, color)
	}
	if ans > solve(start, -1, []int{2, 0, 1}, 0) {
		ans = solve(start, -1, []int{2, 0, 1}, 0)
		//fmt.Println("debugans", ans)
		copy(ansColor, color)
	}
	if ans > solve(start, -1, []int{2, 1, 0}, 0) {
		ans = solve(start, -1, []int{2, 1, 0}, 0)
		//fmt.Println("debugans2", ans)
		copy(ansColor, color)
	}
	//fmt.Println("debug", start)
	fmt.Fprintf(out, "%d\n", ans)
	for i := 0; i < n-1; i++ {
		fmt.Fprintf(out, "%d ", ansColor[i])
	}
	fmt.Fprintf(out, "%d\n", ansColor[n-1])
	return
}

func copy(a, b []int) {
	n := len(a)
	for i := 0; i < n; i++ {
		a[i] = b[i]
	}
	return
}

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

func solve(cur int, par int, seq []int, time int) int64 {
	curColor := seq[time%3]
	color[cur] = curColor + 1
	next := edge[cur][0]
	if next == par {
		if len(edge[cur]) == 1 {
			return int64(c[curColor][cur])
		}
		next = edge[cur][1]
	}
	return int64(c[curColor][cur]) + solve(next, cur, seq, time+1)
}

package main

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

func childNode(tree *[][]int, parent, curent int) int {
	nodes := (*tree)[curent]
	if nodes[0] != parent {
		return nodes[0]
	}

	return nodes[1]
}

func main() {
	var n int

	reader := bufio.NewReader(os.Stdin)
	fmt.Fscanf(reader, "%d\n", &n)

	//fmt.Println(n, s)
	tree := make([][]int, n+1)
	colors := [3][]int{make([]int, n+1), make([]int, n+1), make([]int, n+1)}

	var p, m int
	for j := 0; j < 3; j++ {
		for i := 1; i <= n; i++ {
			if i != n {
				fmt.Fscanf(reader, "%d", &p)
			} else {
				fmt.Fscanf(reader, "%d\n", &p)
			}
			colors[j][i] = p
		}
	}

	noAns := false

	for i := 1; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &p, &m)
		if noAns {
			continue
		}

		if len(tree[p]) == 0 {
			tree[p] = make([]int, 0, 3)
		}

		if len(tree[m]) == 0 {
			tree[m] = make([]int, 0, 3)
		}

		tree[p] = append(tree[p], m)
		tree[m] = append(tree[m], p)

		if len(tree[m]) > 2 || len(tree[p]) > 2 {
			noAns = true
		}
	}

	if noAns {
		fmt.Printf("-1\n")
		return
	}

	root := 0
	for i := 1; i <= n; i++ {
		if len(tree[i]) == 1 {
			root = i
			break
		}
	}

	var ans []int
	var sum int64 = int64(1) << 62

	var indexi, indexj, indexk int
	var colori, colorj, colork int
	for i := 0; i < 3; i++ {

		for j := 0; j < 3; j++ {
			if i == j {
				continue
			}

			for k := 0; k < 3; k++ {
				if i == k || j == k {
					continue
				}
				colori = i
				colorj = j
				colork = k

				indexi = root
				indexj = childNode(&tree, 0, indexi)
				//indexk = childNode(&tree, indexj)

				var tans []int = make([]int, n+1)
				var tsum int64 = 0

				tans[indexi] = colori
				tsum += int64(colors[colori][indexi])
				tans[indexj] = colorj
				tsum += int64(colors[colorj][indexj])

				for ik := 3; ik <= n; ik++ {
					indexk = childNode(&tree, indexi, indexj)

					tans[indexk] = colork
					tsum += int64(colors[colork][indexk])

					colori, colorj, colork = colorj, colork, colori
					indexi, indexj, indexk = indexj, indexk, indexi
				}

				//fmt.Println(tsum)
				if tsum < sum {
					sum = tsum
					ans = tans
				}
			}

		}
	}

	fmt.Printf("%d\n", sum)

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

package main

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

func childNode(tree *[][]int, parent, curent int) int {
	nodes := (*tree)[curent]
	if nodes[0] != parent {
		return nodes[0]
	}

	return nodes[1]
}

func main() {
	var n int

	reader := bufio.NewReader(os.Stdin)
	fmt.Fscanf(reader, "%d\n", &n)

	//fmt.Println(n, s)
	tree := make([][]int, n+1)
	colors := [3][]int{make([]int, n+1), make([]int, n+1), make([]int, n+1)}

	var p, m int
	for j := 0; j < 3; j++ {
		for i := 1; i <= n; i++ {
			if i != n {
				fmt.Fscanf(reader, "%d", &p)
			} else {
				fmt.Fscanf(reader, "%d\n", &p)
			}
			colors[j][i] = p
		}
	}

	noAns := false

	for i := 1; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &p, &m)
		if noAns {
			continue
		}

		if len(tree[p]) == 0 {
			tree[p] = make([]int, 0, 3)
		}

		if len(tree[m]) == 0 {
			tree[m] = make([]int, 0, 3)
		}

		tree[p] = append(tree[p], m)
		tree[m] = append(tree[m], p)

		if len(tree[m]) > 2 || len(tree[p]) > 2 {
			noAns = true
		}
	}

	if noAns {
		fmt.Printf("-1\n")
		return
	}

	root := 0
	for i := 1; i <= n; i++ {
		if len(tree[i]) == 1 {
			root = i
			break
		}
	}

	var ans []int
	var sum int64 = int64(1) << 62

	var indexi, indexj, indexk int
	var colori, colorj, colork int
	for i := 0; i < 3; i++ {

		for j := 0; j < 3; j++ {
			if i == j {
				continue
			}

			for k := 0; k < 3; k++ {
				if i == k || j == k {
					continue
				}
				colori = i
				colorj = j
				colork = k

				indexi = root
				indexj = childNode(&tree, 0, indexi)
				//indexk = childNode(&tree, indexj)

				var tans []int = make([]int, n+1)
				var tsum int64 = 0

				tans[indexi] = colori
				tsum += int64(colors[colori][indexi])
				tans[indexj] = colorj
				tsum += int64(colors[colorj][indexj])

				for ik := 3; ik <= n; ik++ {
					indexk = childNode(&tree, indexi, indexj)

					tans[indexk] = colork
					tsum += int64(colors[colork][indexk])

					colori, colorj, colork = colorj, colork, colori
					indexi, indexj, indexk = indexj, indexk, indexi
				}

				//fmt.Println(tsum)
				if tsum < sum {
					sum = tsum
					ans = tans
				}
			}
		}
	}

	fmt.Printf("%d\n", sum)

	inter := make([]interface{}, len(ans)-1)
	for i := 1; i <= n; i++ {
		inter[i-1] = ans[i] + 1
	}

	fmt.Println(inter...)
	// for i := 1; i <= n; i++ {
	// 	if i != n {
	// 		fmt.Printf("%d ", ans[i]+1)
	// 	} else {
	// 		fmt.Printf("%d\n", ans[i]+1)
	// 	}
	// }
}

package main

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

func GetWR() (*bufio.Reader, *bufio.Writer) {
	l := os.Getenv("LOCAL_DEBUG")
	reader := io.Reader(os.Stdin)
	writer := io.Writer(os.Stdout)

	if l != "" {
		bs, _ := ioutil.ReadFile("in.txt")
		reader = bytes.NewBuffer(bs)
	}
	return bufio.NewReader(reader), bufio.NewWriter(writer)
}

func C(n int64, c [][]int64, edge map[int64][]int64, oneE int64, y [3]int64) ([]int64, int64) {
	res := make([]int64, n+1)
	sum := int64(0)
	vis := make(map[int64]bool)
	j := 0
	q := make([]int64, 0, n)
	q = append(q, oneE)
	vis[oneE] = true

	for len(q) != 0 {
		l := len(q)
		yy := y[j%3]
		for l != 0 {
			v := q[0]
			q = q[1:]
			//fmt.Printf("yy %d, v %d\n", yy, v)
			sum += c[yy][v]
			res[v] = yy

			l--
			for _, vv := range edge[v] {
				if !vis[vv] {
					q = append(q, vv)
					vis[vv] = true
				}
			}
		}
		j++
	}
	return res, sum
}

func main() {
	var n, i, j, u, v int64
	var c [][]int64
	var edge map[int64][]int64
	var oneE int64

	r, w := GetWR()
	defer w.Flush()
	R := func(format string, a ...interface{}) { _, _ = fmt.Fscanf(r, format, a...) }
	RE := func(format string, a ...interface{}) error { _, err := fmt.Fscanf(r, format, a...); return err }
	W := func(format string, a ...interface{}) { _, _ = fmt.Fprintf(w, format, a...) }

	for io.EOF != RE("%d\n", &n) {
		c = make([][]int64, 3)
		edge = make(map[int64][]int64, n)

		for i = 0; i < 3; i++ {
			c[i] = make([]int64, n+1)
			for j = 1; j <= n; j++ {
				R("%d", &c[i][j])
			}
			R("\n")
		}
		for i = 0; i < n-1; i++ {
			R("%d %d\n", &u, &v)
			edge[u] = append(edge[u], v)
			edge[v] = append(edge[v], u)
		}
		f := false
		for e1, ea := range edge {
			if len(ea) >= 3 {
				f = true
			}
			if len(ea) == 1 {
				oneE = e1
			}
		}
		if f {
			W("-1\n")
		} else {
			sum := make([]int64, 6)
			res := make([][]int64, 6)

			res[0], sum[0] = C(n, c, edge, oneE, [3]int64{0, 1, 2})
			res[1], sum[1] = C(n, c, edge, oneE, [3]int64{0, 2, 1})
			res[2], sum[2] = C(n, c, edge, oneE, [3]int64{1, 0, 2})
			res[3], sum[3] = C(n, c, edge, oneE, [3]int64{1, 2, 0})
			res[4], sum[4] = C(n, c, edge, oneE, [3]int64{2, 1, 0})
			res[5], sum[5] = C(n, c, edge, oneE, [3]int64{2, 0, 1})

			s := int64(3 * 100000 * 1000000000)
			ti := 0
			for i := 0; i < 6; i++ {
				if sum[i] < s {
					s = sum[i]
					ti = i
				}
			}
			W("%d\n", s)
			for j := int64(1); j <= n; j++ {
				if j == n {
					W("%d\n", res[ti][j]+1)
				} else {
					W("%d ", res[ti][j]+1)
				}
			}
		}
	}
}

package main

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

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

	var n int
	Fscan(in, &n)
	c := [3][]int64{}
	for i := range c {
		c[i] = make([]int64, n)
		for j := range c[i] {
			Fscan(in, &c[i][j])
		}
	}
	g := make([][]int, n)
	deg := make([]int, n)
	for m := n - 1; m > 0; m-- {
		var v, w int
		Fscan(in, &v, &w)
		v--
		w--
		deg[v]++
		deg[w]++
		if deg[v] > 2 || deg[w] > 2 {
			Fprint(out, -1)
			return
		}
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	vs := make([]int, 0, n)
	for i, d := range deg {
		if d == 1 {
			vs = append(vs, i, g[i][0])
			for prev, v := i, g[i][0]; len(g[v]) == 2; {
				for _, w := range g[v] {
					if w != prev {
						vs = append(vs, w)
						prev, v = v, w
						break
					}
				}
			}
			break
		}
	}
	minAns, orderIdxAns := int64(1e18), 0
	orders := [6][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}}
	for i, order := range orders {
		sum := int64(0)
		for i := range vs {
			sum += c[order[i%3]][i]
		}
		if sum < minAns {
			minAns = sum
			orderIdxAns = i
		}
	}
	Fprintln(out, minAns)
	order := orders[orderIdxAns]
	for i := range vs {
		Fprint(out, order[i%3]+1, " ")
	}
}

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

package main

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

func GetWR() (*bufio.Reader, *bufio.Writer) {
	l := os.Getenv("LOCAL_DEBUG")
	reader := io.Reader(os.Stdin)
	writer := io.Writer(os.Stdout)

	if l != "" {
		bs, _ := ioutil.ReadFile("in.txt")
		reader = bytes.NewBuffer(bs)
	}
	return bufio.NewReader(reader), bufio.NewWriter(writer)
}

func C(n int64, c [][]int64, edge map[int64][]int64, y [3]int64) ([]int64, int64) {
	res := make([]int64, n+1)
	sum := int64(0)
	vis := make(map[int64]bool)
	j := 0
	q := make([]int64, 0, n)
	q = append(q, 1)
	vis[1] = true

	for len(q) != 0 {
		l := len(q)
		yy := y[j%3]
		for l != 0 {
			v := q[0]
			q = q[1:]
			//fmt.Printf("yy %d, v %d\n", yy, v)
			sum += c[yy][v]
			res[v] = yy

			l--
			for _, vv := range edge[v] {
				if !vis[vv] {
					q = append(q, vv)
					vis[vv] = true
				}
			}
		}
		j++
	}
	return res, sum
}

func main() {
	var n, i, j, u, v int64
	var c [][]int64
	var edge map[int64][]int64

	r, w := GetWR()
	defer w.Flush()
	R := func(format string, a ...interface{}) error { _, err := fmt.Fscanf(r, format, a...); return err }
	W := func(format string, a ...interface{}) error { _, err := fmt.Fprintf(w, format, a...); return err }

	for io.EOF != R("%d\n", &n) {
		c = make([][]int64, 4)
		edge = make(map[int64][]int64, n)

		for i = 0; i < 3; i++ {
			c[i] = make([]int64, n+1)
			for j = 1; j <= n; j++ {
				R("%d", &c[i][j])
			}
			R("\n")
		}
		for i = 0; i < n-1; i++ {
			R("%d %d\n", &u, &v)
			edge[u] = append(edge[u], v)
			edge[v] = append(edge[v], u)
		}
		f := false
		for _, e := range edge {
			if len(e) >= 3 {
				f = true
			}
		}
		if f {
			W("-1\n")
		} else {
			sum := make([]int64, 6)
			res := make([][]int64, 6)

			res[0], sum[0] = C(n, c, edge, [3]int64{0, 1, 2})
			res[1], sum[1] = C(n, c, edge, [3]int64{0, 2, 1})
			res[2], sum[2] = C(n, c, edge, [3]int64{1, 0, 2})
			res[3], sum[3] = C(n, c, edge, [3]int64{1, 2, 0})
			res[4], sum[4] = C(n, c, edge, [3]int64{2, 1, 0})
			res[5], sum[5] = C(n, c, edge, [3]int64{2, 0, 1})

			s := int64(3 * 100000 * 1000000000)
			ti := 0
			for i := 0; i < 6; i++ {
				if sum[i] < s {
					s = sum[i]
					ti = i
				}
			}
			W("%d\n", s)
			for j := int64(1); j <= n; j++ {
				if j == n {
					W("%d\n", res[ti][j]+1)
				} else {
					W("%d ", res[ti][j]+1)
				}
			}
		}
	}
}

package main

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

func GetWR() (*bufio.Reader, *bufio.Writer) {
	l := os.Getenv("LOCAL_DEBUG")
	reader := io.Reader(os.Stdin)
	writer := io.Writer(os.Stdout)

	if l != "" {
		bs, _ := ioutil.ReadFile("in.txt")
		reader = bytes.NewBuffer(bs)
	}
	return bufio.NewReader(reader), bufio.NewWriter(writer)
}

func C(n int64, c [][]int64, edge map[int64][]int64, y [3]int64) ([]int64, int64) {
	res := make([]int64, n+1)
	sum := int64(0)
	vis := make(map[int64]bool)
	j := 0
	q := make([]int64, 0, n)
	q = append(q, 1)
	vis[1] = true

	for len(q) != 0 {
		l := len(q)
		yy := y[j%3]
		for l != 0 {
			v := q[0]
			q = q[1:]
			//fmt.Printf("yy %d, v %d\n", yy, v)
			sum += c[yy][v]
			res[v] = yy

			l--
			for _, vv := range edge[v] {
				if !vis[vv] {
					q = append(q, vv)
					vis[vv] = true
				}
			}
		}
		j++
	}
	return res, sum
}

func main() {
	var n, i, j, u, v int64
	var c [][]int64
	var edge map[int64][]int64

	r, w := GetWR()
	defer w.Flush()
	R := func(format string, a ...interface{}) error { _, err := fmt.Fscanf(r, format, a...); return err }
	W := func(format string, a ...interface{}) error { _, err := fmt.Fprintf(w, format, a...); return err }

	for io.EOF != R("%d\n", &n) {
		c = make([][]int64, 4)
		edge = make(map[int64][]int64, n)

		for i = 0; i < 3; i++ {
			c[i] = make([]int64, n+1)
			for j = 1; j <= n; j++ {
				R("%d", &c[i][j])
			}
			R("\n")
		}
		for i = 0; i < n-1; i++ {
			R("%d %d\n", &u, &v)
			edge[u] = append(edge[u], v)
			edge[v] = append(edge[v], u)
		}
		f := false
		for _, e := range edge {
			if len(e) >= 3 {
				f = true
			}
		}
		if f {
			W("-1\n")
		} else {
			sum := make([]int64, 6)
			res := make([][]int64, 6)

			res[0], sum[0] = C(n, c, edge, [3]int64{0, 1, 2})
			res[1], sum[1] = C(n, c, edge, [3]int64{0, 2, 1})
			res[2], sum[2] = C(n, c, edge, [3]int64{1, 0, 2})
			res[3], sum[3] = C(n, c, edge, [3]int64{1, 2, 0})
			res[4], sum[4] = C(n, c, edge, [3]int64{2, 1, 0})
			res[5], sum[5] = C(n, c, edge, [3]int64{2, 0, 1})

			s := int64(3 * 1000000000)
			ti := 0
			for i := 0; i < 6; i++ {
				if sum[i] < s {
					s = sum[i]
					ti = i
				}
			}
			W("%d\n", s)
			for j := int64(1); j <= n; j++ {
				if j == n {
					W("%d\n", res[ti][j]+1)
				} else {
					W("%d ", res[ti][j]+1)
				}
			}
		}
	}
}


This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.

The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.

Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.

package main

import (
	"container/heap"
	"fmt"
    "bufio"
    "os"
)

var (
   reader = bufio.NewReader(os.Stdin)
)

type entry struct {
	cost, pos int
}

type myQueue []*entry

func (pq myQueue) Len() int {
	return len(pq)
}

func (pq myQueue) Less(i, j int) bool {
	return pq[i].cost < pq[j].cost
}

func (pq myQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *myQueue) Push(x interface{}) {
	item := x.(*entry)
	*pq = append(*pq, item)
}

func (pq *myQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

func Qamount(a []byte, n int) int {
	res := 0
    for i := 0; i < n; i++ {
        if a[i] == '?' {
           res++
        }
	}
    return res
}

func main() {
	const inf = 1e9
	myQ := &myQueue{}
	heap.Init(myQ)
	var tempTab string
	cval, oval := make([]int, 60000), make([]int, 60000)
	tab := make([]byte, 60000)
	fmt.Fscanf(reader, "%v", &tempTab)
	n := len(tempTab)
	for i := 0; i < n; i++ {
		tab[i] = tempTab[i]
	}
	//fmt.Printf("%v\n", tab)
	m := Qamount(tab, n)
//    fmt.Println(m)
	for i := 0; i < m; i++ {
		fmt.Fscan(reader, &oval[i], &cval[i])
	}
//    for i := 0; i < m; i++ {
//       fmt.Println(i, oval[i], cval[i])
//    }
	bal, res, pos := 0, int64(0), 0
	for i := 0; i < n; i++ {
		switch tab[i] {
		case '(':
			bal++
		case ')':
			bal--
		default:
//            fmt.Println("res += ", int64(cval[pos]))
			res += int64(cval[pos])
			tab[i] = ')'
			bal--
			heap.Push(myQ, &entry{oval[pos] - cval[pos], i})
			pos++
		}
		if bal < 0 {
			if myQ.Len() > 0 {
				temp := heap.Pop(myQ).(*entry)
				//fmt.Printf("  %v\n", heap.Pop(myQ))
				res += int64(temp.cost)
				tab[temp.pos] = '('
				bal += 2
			} else {
				bal = inf
				break
			}
		}
	}
    tempTab = string(tab[:n])
	if bal == 0 {
		fmt.Printf("%v\n%v\n", res, tempTab)
	} else {
		fmt.Printf("-1\n")
	}
}

package main

import (
	"bytes"
	"container/heap"
	"fmt"
	"io/ioutil"
	"os"
)

type Node struct {
	Index int
	Value int64
}

type NodeHeap []*Node

func (h NodeHeap) Len() int {
	return len(h)
}

func (h NodeHeap) Less(i, j int) bool {
	return h[i].Value > h[j].Value
}

func (h NodeHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *NodeHeap) Push(x interface{}) {
	*h = append(*h, x.(*Node))
}

func (h *NodeHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func main() {
	left := [50000]int64{}
	right := [50000]int64{}
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var s string
	fmt.Fscanf(reader, "%s\n", &s)
	rawBytes := []byte(s)
	resultBytes := make([]byte, len(rawBytes))

	qCount := 0
	cost := int64(0)

	h := &NodeHeap{}
	heap.Init(h)

	for i := 0; i < len(rawBytes); i++ {
		if rawBytes[i] == '(' {
			resultBytes[i] = '('
		} else if rawBytes[i] == ')' {
			resultBytes[i] = ')'
		} else if rawBytes[i] == '?' {
			resultBytes[i] = ')'
			fmt.Fscanf(reader, "%d %d\n", &left[qCount], &right[qCount])
			cost += right[qCount]
			qCount++
		}
	}
	leftCount := 0
	curQues := 0
	for i := 0; i < len(rawBytes); i++ {
		if rawBytes[i] == '(' {
			leftCount++
		} else if rawBytes[i] == ')' {
			leftCount--
		} else if rawBytes[i] == '?' {
			heap.Push(h, &Node{i, right[curQues] - left[curQues]})
			leftCount--
			curQues++
		}
		if leftCount < 0 {
			if len(*h) == 0 {
				fmt.Printf("-1")
				return
			}
			node := heap.Pop(h).(*Node)
			cost -= node.Value
			resultBytes[node.Index] = '('
			leftCount += 2
		}
	}
	if leftCount != 0 {
		fmt.Printf("-1")
		return
	}
	fmt.Printf("%d\n", cost)
	fmt.Printf("%s", string(resultBytes))

}

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
)

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

	s, _ := reader.ReadString('\n')

	var cnt int
	for i := 0; i < len(s); i++ {
		if s[i] == '?' {
			cnt++
		}
	}
	cost := make([][]int, cnt)
	for i := 0; i < cnt; i++ {
		cost[i] = readNNums(reader, 2)
	}
	res, ss := solve(s, cost)
	fmt.Println(res)
	if res < 0 {
		return
	}

	fmt.Println(ss)
}

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') {
			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(s string, cost [][]int) (int64, string) {
	ss := []byte(s)
	var open int
	pq := make(PriorityQueue, 0, len(s))
	var res int64
	for i, j := 0, 0; i < len(s); i++ {
		if s[i] != '(' && s[i] != ')' && s[i] != '?' {
			break
		}
		if s[i] == '(' {
			open++
		} else {
			open--
		}

		if s[i] == '?' {
			cur := cost[j]
			j++
			a, b := cur[0], cur[1]
			ss[i] = ')'
			heap.Push(&pq, &Item{b - a, i, -1})
			res += int64(b)
		}

		if open < 0 {
			if len(pq) == 0 {
				break
			}
			x := heap.Pop(&pq).(*Item)
			ss[x.second] = '('
			res += int64(-x.first)
			open += 2
		}
	}

	if open != 0 {
		return -1, ""
	}
	return res, string(ss)
}

type Item struct {
	first  int
	second int
	index  int
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].first > pq[j].first
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

package main

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

type entry struct {
	index, cost int
}

func solve() {
	h := &Int64Heap{}
	heap.Init(h)
	sx := readString()
	value := int64(0)
	n := 0

	s := []byte(sx)
	for i, c := range s {
		switch c {
		case '(':
			n++
			break
		case ')':
			n--
			break
		case '?':
			l := readInt64()
			r := readInt64()
			value += r
			n--
			s[i] = ')'
			heap.Push(h, costpos{r - l, i})
			break
		}

		if n < 0 {
			if h.Len() == 0 {
				break
			}
			cp := heap.Pop(h).(costpos)
			value -= cp.cost
			s[cp.pos] = '('
			n += 2
		}
	}

	if n != 0 {
		fmt.Println("-1")
		return
	}
	fmt.Println(value)
	fmt.Println(string(s))
}

type costpos struct {
	cost int64
	pos  int
}
type Int64Heap []costpos

// This is a max-heap of int64s
func (h Int64Heap) Len() int           { return len(h) }
func (h Int64Heap) Less(i, j int) bool { return h[i].cost > h[j].cost }
func (h Int64Heap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *Int64Heap) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify
	// the slice's length, not just its contents.
	*h = append(*h, x.(costpos))
}

func (h *Int64Heap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

var scanner *bufio.Scanner

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

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

package main

import (
	"container/heap"
	"fmt"
    "bufio"
    "os"
)

var (
   reader = bufio.NewReader(os.Stdin)
)

type entry struct {
	cost, pos int
}

type myQueue []*entry

func (pq myQueue) Len() int {
	return len(pq)
}

func (pq myQueue) Less(i, j int) bool {
	return pq[i].cost < pq[j].cost
}

func (pq myQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *myQueue) Push(x interface{}) {
	item := x.(*entry)
	*pq = append(*pq, item)
}

func (pq *myQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

func Qamount(a []byte, n int) int {
	i, res := 0, 0
	for a[i] != 0 {
		i++
        if a[i] == '?' {
           res++
        }
	}
    return res
}

func main() {
	const inf = 1e9
	myQ := &myQueue{}
	heap.Init(myQ)
	var tempTab string
	cval, oval := make([]int, 60000), make([]int, 60000)
	tab := make([]byte, 60000)
	fmt.Fscanf(reader, "%v", &tempTab)
	n := len(tempTab)
	for i := 0; i < n; i++ {
		tab[i] = tempTab[i]
	}
	//fmt.Printf("%v\n", tab)
	m := Qamount(tab, n)
//    fmt.Println(m)
	for i := 0; i < m; i++ {
		fmt.Fscan(reader, &oval[i], &cval[i])
	}
//    for i := 0; i < m; i++ {
//       fmt.Println(i, oval[i], cval[i])
//    }
	bal, res, pos := 0, int64(0), 0
	for i := 0; i < n; i++ {
		switch tab[i] {
		case '(':
			bal++
		case ')':
			bal--
		default:
//            fmt.Println("res += ", int64(cval[pos]))
			res += int64(cval[pos])
			tab[i] = ')'
			bal--
			heap.Push(myQ, &entry{oval[pos] - cval[pos], i})
			pos++
		}
		if bal < 0 {
			if myQ.Len() > 0 {
				temp := heap.Pop(myQ).(*entry)
				//fmt.Printf("  %v\n", heap.Pop(myQ))
				res += int64(temp.cost)
				tab[temp.pos] = '('
				bal += 2
			} else {
				bal = inf
				break
			}
		}
	}
    tempTab = string(tab[:n])
	if bal == 0 {
		fmt.Printf("%v\n%v\n", res, tempTab)
	} else {
		fmt.Printf("-1\n")
	}
}

package main

import (
	"container/heap"
	"fmt"
)

type entry struct {
	cost, pos int
}

type myQueue []*entry

func (pq myQueue) Len() int {
	return len(pq)
}

func (pq myQueue) Less(i, j int) bool {
	return pq[i].cost < pq[j].cost
}

func (pq myQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *myQueue) Push(x interface{}) {
	item := x.(*entry)
	*pq = append(*pq, item)
}

func (pq *myQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

func Qamount(a []byte, n int) int {
	i := 0
	for a[i] != 0 {
		i++
	}
	return i
}

func main() {
	const inf = 1e9
	myQ := &myQueue{}
	heap.Init(myQ)
	var tempTab string
	cval, oval := make([]int, 60000), make([]int, 60000)
	tab := make([]byte, 60000)
	fmt.Scanf("%v", &tempTab)
	n := len(tempTab)
	for i := 0; i < n; i++ {
		tab[i] = tempTab[i]
	}
	//fmt.Printf("%v\n", tab)
	m := Qamount(tab, n)
	for i := 0; i < m; i++ {
		fmt.Scanf("%d%d", &oval[i], &cval[i])
	}
	bal, res, pos := 0, int64(0), 0
	for i := 0; i < n; i++ {
		switch tab[i] {
		case '(':
			bal++
		case ')':
			bal--
		default:
			res += int64(cval[pos])
			tab[i] = ')'
			bal--
			heap.Push(myQ, &entry{oval[pos] - cval[pos], i})
			pos++
		}
		if bal < 0 {
			if myQ.Len() > 0 {
				temp := heap.Pop(myQ).(*entry)
				//fmt.Printf("  %v\n", heap.Pop(myQ))
				res += int64(temp.cost)
				tab[temp.pos] = '('
				bal += 2
			} else {
				bal = inf
				break
			}
		}
	}
    tempTab = string(tab[:n])
	if bal == 0 {
		fmt.Printf("%v\n%v\n", res, tempTab)
	} else {
		fmt.Printf("-1\n")
	}
}

package main

import (
   "container/heap"
   "fmt"
)

type entry struct {
   cost, pos int
}

type myQueue []*entry

func (pq myQueue) Len() int {
   return len(pq)
}

func (pq myQueue) Less(i, j int) bool {
   return pq[i].cost < pq[j].cost
}

func (pq myQueue) Swap(i, j int) {
   pq[i], pq[j] = pq[j], pq[i]
}

func (pq *myQueue) Push(x interface{}) {
   item := x.(*entry)
   *pq = append(*pq, item)
}

func (pq *myQueue) Pop() interface{} {
   old := *pq
   n := len(old)
   item := old[n-1]
   *pq = old[0 : n-1]
   return item
}

func Qamount (a []byte, n int) int {
   i := 0
   for a[i] != 0 {
      i++
   }
   return i
}

func main() {
   const inf = 1e9
   myQ := &myQueue{}
   heap.Init(myQ)
   var tempTab string
   cval, oval := make([]int, 60000), make([]int, 60000)
   tab := make([]byte, 60000)
   fmt.Scanf("%v", &tempTab)
   n := len(tempTab)
   for i := 0; i < n; i++ {
      tab[i] = tempTab[i]
   }
   //fmt.Printf("%v\n", tab)
   m := Qamount(tab, n)
   for i := 0; i < m; i++ {
      fmt.Scanf("%d%d", &oval[i], &cval[i])
   }
   bal, res, pos := 0, int64(0), 0
   for i := 0; i < n; i++ {
      switch tab[i] {
      case '(':
         bal++
      case ')':
         bal--
      default:
         res += int64(cval[pos])
         tab[i] = ')'
         bal--
         heap.Push(myQ, &entry{oval[pos]-cval[pos], i})
         pos++
      }
      if bal < 0 {
         if myQ.Len() > 0 {
            temp := heap.Pop(myQ).(*entry)
            //fmt.Printf("  %v\n", heap.Pop(myQ))
            res += int64(temp.cost)
            tab[temp.pos] = '('
            bal += 2
         } else {
            bal = inf
            break
         }
      }
   }
   tempTab = string(tab)
   if bal == 0 {
      fmt.Printf("%v\n%v\n", res, tempTab)
   } else {
      fmt.Printf("-1\n")
   }
}

package main

import (
	"bytes"
	"container/heap"
	"fmt"
	"io/ioutil"
	"os"
)

type Node struct {
	Index int
	Value int
}

type NodeHeap []*Node

func (h NodeHeap) Len() int {
	return len(h)
}

func (h NodeHeap) Less(i, j int) bool {
	return h[i].Value > h[j].Value
}

func (h NodeHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *NodeHeap) Push(x interface{}) {
	*h = append(*h, x.(*Node))
}

func (h *NodeHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func main() {
	left := [50000]int{}
	right := [50000]int{}
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var s string
	fmt.Fscanf(reader, "%s\n", &s)
	rawBytes := []byte(s)
	resultBytes := make([]byte, len(rawBytes))

	qCount := 0
	cost := 0

	h := &NodeHeap{}
	heap.Init(h)

	for i := 0; i < len(rawBytes); i++ {
		if rawBytes[i] == '(' {
			resultBytes[i] = '('
		} else if rawBytes[i] == ')' {
			resultBytes[i] = ')'
		} else if rawBytes[i] == '?' {
			resultBytes[i] = ')'
			fmt.Fscanf(reader, "%d %d\n", &left[qCount], &right[qCount])
			cost += right[qCount]
			qCount++
		}
	}
	leftCount := 0
	curQues := 0
	for i := 0; i < len(rawBytes); i++ {
		if rawBytes[i] == '(' {
			leftCount++
		} else if rawBytes[i] == ')' {
			leftCount--
		} else if rawBytes[i] == '?' {
			heap.Push(h, &Node{i, right[curQues] - left[curQues]})
			leftCount--
			curQues++
		}
		if leftCount < 0 {
			if len(*h) == 0 {
				fmt.Printf("-1")
				return
			}
			node := heap.Pop(h).(*Node)
			cost -= node.Value
			resultBytes[node.Index] = '('
			leftCount += 2
		}
	}
	fmt.Printf("%d\n", cost)
	fmt.Printf("%s", string(resultBytes))

}

package main

import (
	"bytes"
	"container/heap"
	"fmt"
	"io/ioutil"
	"os"
)

type Node struct {
	Index int
	Value int64
}

type NodeHeap []*Node

func (h NodeHeap) Len() int {
	return len(h)
}

func (h NodeHeap) Less(i, j int) bool {
	return h[i].Value > h[j].Value
}

func (h NodeHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *NodeHeap) Push(x interface{}) {
	*h = append(*h, x.(*Node))
}

func (h *NodeHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func main() {
	left := [50000]int64{}
	right := [50000]int64{}
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var s string
	fmt.Fscanf(reader, "%s\n", &s)
	rawBytes := []byte(s)
	resultBytes := make([]byte, len(rawBytes))

	qCount := 0
	cost := int64(0)

	h := &NodeHeap{}
	heap.Init(h)

	for i := 0; i < len(rawBytes); i++ {
		if rawBytes[i] == '(' {
			resultBytes[i] = '('
		} else if rawBytes[i] == ')' {
			resultBytes[i] = ')'
		} else if rawBytes[i] == '?' {
			resultBytes[i] = ')'
			fmt.Fscanf(reader, "%d %d\n", &left[qCount], &right[qCount])
			cost += right[qCount]
			qCount++
		}
	}
	leftCount := 0
	curQues := 0
	for i := 0; i < len(rawBytes); i++ {
		if rawBytes[i] == '(' {
			leftCount++
		} else if rawBytes[i] == ')' {
			leftCount--
		} else if rawBytes[i] == '?' {
			heap.Push(h, &Node{i, right[curQues] - left[curQues]})
			leftCount--
			curQues++
		}
		if leftCount < 0 {
			if len(*h) == 0 {
				fmt.Printf("-1")
				return
			}
			node := heap.Pop(h).(*Node)
			cost -= node.Value
			resultBytes[node.Index] = '('
			leftCount += 2
		}
	}
	fmt.Printf("%d\n", cost)
	fmt.Printf("%s", string(resultBytes))

}

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
)

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

	s, _ := reader.ReadString('\n')

	var cnt int
	for i := 0; i < len(s); i++ {
		if s[i] == '?' {
			cnt++
		}
	}
	cost := make([][]int, cnt)
	for i := 0; i < cnt; i++ {
		cost[i] = readNNums(reader, 2)
	}
	res, ss := solve(s, cost)
	fmt.Println(res)
	if res < 0 {
		return
	}

	fmt.Println(ss)
}

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') {
			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(s string, cost [][]int) (int64, string) {
	ss := []byte(s)
	var open int
	pq := make(PriorityQueue, 0, len(s))
	var res int64
	for i, j := 0, 0; i < len(s); i++ {
		if s[i] != '(' && s[i] != ')' && s[i] != '?' {
			break
		}
		if s[i] == '(' {
			open++
		} else {
			open--
		}

		if s[i] == '?' {
			cur := cost[j]
			j++
			a, b := cur[0], cur[1]
			ss[i] = ')'
			heap.Push(&pq, &Item{b - a, i, -1})
			res += int64(b)
		}

		if open < 0 {
			if len(pq) == 0 {
				break
			}
			x := heap.Pop(&pq).(*Item)
			ss[x.second] = '('
			res += int64(-x.first)
			open += 2
		}
	}

	if open < 0 {
		return -1, ""
	}
	return res, string(ss)
}

type Item struct {
	first  int
	second int
	index  int
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].first > pq[j].first
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
)

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

	s, _ := reader.ReadString('\n')

	var cnt int
	for i := 0; i < len(s); i++ {
		if s[i] == '?' {
			cnt++
		}
	}
	cost := make([][]int, cnt)
	for i := 0; i < cnt; i++ {
		cost[i] = readNNums(reader, 2)
	}
	res, ss := solve(s, cost)
	fmt.Println(res)
	if res < 0 {
		return
	}

	fmt.Println(ss)
}

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') {
			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(s string, cost [][]int) (int64, string) {
	ss := []byte(s)
	var open int
	pq := make(PriorityQueue, 0, len(s))
	var res int64
	for i, j := 0, 0; i < len(s); i++ {
		if s[i] == '\n' {
			break
		}
		if s[i] == '(' {
			open++
		} else {
			open--
		}

		if s[i] == '?' {
			cur := cost[j]
			j++
			a, b := cur[0], cur[1]
			ss[i] = ')'
			heap.Push(&pq, &Item{b - a, i, -1})
			res += int64(b)
		}

		if open < 0 {
			if len(pq) == 0 {
				break
			}
			x := heap.Pop(&pq).(*Item)
			ss[x.second] = '('
			res += int64(-x.first)
			open += 2
		}
	}

	if open < 0 {
		return -1, ""
	}
	return res, string(ss)
}

type Item struct {
	first  int
	second int
	index  int
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].first > pq[j].first
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}


Gaurang has grown up in a mystical universe. He is faced by $$$n$$$ consecutive 2D planes. He shoots a particle of decay age $$$k$$$ at the planes.A particle can pass through a plane directly, however, every plane produces an identical copy of the particle going in the opposite direction with a decay age $$$k-1$$$. If a particle has decay age equal to $$$1$$$, it will NOT produce a copy.For example, if there are two planes and a particle is shot with decay age $$$3$$$ (towards the right), the process is as follows: (here, $$$D(x)$$$ refers to a single particle with decay age $$$x$$$)  the first plane produces a $$$D(2)$$$ to the left and lets $$$D(3)$$$ continue on to the right;  the second plane produces a $$$D(2)$$$ to the left and lets $$$D(3)$$$ continue on to the right;  the first plane lets $$$D(2)$$$ continue on to the left and produces a $$$D(1)$$$ to the right;  the second plane lets $$$D(1)$$$ continue on to the right ($$$D(1)$$$ cannot produce any copies). In total, the final multiset $$$S$$$ of particles is $$$\{D(3), D(2), D(2), D(1)\}$$$. (See notes for visual explanation of this test case.)Gaurang is unable to cope up with the complexity of this situation when the number of planes is too large. Help Gaurang find the size of the multiset $$$S$$$, given $$$n$$$ and $$$k$$$.Since the size of the multiset can be very large, you have to output it modulo $$$10^9+7$$$.Note: Particles can go back and forth between the planes without colliding with each other.

The first line of the input contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Then, $$$t$$$ lines follow, each containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 1000$$$).  Additionally, the sum of $$$n$$$ over all test cases will not exceed $$$1000$$$, and the sum of $$$k$$$ over all test cases will not exceed $$$1000$$$. All test cases in one test are different.

Output $$$t$$$ integers. The $$$i$$$-th of them should be equal to the answer to the $$$i$$$-th test case.

NoteLet us explain the first example with four test cases. Test case 1: ($$$n = 2$$$, $$$k = 3$$$) is already explained in the problem statement.See the below figure of this simulation. Each straight line with a different color represents the path of a different particle. As you can see, there are four distinct particles in the multiset. Note that the vertical spacing between reflected particles is for visual clarity only (as mentioned before, no two distinct particles collide with each other)  Test case 2: ($$$n = 2$$$, $$$k = 2$$$) is explained as follows: the first plane produces a $$$D(1)$$$ to the left and lets $$$D(2)$$$ continue on to the right;  the second plane produces a $$$D(1)$$$ to the left and lets $$$D(2)$$$ continue on to the right;  the first plane lets $$$D(1)$$$ continue on to the left ($$$D(1)$$$ cannot produce any copies).Total size of multiset obtained $$$\{D(1), D(1), D(2)\}$$$ is equal to three.Test case 3: ($$$n = 3$$$, $$$k = 1$$$), there are three planes, but decay age is only one. So no new copies are produced while the one particle passes through the planes. Hence, the answer is one.Test case 4: ($$$n = 1$$$, $$$k = 3$$$) there is only one plane. The particle produces a new copy to the left. The multiset $$$\{D(2), D(3)\}$$$ is of size two.

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	const mod = 1000000007
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for c:=1;c<=t;c++{
		var n, k int
		fmt.Fscan(in,&n,&k)
		a := make([]int,n+5)
		cnt:=0
		ans:=0
		for i:=k;i>=1;i--{
			cnt++
			if i==k{
				ans += 1
				for j:=1;j<=n;j++{
					a[j]=1
				}
				continue
			}
			if cnt%2==0{
				pre := 0
				for j:=n;j>=1;j--{
					ans = (ans%(mod) + a[j]%(mod))%(mod)
					temp := a[j]
					a[j] = pre
					pre = (pre%(mod) + temp%(mod))%(mod)
				}
			}else{
				pre := 0
				for j:=1;j<=n;j++{
					ans = (ans%(mod) + a[j]%(mod))%(mod)
					temp := a[j]
					a[j] = pre
					pre = (pre%(mod) + temp%(mod))%(mod)
				}
			}
		}
		fmt.Fprintln(out,ans%mod)
	}
}

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, k := readTwoNums(reader)
		res := solve(n, k)
		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
}

const MOD = 1000000007

func modAdd(a *int, b int) {
	*a += b
	if *a >= MOD {
		*a -= MOD
	}
}

func solve(n, k int) int {
	dp := make([][]int, n)
	for i := 0; i < n; i++ {
		dp[i] = make([]int, k+1)
	}

	for j := 1; j <= k; j++ {

		if j > 2 {
			var sum int
			for i := 0; i < n-1; i++ {
				modAdd(&sum, dp[i][j-2])
				dp[i][j] = sum
			}
		}
		dp[n-1][j] = 1
		for i := n - 2; i >= 0; i-- {
			// go right and go down with j - 1
			modAdd(&dp[i][j], dp[i+1][j])
			if j > 1 {
				// go left with j - 1
				modAdd(&dp[i][j], 1)
			}
		}
	}

	if k > 1 {
		modAdd(&dp[0][k], 1)
	}

	return dp[0][k]
}

package main

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

const N = 1e3 + 7
const mod = 1e9 + 7

var ps [N][N]int

func solve() {
	var n, k int
	Scan(&n, &k)
	ans := 1
	if k > 1 {
		ans += n
		for i := 1; i <= n; i++ {
			ps[k-1][i] = 1
		}
	}
	turn := 0
	for i := k - 2; i > 0; i-- {
		if turn == 0 {
			for j := n - 1; j > 0; j-- {
				ps[i][j] = ps[i][j+1] + ps[i+1][j+1]
				ps[i][j] %= mod
				ans += ps[i][j]
				ans %= mod
			}
		} else {
			for j := 2; j <= n; j++ {
				ps[i][j] = ps[i][j-1] + ps[i+1][j-1]
				ps[i][j] %= mod
				ans += ps[i][j]
				ans %= mod
			}
		}
		turn = 1 - turn
	}
	Println(ans)
	for i := 1; i <= k; i++ {
		for j := 0; j <= n; j++ {
			ps[i][j] = 0
		}
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	var T int
	Scan(&T)
	for ; T > 0; T-- {
		solve()
	}
}

package main

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

const N int = 1e3 + 5
var stdIn = bufio.NewReader(os.Stdin)
var stdOut = bufio.NewWriter(os.Stdout)
type ll int64
const mod ll = 1e9 + 7
func main() {
	defer stdOut.Flush()
	var t int
	fmt.Fscan(stdIn, &t)
	a := [N][N]ll{}

	for t > 0{
		var n, k int
		fmt.Fscan(stdIn, &n ,&k)
		for i := 0; i <= n; i ++ {
			a[1][i] = 1
		}

		for age := 2; age <= k; age ++ {
			a[age][0] = 1
			for plane := 1; plane <= n; plane ++ {
				a[age][plane] =(a[age][plane - 1] + a[age - 1][n - plane]) % mod
				//fmt.Fprintf(stdOut, "%d , %d : ", age, plane)
				//fmt.Fprintln(stdOut, a[age][plane])
			}
		}
		fmt.Fprintln(stdOut, a[k][n])
		t --
	}

}

package main

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

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

const mod = 1000000007

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

func toInt(buf []byte) (n int) {
	for _, v := range buf {
		n = (n * 10) + int(v-'0')
	}
	return
}

type Pair struct {
	a, b int
}

type Pairs []Pair

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

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

//define constants here
const (
	N = 1001
	K = 1001
)

//define global variables here
var (
	dp   = [N][K][2]int{}
	n, k int
)

//Write your code from here

func solve(cur, k, dir int) int {

	if k == 1 {
		return 1
	}

	if dp[cur][k][dir] != -1 {
		return dp[cur][k][dir]
	}

	ans := 2 //me and my copy
	//dir are two make copy forward and one backward
	if dir == 1 {

		if cur < n {
			ans += solve(cur+1, k, dir) - 1
		}
		ans %= mod
		if cur > 1 {
			ans += solve(cur-1, k-1, 1-dir) - 1
		}

		ans %= mod
		dp[cur][k][dir] = ans

	} else {

		if cur > 1 {
			ans += solve(cur-1, k, dir) - 1
		}
		ans %= mod
		if cur < n {
			ans += solve(cur+1, k-1, 1-dir) - 1
		}
		ans %= mod
		dp[cur][k][dir] = ans
	}
	return ans

}

func main() {
	defer writer.Flush()
	var t int
	scanf("%d\n", &t)

	for t > 0 {
		scanf("%d %d\n", &n, &k)

		for i := 0; i < 1001; i++ {
			for j := 0; j < 1001; j++ {
				dp[i][j][0] = -1
				dp[i][j][1] = -1
			}
		}
		printf("%d\n", solve(1, k, 1))
		t--
	}

}

package main
import ."fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	f := [1001][1001]int{}
	var T, n, k int
	for Scan(&T); T > 0; T-- {
		Scan(&n, &k)
		for i := 1; i <= k; i++ {
			f[i][0] = 1
			for j := 1; j <= n; j++ {
				f[i][j] = (f[i][j-1] + f[i-1][n-j]) % (1e9 + 7)
			}
		}
		Println(f[k][n])
	}
}


The process of mammoth's genome decoding in Berland comes to its end!One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.

The first line contains the integer n (4 ≤ n ≤ 255) — the length of the genome. The second line contains the string s of length n — the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.

If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).

NoteIn the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.In the third and the fourth examples it is impossible to decode the genom.

package main

import (
	"fmt"
)

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

func main() {

	var n int
	fmt.Scanf("%d\n", &n)

	var str string
	fmt.Scanf("%s", &str)

	s := []rune(str)

	var cnt[5] int

	for i:=0; i<n; i++ {

		if (s[i]=='A') {
			cnt[0]++;
		} else if (s[i]=='C') {
			cnt[1]++;
		} else if (s[i]=='G') {
			cnt[2]++;
		} else if (s[i]=='T') {
			cnt[3]++;
		}

	}

	var x int

	x = max(max(cnt[0], cnt[1]), max(cnt[2], cnt[3]))

	for i:=0; i<4; i++ {
		cnt[i] -= x
	}

	for i:=0; i<n; i++ {
		if (s[i]=='?') {
			if (cnt[0] < 0) {
				s[i] = 'A'
				cnt[0]++
			} else if (cnt[1] < 0) {
				s[i] = 'C'
				cnt[1]++
			} else if (cnt[2] < 0) {
				s[i] = 'G'
				cnt[2]++
			} else if (cnt[3] < 0) {
				s[i] = 'T'
				cnt[3]++
			} else {
				for j:=0; j<4; j++ {
					cnt[j]--
				}
				s[i] = 'A'
				cnt[0]++
			}
		}
	}

	if (cnt[0]==0 && cnt[1]==0 && cnt[2] == 0 && cnt[3] == 0) {
		fmt.Printf("%s", string(s))
	} else {
		fmt.Printf("===")
	}
}

package main

import (
	"fmt"
)

func main() {
	var s string
	var n int

	fmt.Scanf("%d\n", &n)
	fmt.Scanf("%s\n", &s)

	if n%4 != 0 {
		fmt.Println("===")
		return
	}

	counts := map[rune]int{
		'A': 0,
		'C': 0,
		'G': 0,
		'T': 0,
	}
	for _, c := range s {
		if c == '?' {
			continue
		}
		counts[c]++
	}

	for _, count := range counts {
		if count > n/4 {
			fmt.Println("===")
			return
		}
	}

	out := make([]byte, len(s))
	for i, c := range s {
		if c != '?' {
			out[i] = byte(c)
			continue
		}

		var replace rune
		// fmt.Println(counts)
		for c, count := range counts {
			if count >= n/4 {
				continue
			}
			replace = c
			counts[c]++
			break
		}

		out[i] = byte(replace)
	}

	fmt.Println(string(out))
}

package main

import(
	"fmt"
	"os"
)

func main() {
	var a, c, g, t int = 0, 0, 0, 0
	var n int
	var s string

	fmt.Fscanf(os.Stdin, "%d\n%s\n", &n, &s)

	S := []rune(s)

	div := n / 4.0

	for _, r := range S {
		switch r {
		case 'A':
			a++
		case 'C':
			c++
		case 'G':
			g++
		case 'T':
			t++
		}
	}

	if n % 4 == 0 && a <= div && c <= div && g <= div && t <= div {
		for i, r := range S {
			if r != '?' {
				continue
			}
			if a < div {
				S[i] = 'A'
				a++
				continue
			}
			if c < div {
				S[i] = 'C'
				c++
				continue
			}
			if g < div {
				S[i] = 'G'
				g++
				continue
			}
			if t < div {
				S[i] = 'T'
				t++
				continue
			}
		}
	}

	if a == div && c == div && g == div && t == div {
		fmt.Println(string(S))
	} else {
		fmt.Println("===")
	}
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scanln(&n)

	var s string
	fmt.Scan(&s)

	var afreq, cfreq, gfreq, tfreq, qfreq int
	for _, c := range s {
		switch c {
		case 'A':
			afreq++
		case 'G':
			gfreq++
		case 'C':
			cfreq++
		case 'T':
			tfreq++
		case '?':
			qfreq++
		}
	}

	var ss = []byte(s)

	for i := range s {
		if s[i] == '?' {
			if gfreq < cfreq || gfreq < tfreq || gfreq < afreq {
				ss[i] = 'G'
				gfreq++
			} else if cfreq < gfreq || cfreq < tfreq || cfreq < afreq {
				ss[i] = 'C'
				cfreq++
			} else if tfreq < cfreq || tfreq < gfreq || tfreq < afreq {
				ss[i] = 'T'
				tfreq++
			} else {
				ss[i] = 'A'
				afreq++
			}
		}
	}

	if afreq == gfreq && afreq == cfreq && afreq == tfreq {
		fmt.Println(string(ss))
	} else {
		fmt.Println("===")
	}
}

package main

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

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	S := sc.NextLine()

	mp := map[byte]int{}
	mx := N / 4

	for _, v := range S {
		if v == '?' {
			continue
		}
		mp[byte(v)]++
		if mp[byte(v)] > mx {
			fmt.Println("===")
			return
		}
	}
	ans := make([]byte, 0)

	for _, v := range S {
		if v == '?' {
			a := byte(' ')
			for _, c := range "AGCT" {
				if mp[byte(c)] < mx {
					mp[byte(c)]++
					a = byte(c)
					break
				}
			}
			if a == ' ' {
				fmt.Println("===")
				return
			}
			ans = append(ans, a)

		} else {
			ans = append(ans, byte(v))
		}
	}
	fmt.Println(string(ans))

}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r:rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var s string
	var n int

	fmt.Scanf("%d\n", &n)
	fmt.Scanf("%s\n", &s)

	if n%4 != 0 {
		fmt.Println("===")
		return
	}

	counts := map[rune]int{
		'A': 0,
		'C': 0,
		'G': 0,
		'T': 0,
	}
	for _, c := range s {
		if c == '?' {
			continue
		}
		counts[c]++
	}

	for _, count := range counts {
		if count > n/4 {
			fmt.Println("===")
			return
		}
	}

	out := make([]byte, len(s))
	for i, c := range s {
		if c != '?' {
			out[i] = byte(c)
			continue
		}

		var replace rune
		for c, count := range counts {
			if count > n/4 {
				continue
			}
			replace = c
			counts[c]++
			break
		}

		out[i] = byte(replace)
	}

	fmt.Println(string(out))
}


Boy Dima gave Julian a birthday present — set $$$B$$$ consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two $$$i$$$ and $$$j$$$ with an edge if $$$|i - j|$$$ belongs to $$$B$$$.Unfortunately, Julian doesn't like the graph, that was built using $$$B$$$. Alex decided to rectify the situation, so he wants to erase some numbers from $$$B$$$, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from $$$B$$$ so that graph constructed on the new set is bipartite.Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.

First line contains an integer $$$n ~ (1 \leqslant n \leqslant 200\,000)$$$ — size of $$$B$$$ Second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n ~ (1 \leqslant b_i \leqslant 10^{18})$$$ — numbers of $$$B$$$, all $$$b_i$$$ are unique

In the first line print single integer $$$k$$$ – the number of erased elements. In the second line print $$$k$$$ integers — values of erased elements. If there are multiple answers, print any of them.

// Author: sighduck
// URL: https://codeforces.com/contest/1220/problem/D

package main

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

func multiplicityOfTwo(x int64) int64 {
	if x%2 == 0 {
		return 1 + multiplicityOfTwo(x/2)
	}
	return 0
}

func Solve(n int, b []int64) []int64 {
	solution := []int64{}
	powerOfTwoMap := make(map[int64]int)
	maxMultiplicity := int64(-1)
	maxMultiplicityCount := -1
	for _, elem := range b {
		multiplicity := multiplicityOfTwo(elem)
		powerOfTwoMap[multiplicity] += 1
		if powerOfTwoMap[multiplicity] > maxMultiplicityCount {
			maxMultiplicity = multiplicity
			maxMultiplicityCount = powerOfTwoMap[multiplicity]
		}
	}
	for _, elem := range b {
		if multiplicityOfTwo(elem) != maxMultiplicity {
			solution = append(solution, elem)
		}
	}
	return solution
}

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

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

	solution := Solve(n, b)
	fmt.Fprintf(writer, "%d\n", len(solution))
	for _, elem := range solution {
		fmt.Fprintf(writer, "%d\n", elem)
	}
}