package main

import "fmt"

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

	var s string
	fmt.Scan(&s)
	data := []rune(s)

	isAnswerPositive := false
	isZeroFound, isOneFound, isDotFound, dotPos := false, false, false, 0
	for i := 0; i < p; i++ {
		if i + p < n {
			isZeroFound, isOneFound, isDotFound, dotPos = false, false, false, 0
			for j := i; j < n; j += p {
				if data[j] == '.' {
					isDotFound = true
					dotPos = j

					if !isZeroFound && !isOneFound {
						if j + p < n {
							if data[j+p] == '1' {
								isOneFound = true
							}
							if data[j+p] == '0' {
								isZeroFound = true
							}
						}
					}
				}
				if data[j] == '1' {
					isOneFound = true
				}
				if data[j] == '0' {
					isZeroFound = true
				}

				if isDotFound || (isZeroFound && isOneFound) {
					isAnswerPositive = true
					break
				}
			}
			if isAnswerPositive {
				break
			}
		} else {
			break
		}
	}
	if !isAnswerPositive || p == n {
		fmt.Print("NO")
	} else {
		for i := 0; i < n; i++ {
			if isDotFound && i == dotPos {
				if isOneFound {
					fmt.Print("0")
				} else {
					fmt.Print("1")
				}
				continue
			}
			if data[i] == '.' {
				fmt.Print("0")
			} else {
				fmt.Print(string(data[i]))
			}
		}
	}
}

package main

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

func Init() {}
func Solve(io *FastIO) {
	n, p, s := io.NextInt(), io.NextInt(), io.NextString()
	o := make([]byte, 0, 0)
	var bol bool
	for i := 0; i < n; i++ {
		o = append(o, s[i])
		if i < p {
			continue
		}
		bol = true
		if o[i%p] == s[i] {
			bol = false
			if s[i] == '.' {
				o[i%p], o[i] = '0', '1'
				bol = true
			}
		} else if o[i] == '.' {
			if o[i%p] == '0' {
				o[i] = '1'
			} else {
				o[i] = '0'
			}
		} else if o[i%p] == '.' {
			if o[i] == '0' {
				o[i%p] = '1'
			} else if o[i] == '1' {
				o[i%p] = '0'
			}
		}
		if bol {
			break
		}
	}
	if !bol {
		io.Println("No")
		return
	}
	for _, i := range bytes.Runes(o) {
		if i == '.' {
			io.Printf("0")
		} else {
			io.Printf(string(i))
		}
	}
	//io.Printf("\n") //
	for _, i := range s[len(o):] {
		if i == '.' {
			io.Printf("0")
		} else {
			io.Printf(string(i))
		}
	}
	io.Printf("\n")
}

type FastIO struct {
	//by megaspazz
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}
func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = res*10 + int(c-'0')
		c = io.NextChar()
	}
	return res * sgn
}
func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = int64(-1)
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = res*10 + int64(c-'0')
		c = io.NextChar()
	}
	return res * sgn
}
func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}
func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size+offset)
	for i := 0; i < size; i++ {
		arr[i+offset] = io.NextInt()
	}
	return arr
}
func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}
func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size+offset)
	for i := 0; i < size; i++ {
		arr[i+offset] = io.NextLong()
	}
	return arr
}
func (io *FastIO) NextString() string {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}
func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}
func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}
func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}
func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}
func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}
func IsLineBreakChar(c byte) bool {
	switch c {
	case 0, '\n', '\r':
		return true
	default:
		return false
	}
}
func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}

package main

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

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

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

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

func printText(text string) {
	writer.WriteString(text)
}

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

	var n, p int = readInt32(), readInt32()
	var s string = readText()
	ss := []byte(s)
	isYes := false

	i := 0
	for i+p < n {

		if s[i] == '.' {
			switch s[i+p] {
			case '0':
				ss[i] = '1'
			case '1':
				ss[i] = '0'
			case '.':
				ss[i] = '0'
				ss[i+p] = '1'
			}
			isYes = true
		}

		if s[i] == '0' {
			switch s[i+p] {
			case '1':
				ss[i+p] = '1'
				isYes = true
			case '.':
				ss[i+p] = '1'
				isYes = true
			}
		}

		if s[i] == '1' {
			switch s[i+p] {
			case '0':
				ss[i+p] = '0'
				isYes = true
			case '.':
				ss[i+p] = '0'
				isYes = true
			}
		}

		i++
	}

	if isYes {
		for i := range ss {
			if ss[i] == '.' {
				ss[i] = '0'
			}
		}
		printText(string(ss))
	} else {
		printText("No")
	}
}

package main

import (
	"fmt"
)

func main() {
	var n, p, i int
	var s string
	fmt.Scanf("%d %d\n", &n, &p)
	fmt.Scanln(&s)

	flag := false
	runes := []rune(s)
	for i = 0; i < n-p; i++ {
		if runes[i] != runes[i+p] || (runes[i] == '.' && runes[i+p] == '.') {
			flag = true
		}
	}

	if flag {
		for i = 0; i < n; i++ {
			if runes[i] == '.' {
				if i+p < n && runes[i+p] == '0' {
					runes[i] = '1'
				} else if i+p < n && runes[i+p] == '1' {
					runes[i] = '0'
				} else if i-p >= 0 && runes[i-p] == '0' {
					runes[i] = '1'
				} else if i-p >= 0 && runes[i-p] == '1' {
					runes[i] = '0'
				} else if i+p < n && runes[i+p] == '.' {
					runes[i] = '0'
					runes[i+p] = '1'
				} else if i-p >= 0 && runes[i-p] == '.' {
					runes[i] = '0'
					runes[i-p] = '1'
				} else {
					runes[i] = '0'
				}
			}
		}

		fmt.Println(string(runes))
	} else {
		fmt.Println("No")
	}

}

package main

import "fmt"

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

	var s string
	fmt.Scan(&s)
	data := []rune(s)

	isAnswerPositive := false
	isZeroFound, isOneFound, isDotFound, dotPos := false, false, false, 0
	for i := 0; i < p; i++ {
		isZeroFound, isOneFound, isDotFound, dotPos = false, false, false, 0
		if i + p < n {
			for j := i; j < n; j += p {
				if data[j] == '.' {
					isDotFound = true
					dotPos = j
				}
				if data[j] == '1' {
					isOneFound = true
				}
				if data[j] == '0' {
					isZeroFound = true
				}

				if isDotFound || (isZeroFound && isOneFound) {
					isAnswerPositive = true
					break
				}
			}
			if isAnswerPositive {
				break
			}
		}
	}
	if !isAnswerPositive || p == n {
		fmt.Print("NO")
	} else {
		for i := 0; i < n; i++ {
			if isDotFound && i == dotPos {
				if isOneFound {
					fmt.Print("0")
				} else {
					fmt.Print("1")
				}
				continue
			}
			if data[i] == '.' {
				fmt.Print("0")
			} else {
				fmt.Print(string(data[i]))
			}
		}
	}
}

package main

import "fmt"

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

	var s string
	fmt.Scan(&s)
	data := []rune(s)

	isAnswerPositive := false
	isZeroFound, isOneFound, isDotFound, dotPos := false, false, false, 0
	for i := 0; i < p; i++ {
		isZeroFound, isOneFound, isDotFound, dotPos = false, false, false, 0
		for j := i; j < n; j += p {
			if data[j] == '.' {
				isDotFound = true
				dotPos = j
			}
			if data[j] == '1' {
				isOneFound = true
			}
			if data[j] == '0' {
				isZeroFound = true
			}

			if isDotFound || (isZeroFound && isOneFound) {
				isAnswerPositive = true
				break
			}
		}
		if isAnswerPositive {
			break
		}
	}
	if !isAnswerPositive || p == n {
		fmt.Print("NO")
	} else {
		for i := 0; i < n; i++ {
			if isDotFound && i == dotPos {
				if isOneFound {
					fmt.Print("0")
				} else {
					fmt.Print("1")
				}
				continue
			}
			if data[i] == '.' {
				fmt.Print("0")
			} else {
				fmt.Print(string(data[i]))
			}
		}
	}
}

package main

import "fmt"

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

	var s string
	fmt.Scan(&s)
	data := []rune(s)

	isAnswerPositive := false
	isZeroFound, isOneFound, isDotFound, dotPos := false, false, false, 0
	for i := 0; i < p; i++ {
		isZeroFound, isOneFound, isDotFound, dotPos = false, false, false, 0
		for j := i+p; j < n; j += p {
			if data[j] == '.' {
				isDotFound = true
				dotPos = j
			}
			if data[j] == '1' {
				isOneFound = true
			}
			if data[j] == '0' {
				isZeroFound = true
			}

			if isDotFound || (isZeroFound && isOneFound) {
				isAnswerPositive = true
				break
			}
		}
		if isAnswerPositive {
			break
		}
	}
	if !isAnswerPositive || p == n {
		fmt.Print("NO")
	} else {
		for i := 0; i < n; i++ {
			if isDotFound && i == dotPos {
				if isOneFound {
					fmt.Print("0")
				} else {
					fmt.Print("1")
				}
				continue
			}
			if data[i] == '.' {
				fmt.Print("0")
			} else {
				fmt.Print(string(data[i]))
			}
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n, p, i int
	var s string
	fmt.Scanf("%d %d\n", &n, &p)
	fmt.Scanln(&s)

	flag := false
	runes := []rune(s)
	for i = 0; i < n-p; i++ {
		if runes[i] != runes[i+p] {
			flag = true
		}
	}

	if flag {
		for i = 0; i < n; i++ {
			if runes[i] == '.' {
				if i+p < n && runes[i+p] == '0' {
					runes[i] = '1'
				} else if i+p < n && runes[i+p] == '1' {
					runes[i] = '0'
				} else if i-p >= 0 && runes[i-p] == '0' {
					runes[i] = '1'
				} else if i-p >= 0 && runes[i-p] == '1' {
					runes[i] = '0'
				} else if i+p < n && runes[i+p] == '.' {
					runes[i] = '0'
					runes[i+p] = '1'
				} else if i-p >= 0 && runes[i-p] == '.' {
					runes[i] = '0'
					runes[i-p] = '1'
				} else {
					runes[i] = '0'
				}
			}
		}

		fmt.Println(string(runes))
	} else {
		fmt.Println("No")
	}

}


package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t, n   int
)

func solve(b []string) string {
	found := false
	x := b[0]
	for i := 1; i < len(b); i++ {
		if b[i][0] != b[i-1][1] {
			found = true
			x += b[i]
		} else {
			x += string(b[i][1])
		}
	}
	if !found {
		x += "a"
	}
	return x
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		b := make([]string, n-2)
		for i := 0; i < n-2; i++ {
			fmt.Fscan(reader, &b[i])
		}
		fmt.Println(solve(b))
	}
}

package main

import "fmt"

var (
//n, strs = 7, []string{"ab", "bb", "ba", "aa", "ba"}
)

func main() {
	t := 0
	fmt.Scan(&t)
	for t > 0 {
		n := 0
		fmt.Scan(&n)
		n -= 2
		strs := []string{}
		for n > 0 {
			temp := ""
			fmt.Scan(&temp)
			strs = append(strs, temp)
			n--
		}
		fmt.Println(solve(strs))
		t--
	}
}

func solve(strs []string) string {

	result := ""

	// record := map[string]bool{}
	// newStrs := []string{}
	// for i := range strs {
	// 	_, exist := record[strs[i]]
	// 	if !exist {
	// 		record[strs[i]] = true
	// 		newStrs = append(newStrs, strs[i])
	// 	}
	// }

	for i := range strs {

		switch check(strs[i], result) {
		case 0:
			continue
		case 1:
			result = string(strs[i][0]) + result
		case 2:
			result = result + string(strs[i][1])
		default:
			result += strs[i]
		}

	}

	count := len(strs) + 2 - len(result)
	for count > 0 {
		result += "a"
		count--
	}

	return result
}

func check(str string, result string) int {

	//size := len(str)
	if len(result) == 0 {
		return 3
	}

	// for i := 0; i+size <= len(result); i++ {
	// 	if result[i:i+size] == str {
	// 		return 0
	// 	}
	// }

	// if str[1] == result[0] {
	// 	return 1
	// }

	if str[0] == result[len(result)-1] {
		return 2
	}

	return 3

}

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		list:= make([]string,n-2)
		for j:=0;j<n-2;j++{
			fmt.Fscan(in,&list[j])
		}
		var output string
		if len(list) == 1 {
			fmt.Fprintln(out,string(list[0])+"b")
			continue
		}
		count:=len(list)*2-n
		output+= string(list[0])
		for j:=1;j<len(list);j++{
			if string(list[j-1][1]) == string(list[j][0]) && count > 0{
				count--
				output+= string(list[j][1])
				continue
			}
			output+= list[j]
		}
		fmt.Fprintln(out,output)
	}
}

package main

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

func CF1618B(rawIn io.Reader, rawOut io.Writer) {
	in := bufio.NewReader(rawIn)
	out := bufio.NewWriter(rawOut)
	defer out.Flush()

	var cases int
	fmt.Fscan(in, &cases)
	for cc := 0; cc < cases; cc++ {
		var n int
		fmt.Fscan(in, &n)
		segments := make([]string, n-2)
		for i := 0; i < len(segments); i++ {
			fmt.Fscan(in, &segments[i])
		}

		var buffer strings.Builder
		buffer.WriteString(segments[0])
		for i := 0; i < len(segments)-1; i++ {
			if segments[i][1] == segments[i+1][0] {
				buffer.WriteByte(segments[i+1][1])
			} else {
				buffer.WriteByte(segments[i+1][0])
				buffer.WriteByte(segments[i+1][1])
			}
		}
		candidate := buffer.String()
		if len(candidate) < n {
			candidate = candidate + string(candidate[len(candidate)-1])
		}
		fmt.Fprintln(out, candidate)
	}
}

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

package main

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

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

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

		var prev string
		fmt.Fscan(in, &prev)
		var buf bytes.Buffer
		buf.WriteByte(prev[0])
		for i := 1; i < size-2; i++ {
			var bg string
			fmt.Fscan(in, &bg)
			if bg[0] == prev[1] {
				buf.WriteByte(bg[0])
				prev = bg
			} else {
				buf.WriteByte(prev[1])
				buf.WriteByte(bg[0])
				prev = bg
			}
		}

		buf.WriteByte(prev[1])
		if len(buf.String()) < size {
			buf.WriteByte('b')
		}
		fmt.Fprintln(out, buf.String())
	}
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < n; i++ {
		scanner.Scan()
		scanner.Scan()
		bigrams := strings.Fields(scanner.Text())
		found := false
		fmt.Printf("%c", bigrams[0][0])
		for j := 1; j < len(bigrams); j++ {
			if bigrams[j-1][1] != bigrams[j][0] {
				fmt.Printf("%c", bigrams[j-1][1])
				found = true
			}
			fmt.Printf("%c", bigrams[j][0])
		}
		last := bigrams[len(bigrams)-1][1]
		if !found {
			fmt.Printf("%c%c\n", last, last)
		} else {
			fmt.Printf("%c\n", last)
		}
	}
}

package main

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

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

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

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

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

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

/**
Run solve the problem CF1618B
Date: 15/12/21
User: epradere
URL: https://codeforces.com/contest/1618/problem/B
Problem: CF1618B
**/
func (in *CF1618B) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		var sb strings.Builder
		last := ""
		for i := 0; i < n-2; i++ {
			str := in.NextString()
			if i == 0 {
				sb.WriteString(str)
			} else {
				if last[1:] != str[0:1] {
					sb.WriteString(str)
				} else {
					sb.WriteString(str[1:])
				}
			}
			last = str
		}
		for sb.Len() < n {
			sb.WriteString("b")
		}
		fmt.Println(sb.String())
	}
}

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

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

package main

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

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n := 0, 0
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n)
		o, ans := make([]string, n-2), ""
		for j := 0; j < n-2; j++ {
			fmt.Fscan(f, &o[j])
		}
		for j := 0; j < n-2; j++ {
			// aa ab(aab), aa ba(aaba), aa aa(aaa), aa bb(aabb)
			// ab ab(abab), ab ba(aba), ab aa(abaa), ab bb(abb)
			// bb ab(bbab), bb ba(bba), bb aa(bbaa), bb bb(bbb)
			// ba ab(bab), ba ba(baba), ba aa(baa), ba bb(babb)
			if j == 0 || o[j][0] != o[j-1][1] {
				ans += o[j]
			} else {
				ans += string(o[j][1])
			}
		}
		if len(ans) < n {
			fmt.Fprintln(w, ans+"a")
		} else {
			fmt.Fprintln(w, ans)
		}
	}
	w.Flush()
}

func main() {
	solve()
}

package main

import "fmt"

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

	for t := 0; t < test; t++ {
		var n int
		fmt.Scan(&n)

		var s []string
		for i := 0; i < n-2; i++ {
			var temp string
			fmt.Scan(&temp)
			s = append(s, temp)
		}

		res := s[0]
		for i := 1; i < n-2; i++ {
			if res[len(res)-1] == s[i][0] {
				res += string(s[i][1])
			} else {
				res += s[i]
			}
		}
		if len(res) < n {
			res += "a"
		}

		fmt.Println(res)
	}
}

package main

import "fmt"

var (
//n, strs = 7, []string{"ab", "bb", "ba", "aa", "ba"}
)

func main() {
	t := 0
	fmt.Scan(&t)
	for t > 0 {
		n := 0
		fmt.Scan(&n)
		n -= 2
		strs := []string{}
		for n > 0 {
			temp := ""
			fmt.Scan(&temp)
			strs = append(strs, temp)
			n--
		}
		fmt.Println(solve(strs))
		t--
	}
}

func solve(strs []string) string {

	result := ""

	// record := map[string]bool{}
	// newStrs := []string{}
	// for i := range strs {
	// 	_, exist := record[strs[i]]
	// 	if !exist {
	// 		record[strs[i]] = true
	// 		newStrs = append(newStrs, strs[i])
	// 	}
	// }

	for i := range strs {

		switch check(strs[i], result) {
		case 0:
			continue
		case 1:
			result = string(strs[i][0]) + result
		case 2:
			result = result + string(strs[i][1])
		default:
			result += strs[i]
		}

	}

	count := len(strs) + 2 - len(result)
	for count > 0 {
		result += "z"
		count--
	}

	return result
}

func check(str string, result string) int {

	//size := len(str)
	if len(result) == 0 {
		return 3
	}

	// for i := 0; i+size <= len(result); i++ {
	// 	if result[i:i+size] == str {
	// 		return 0
	// 	}
	// }

	// if str[1] == result[0] {
	// 	return 1
	// }

	if str[0] == result[len(result)-1] {
		return 2
	}

	return 3

}

package main

import "fmt"

var (
//n, strs = 7, []string{"ab", "bb", "ba", "aa", "ba"}
)

func main() {
	t := 0
	fmt.Scan(&t)
	for t > 0 {
		n := 0
		fmt.Scan(&n)
		n -= 2
		strs := []string{}
		for n > 0 {
			temp := ""
			fmt.Scan(&temp)
			strs = append(strs, temp)
			n--
		}
		fmt.Println(solve(strs))
		t--
	}
}

func solve(strs []string) string {

	result := ""

	record := map[string]bool{}
	newStrs := []string{}
	for i := range strs {
		_, exist := record[strs[i]]
		if !exist {
			record[strs[i]] = true
			newStrs = append(newStrs, strs[i])
		}
	}

	for i := range newStrs {

		switch check(newStrs[i], result) {
		case 0:
			continue
		case 1:
			result = string(newStrs[i][0]) + result
		case 2:
			result = result + string(newStrs[i][1])
		default:
			result += newStrs[i]
		}

	}

	count := len(strs) + 2 - len(result)
	for count > 0 {
		result += "z"
		count--
	}

	return result
}

func check(str string, result string) int {

	size := len(str)
	if len(result) == 0 {
		return 3
	}

	for i := 0; i+size <= len(result); i++ {
		if result[i:i+size] == str {
			return 0
		}
	}

	// if str[1] == result[0] {
	// 	return 1
	// }

	if str[0] == result[len(result)-1] {
		return 2
	}

	return 3

}

package main

import "fmt"

var (
//n, strs = 7, []string{"ab", "bb", "ba", "aa", "ba"}
)

func main() {
	t := 0
	fmt.Scan(&t)
	for t > 0 {
		n := 0
		fmt.Scan(&n)
		n -= 2
		strs := []string{}
		for n > 0 {
			temp := ""
			fmt.Scan(&temp)
			strs = append(strs, temp)
			n--
		}
		fmt.Println(solve(strs))
		t--
	}
}

func solve(strs []string) string {

	result := ""

	record := map[string]bool{}
	newStrs := []string{}
	for i := range strs {
		_, exist := record[strs[i]]
		if !exist {
			record[strs[i]] = true
			newStrs = append(newStrs, strs[i])
		}
	}

	for i := range newStrs {

		switch check(newStrs[i], result) {
		case 0:
			continue
		case 1:
			result = string(newStrs[i][0]) + result
		case 2:
			result = result + string(newStrs[i][1])
		default:
			result += newStrs[i]
		}

	}

	count := len(strs) + 2 - len(result)
	for count > 0 {
		result += "z"
		count--
	}

	return result
}

func check(str string, result string) int {

	size := len(str)
	if len(result) == 0 {
		return 3
	}

	for i := 0; i+size <= len(result); i++ {
		if result[i:i+size] == str {
			return 0
		}
	}

	if str[1] == result[0] {
		return 1
	}

	if str[0] == result[len(result)-1] {
		return 2
	}

	return 3

}


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
}

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

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

/********** 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
const INF_INT32 = math.MaxInt32
const INF_BIT30 = 1 << 30

var n int
var S []rune

func main() {
	n = ReadInt()
	S = ReadRuneSlice()

	// 最初から全部いっしょならOK
	memo := make(map[rune]int)
	memo['B'] = 0
	memo['W'] = 0
	for i := 0; i < n; i++ {
		memo[S[i]]++
	}
	if memo['B'] == n || memo['W'] == n {
		fmt.Println(0)
		return
	}

	// BもWも奇数なら無理
	if memo['B']%2 == 1 && memo['W']%2 == 1 {
		fmt.Println(-1)
		return
	}

	answers := []int{}
	if memo['B']%2 == 0 {
		// BをWにする
		for i := 0; i < n-1; i++ {
			if S[i] == 'B' {
				answers = append(answers, i+1)
				S[i] = 'W'
				S[i+1] = rev(S[i+1])
			}
		}
	} else {
		// WをBにする
		for i := 0; i < n-1; i++ {
			if S[i] == 'W' {
				answers = append(answers, i+1)
				S[i] = 'B'
				S[i+1] = rev(S[i+1])
			}
		}
	}

	// PrintDebug("%s\n", string(S))
	fmt.Println(len(answers))
	fmt.Println(PrintIntsLine(answers...))
}

func rev(r rune) rune {
	if r == 'B' {
		return 'W'
	} else {
		return 'B'
	}
}

/*
- まずは全探索を検討しましょう
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
- いきなりオーバーフローはしていませんか？
	- MOD取る系はint64必須ですよ？
*/

/*
ASCII code

ASCII   10進数  ASCII   10進数  ASCII   10進数
!       33      "       34      #       35
$       36      %       37      &       38
'       39      (       40      )       41
*       42      +       43      ,       44
-       45      .       46      /       47
0       48      1       49      2       50
3       51      4       52      5       53
6       54      7       55      8       56
9       57      :       58      ;       59
<       60      =       61      >       62
?       63      @       64      A       65
B       66      C       67      D       68
E       69      F       70      G       71
H       72      I       73      J       74
K       75      L       76      M       77
N       78      O       79      P       80
Q       81      R       82      S       83
T       84      U       85      V       86
W       87      X       88      Y       89
Z       90      [       91      \       92
]       93      ^       94      _       95
`       96      a       97      b       98
c       99      d       100     e       101
f       102     g       103     h       104
i       105     j       106     k       107
l       108     m       109     n       110
o       111     p       112     q       113
r       114     s       115     t       116
u       117     v       118     w       119
x       120     y       121     z       122
{       123     |       124     }       125
~       126             127
*/

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

package main

import "fmt"

func main () {
	var n int
	var s string
	var a [201] int
	fmt.Scan(&n, &s)
	cnt := 0
	color := 66
	for i:= 0; i < n; i++ {
		if s[i] == 66 {
			cnt++
		}
		a[i] = int(s[i])
	}
	if cnt == 0 || cnt == n {
		fmt.Println("0");
		return
	}
	if cnt % 2 == 1 && (n - cnt) % 2 == 1 {
		fmt.Println("-1");
		return
	}

	if cnt % 2 == 1 {
		color = 87
	}
	var ans [601] int
	count := 0
	for i := 0; i < n-1; i++ {
		uncolor := 87
		if color == uncolor {
			uncolor = 66
		}
		if a[i] == color {
			a[i] = uncolor
			if a[i + 1] == color {
				a[i + 1] = uncolor
			} else {
				a[i + 1] = color
			}
			ans[count] = i + 1;
			count++

		}
	}

	fmt.Println(count)
	for i := 0; i < count; i++ {
		fmt.Print(ans[i]," ")
	}
}

package main

import (
	"fmt"
)

func get_counters(s string) (int, int) {
	white_counter := 0
	for _, ch := range s {
		if ch == 'W' {
			white_counter += 1
		}
	}
	black_counter := len(s) - white_counter
	return white_counter, black_counter
}

func is_impossible(s string) bool {
	white_counter, black_counter := get_counters(s)
	if (white_counter%2) == 1 && (black_counter%2) == 1 {
		return true
	}
	return false
}

func get_choice(s string) string {
	white_counter, _ := get_counters(s)
	if (white_counter % 2) == 0 {
		return "W"
	}
	return "B"
}

func main() {
	var n int
	var s string

	fmt.Scan(&n)
	fmt.Scan(&s)

	if is_impossible(s) {
		fmt.Println("-1")

	} else {
		invert := false
		response := 0
		var response_array [205 * 3]int

		choice := get_choice(s)
		// fmt.Println("debug : ", choice)
		for i, ch := range s {
			// fmt.Printf("%c\n", ch)
			current := 0
			if invert {
				current ^= 1
			}
			if string(ch) == choice {
				current ^= 1
			}
			if current == 1 {
				response_array[response] = i
				response += 1
				invert = true
			} else {
				invert = false
			}
		}
		fmt.Println(response)
		for i := 0; i < response; i++ {
			fmt.Print(response_array[i]+1, " ")
		}
		fmt.Print("\n")
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	s := ""
	fmt.Fscanf(in, "%s\n", &s)
	ok1, ans1 := tryB(s)
	ok2, ans2 := tryW(s)
	if !ok1 {
		if ok2 {
			fmt.Fprintf(out, "%d\n", len(ans2))
			for i := 0; i < len(ans2)-1; i++ {
				fmt.Fprintf(out, "%d ", ans2[i])
			}
			if len(ans2) > 0 {
				fmt.Fprintf(out, "%d\n", ans2[len(ans2)-1])
			}
		} else {
			fmt.Fprintf(out, "%d\n", -1)
		}
	} else if !ok2 {
		fmt.Fprintf(out, "%d\n", len(ans1))
		for i := 0; i < len(ans1)-1; i++ {
			fmt.Fprintf(out, "%d ", ans1[i])
		}
		if len(ans1) > 0 {
			fmt.Fprintf(out, "%d\n", ans1[len(ans1)-1])
		}
	} else {
		if len(ans1) < len(ans2) {
			fmt.Fprintf(out, "%d\n", len(ans1))
			for i := 0; i < len(ans1)-1; i++ {
				fmt.Fprintf(out, "%d ", ans1[i])
			}
			if len(ans1) > 0 {
				fmt.Fprintf(out, "%d\n", ans1[len(ans1)-1])
			}
		} else {
			fmt.Fprintf(out, "%d\n", len(ans2))
			for i := 0; i < len(ans2)-1; i++ {
				fmt.Fprintf(out, "%d ", ans2[i])
			}
			if len(ans2) > 0 {
				fmt.Fprintf(out, "%d\n", ans2[len(ans2)-1])
			}
		}
	}
	return
}

func tryB(s string) (bool, []int) {
	a := []byte(s)
	ans := []int{}
	n := len(a)
	for i := 0; i < len(s)-1; i++ {
		if a[i] != 'B' {
			a[i] = 'B'
			if a[i+1] == 'B' {
				a[i+1] = 'W'
			} else {
				a[i+1] = 'B'
			}
			ans = append(ans, i+1)
		}
	}
	if a[n-1] != 'B' {
		return false, nil
	}
	return true, ans
}

func tryW(s string) (bool, []int) {
	a := []byte(s)
	ans := []int{}
	n := len(a)
	for i := 0; i < len(s)-1; i++ {
		if a[i] != 'W' {
			a[i] = 'W'
			if a[i+1] == 'B' {
				a[i+1] = 'W'
			} else {
				a[i+1] = 'B'
			}
			ans = append(ans, i+1)
		}
	}
	if a[n-1] != 'W' {
		return false, nil
	}
	return true, ans
}

package main

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

func main() {
	defer Flush()

	n := readi()
	_ = n
	bs := readb()

	var cb, cw int
	for _, b := range bs {
		if b == 'W' {
			cw++
		} else {
			cb++
		}
	}
	if cw%2 == 1 && cb%2 == 1 {
		println(-1)
		return
	}
	if cw == 0 {
		println(0)
		return
	} else if cb == 0 {
		println(0)
		return
	}

	var ans []int
	if cw%2 == 0 {
		ans = solve('W', 'B', bs)
	} else {
		ans = solve('B', 'W', bs)
	}

	println(len(ans))
	if len(ans) == 0 {
		return
	}
	sp := ""
	for _, i := range ans {
		printf("%s%d", sp, i+1)
		sp = " "
	}
	println()

}

func solve(f, t byte, bs []byte) []int {
	swp := func(i int) {
		if bs[i] == f {
			bs[i] = t
		} else {
			bs[i] = f
		}
	}
	var res []int
	for i, c := range bs {
		if c == f {
			res = append(res, i)
			swp(i)
			swp(i + 1)
		}
	}
	return res
}

// -----------------------------------------------------------------------------

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

func IsNewLine(c byte) bool {
	switch c {
	case '\n', '\r':
		return true
	}
	return false
}

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

// -----------------------------------------------------------------------------

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte.  Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

// -----------------------------------------------------------------------------

// Utilities

func sumSlice(a []int) int {
	var res int
	for _, v := range a {
		res += v
	}
	return res
}

func sumSlicell(a []int64) int64 {
	var res int64
	for _, v := range a {
		res += v
	}
	return res
}

func readInts(N int) (int, []int) {
	if N == 0 {
		N = readi()
	}
	a := make([]int, N)
	for i := range a {
		a[i] = readi()
	}
	return N, a
}

func readIntsll(N int) (int, []int64) {
	if N == 0 {
		N = readi()
	}
	a := make([]int64, N)
	for i := range a {
		a[i] = readll()
	}
	return N, a
}

// reverse slice in place
func reverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
}

// areverse: allocating reverse
func areverse(a []int) []int {
	b := make([]int, len(a))
	for i := range a {
		b[i] = a[len(a)-i-1]
	}
	return b
}

// -----------------------------------------------------------------------------

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

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

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

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

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

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

func absll(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

func egcdll(a, b int64) (int64, int64, int64) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcdll(b, a%b)
	return d, y, x - a/b*y
}

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}

package main

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

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

	testCount := 0
	fmt.Fscanf(in, "%d\n", &testCount)

	x := ""
	fmt.Fscanf(in, "%s\n", &x)

	b := 0
	w := 0
	for i := range x {
		if x[i] == 'B' {
			b++
		} else {
			w++
		}
	}

	if b == 0 || w == 0 {
		fmt.Fprintln(out, 0)
		return
	} else if b%2 == 1 && w%2 == 1 {
		fmt.Fprintln(out, -1)
		return
	}

	evenChar := uint8('B')

	if b%2 == 0 { // even
		evenChar = 'B'
	} else {
		evenChar = 'W'
	}

	idx := []int{}

	for i := 0; i < len(x)-1; i++ {
		if x[i] != evenChar { // odd
			continue
		}
		idx = append(idx, i)

		for j := i + 1; j < len(x); j++ {
			i = j
			if x[i] == evenChar {
				break
			}
			idx = append(idx, j)
		}
	}

	fmt.Fprintln(out, len(idx))

	for i := 0; i < len(idx); i++ {
		fmt.Fprint(out, idx[i]+1, " ")
	}
}

package main

import (
	"fmt"
)

func main() {

	var n int
	var str string
	fmt.Scan(&n)
	fmt.Scan(&str)

	wCnt := 0
	bCnt := 0

	for i := 0; i < n; i++ {
		if string(str[i]) == "W" {
			wCnt++
		} else {
			bCnt++
		}
	}

	res := []int{}
	arr := []byte(str)

	if wCnt == 0 || bCnt == 0 {
		fmt.Println(0)
		return
	} else if wCnt%2 == 1 && bCnt%2 == 1 {
		fmt.Println(-1)
		return
	} else if wCnt%2 == 1 {
		for i := 0; i < n-1; i++ {
			if arr[i] == 'B' {
				if arr[i+1] == 'W' {
					arr[i], arr[i+1] = arr[i+1], arr[i]
					res = append(res, i+1)
				} else {
					arr[i], arr[i+1] = 'W', 'W'
					res = append(res, i+1)
				}
			}
		}
	} else {
		for i := 0; i < n-1; i++ {
			if arr[i] == 'W' {
				if arr[i+1] == 'B' {
					arr[i], arr[i+1] = arr[i+1], arr[i]
					res = append(res, i+1)
				} else {
					arr[i], arr[i+1] = 'B', 'B'
					res = append(res, i+1)
				}
			}
		}
	}
	fmt.Println(len(res))
	for i := 0; i < len(res)-1; i++ {
		fmt.Print(res[i], " ")
	}
	fmt.Println(res[len(res)-1])
}

package main

import (
	"fmt"
)

func is_impossible(s string) bool {
	white_counter := 0
	for _, ch := range s {
		if ch == 'W' {
			white_counter += 1
		}
	}
	black_counter := len(s) - white_counter
	if (white_counter%2) == 1 && (black_counter%2) == 1 {
		return true
	}
	return false
}

func main() {
	var n int
	var s string

	fmt.Scan(&n)
	fmt.Scan(&s)

	if is_impossible(s) {
		fmt.Println("-1")

	} else {
		invert := false
		response := 0
		var response_array [205]int

		for i, ch := range s {
			// fmt.Printf("%c\n", ch)
			current := 0
			if invert {
				current ^= 1
			}
			if ch == 'B' {
				current ^= 1
			}
			if current == 1 {
				response_array[response] = i
				response += 1
				invert = true
			} else {
				invert = false
			}
		}
		fmt.Println(response)
		for i := 0; i < response; i++ {
			fmt.Print(response_array[i]+1, " ")
		}
		fmt.Print("\n")
	}
}


package main

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

func main() {
	sc := NewScanner()
	N, R := sc.NextInt(), sc.NextInt()
	x := sc.NextIntArray()

	fix := make([]float64, 0, N)
	fix = append(fix, float64(R))

	for i := 1; i < N; i++ {
		P := x[i]
		q := float64(R)

		for j := len(fix) - 1; j >= 0; j-- {

			d := 2*R*2*R - (x[j]-P)*(x[j]-P)
			if d >= 0 {
				p := math.Sqrt(float64(d)) + fix[j]
				if q < p {
					q = p
				}
			}
		}
		fix = append(fix, q)
	}
	ans := ""
	for i := 0; i < N; i++ {
		if len(ans) > 0 {
			ans += " "
		}
		ans += fmt.Sprintf("%0.9f", fix[i])
	}
	fmt.Println(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"
	"math"
)

func main() {
	var n int
	var r float64
	fmt.Scan(&n, &r)
	land := make([][2]float64, 0, n)
	for i := 0; i < n; i++ {
		var x float64
		fmt.Scan(&x)
		y := r
		for _, l := range land {
			if math.Abs(l[0]-x)-1e-6 > 2*r {
				continue
			}
			y = math.Max(y, solve(l[0], l[1], x, r))
		}
		land = append(land, [2]float64{x, y})
		if i+1 == n {
			fmt.Printf("%.10f\n", y)
		} else {
			fmt.Printf("%.10f ", y)
		}
	}
}

func solve(x0, y0, x1, r float64) float64 {
	d := 4*y0*y0 - 4*(y0*y0+(x0-x1)*(x0-x1)-4*r*r)
	if d < 0 {
		d = 0
	}
	return (2*y0 + math.Sqrt(d)) / 2
}

package main

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

func main() {
	sc := NewScanner()
	N, R := sc.NextInt(), sc.NextInt()
	x := sc.NextIntArray()

	fix := make([]float64, 0, N)
	fix = append(fix, float64(R))

	for i := 1; i < N; i++ {
		P := x[i]
		q := 0.0

		for j := len(fix) - 1; j >= 0; j-- {
			if P == x[j] {
				p := fix[j] + float64(R+R)
				if q < p {
					q = p
				}
			}
			d := 2*R*2*R - (x[j]-P)*(x[j]-P)
			if d >= 0 {
				p := math.Sqrt(float64(d)) + fix[j]
				if q < p {
					q = p
				}
			}
		}
		fix = append(fix, q)
	}
	ans := ""
	for i := 0; i < N; i++ {
		if len(ans) > 0 {
			ans += " "
		}
		ans += fmt.Sprintf("%0.9f", fix[i])
	}
	fmt.Println(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 (
	"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"
	"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"
	"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)
				}
			}
		}
	}
}


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