In the snake exhibition, there are $$$n$$$ rooms (numbered $$$0$$$ to $$$n - 1$$$) arranged in a circle, with a snake in each room. The rooms are connected by $$$n$$$ conveyor belts, and the $$$i$$$-th conveyor belt connects the rooms $$$i$$$ and $$$(i+1) \bmod n$$$. In the other words, rooms $$$0$$$ and $$$1$$$, $$$1$$$ and $$$2$$$, $$$\ldots$$$, $$$n-2$$$ and $$$n-1$$$, $$$n-1$$$ and $$$0$$$ are connected with conveyor belts.The $$$i$$$-th conveyor belt is in one of three states:  If it is clockwise, snakes can only go from room $$$i$$$ to $$$(i+1) \bmod n$$$.  If it is anticlockwise, snakes can only go from room $$$(i+1) \bmod n$$$ to $$$i$$$.  If it is off, snakes can travel in either direction.   Above is an example with $$$4$$$ rooms, where belts $$$0$$$ and $$$3$$$ are off, $$$1$$$ is clockwise, and $$$2$$$ is anticlockwise.Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$): the number of test cases. The description of the test cases follows.   The first line of each test case description contains a single integer $$$n$$$ ($$$2 \le n \le 300\,000$$$): the number of rooms.  The next line of each test case description contains a string $$$s$$$ of length $$$n$$$, consisting of only '<', '>' and '-'.   If $$$s_{i} = $$$ '>', the $$$i$$$-th conveyor belt goes clockwise.  If $$$s_{i} = $$$ '<', the $$$i$$$-th conveyor belt goes anticlockwise.  If $$$s_{i} = $$$ '-', the $$$i$$$-th conveyor belt is off.  It is guaranteed that the sum of $$$n$$$ among all test cases does not exceed $$$300\,000$$$.

For each test case, output the number of returnable rooms.

NoteIn the first test case, all rooms are returnable except room $$$2$$$. The snake in the room $$$2$$$ is trapped and cannot exit. This test case corresponds to the picture from the problem statement. In the second test case, all rooms are returnable by traveling on the series of clockwise belts.

package main

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

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

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

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

func scan(a ...interface{}) (n int, err error) {
	return fmt.Fscan(in, a...)
}

var err error

func next() (n string) {
	scan(&n)
	return n
}

func nextInt() (n int) {
	scan(&n)
	return n
}

func nextLong() (n int64) {
	scan(&n)
	return n
}

func nextDouble() (n float64) {
	scan(&n)
	return n
}

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

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

const mod = 1000000007

func Add(a, b int64) int64 {
	return (a + b) % mod
}

func Mult(a, b int64) int64 {
	return (a * b) % mod
}

func solve() {
	n := nextInt()
	arr := []byte(next())
	a, b, c := 0, 0, 0
	for _, v := range arr {
		if v == '>' {
			a++
		} else if v == '<' {
			b++
		} else if v == '-' {
			c++
		}
	}
	if a == 0 || b == 0 {
		printf("%d\n", n)
		return
	}
	if c == 0 {
		printf("0\n")
		return
	}
	has := make([]bool, n)
	for i := range has {
		if arr[i] == '-' {
			has[i] = true
			has[(i+1)%n] = true
		}
	}
	num := 0
	for _, v := range has {
		if v {
			num++
		}
	}
	printf("%d\n", num)
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	out = bufio.NewWriterSize(os.Stdout, 8192)
	name := "in"
	file1, err := os.Open(name + ".in")
	if err == nil {
		in = bufio.NewReaderSize(file1, 8192)
	}
	// file2, err := os.Create(name + ".out")
	// if err != nil {
	// 	log.Fatal(err)
	// }
	// out = bufio.NewWriterSize(file2, 8192)
	defer out.Flush()
	// start := time.Now()

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

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

package main

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

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := 0; i < t; i++ {
		n := ReadInt()
		s := ReadString()
		Println(solve(n, s))
	}

}

func solve(n int, s string) int {
	lt := 0
	gt := 0
	for i := 0; i < n; i++ {
		if s[i] == '<' {
			lt++
		} else if s[i] == '>' {
			gt++
		}
	}
	if lt == 0 || gt == 0 {
		return n
	}

	di := make(map[int]bool)
	for i := 0; i < n; i++ {
		if s[i] == '-' {
			di[i] = true
			di[(i+1)%n] = true
		}
	}
	return len(di)
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func Print(a ...interface{})            { fmt.Fprint(_w, a...) }
func Printf(f string, a ...interface{}) { fmt.Fprintf(_w, f, a...) }
func Println(a ...interface{})          { fmt.Fprintln(_w, a...) }
func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(_r, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) (a []int) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt())
	}
	return
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int) (a []int64) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt64())
	}
	return
}

/*
URL:
https://codeforces.com/contest/1428/problem/B
*/

package main

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

var (
	t int

	n int
	S []rune
)

func main() {
	defer stdout.Flush()

	t = readi()
	for i := 0; i < t; i++ {
		n = readi()
		S = readrs()

		solve()
	}
}

func solve() {
	memo := make(map[rune]int)
	for _, r := range S {
		memo[r]++
	}

	if memo['>'] == 0 || memo['<'] == 0 {
		printf("%d\n", n)
		return
	}

	A := make([]int, n)
	for i, r := range S {
		if r != '-' {
			continue
		}

		A[i]++
		A[(i+1)%n]++
	}

	ans := 0
	for i := 0; i < n; i++ {
		if A[i] > 0 {
			ans++
		}
	}
	printf("%d\n", ans)
}

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

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

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

// mod can calculate a right residual whether value is positive or negative.
func mod(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

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

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

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

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

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

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

	return s
}

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

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

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

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

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

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

/*********** Input ***********/

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

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

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

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

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

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

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

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

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

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

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

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

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

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

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

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

/*
URL:
https://codeforces.com/contest/1428/problem/B
*/

package main

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

var (
	t int

	n int
	S []rune
)

func main() {
	defer stdout.Flush()

	t = readi()
	for tc := 0; tc < t; tc++ {
		n = readi()
		S = readrs()

		solve()
	}
}

func solve() {
	scc := NewSccGraph(n)

	for i := 0; i < n; i++ {
		r := S[i]
		if r == '-' {
			scc.AddEdge(i, (i+1)%n)
			scc.AddEdge((i+1)%n, i)
		} else if r == '>' {
			scc.AddEdge(i, (i+1)%n)
		} else {
			scc.AddEdge((i+1)%n, i)
		}
	}

	E := scc.Scc()

	ans := 0
	for _, ids := range E {
		if len(ids) == 1 {
			continue
		}
		ans += len(ids)
	}

	printf("%d\n", ans)
}

// originated from:
// https://qiita.com/EmptyBox_0/items/2f8e3cf7bd44e0f789d5#scc
// https://atcoder.github.io/ac-library/production/document_ja/scc.html

type SccGraph struct {
	n     int
	edges [][2]int
}

type Csr struct {
	start []int
	elist []int
}

func NewSccGraph(n int) *SccGraph {
	scc := new(SccGraph)
	scc.n = n
	return scc
}

func (scc *SccGraph) NumVertices() int {
	return scc.n
}

func (scc *SccGraph) AddEdge(from int, to int) {
	scc.edges = append(scc.edges, [2]int{from, to})
}

func (scc *SccGraph) Scc() [][]int {
	groupNum, ids := scc.SccIds()
	counts := make([]int, groupNum)
	for _, x := range ids {
		counts[x]++
	}
	groups := make([][]int, groupNum)
	for i := 0; i < groupNum; i++ {
		groups[i] = make([]int, 0, counts[i])
	}
	for i := 0; i < scc.n; i++ {
		groups[ids[i]] = append(groups[ids[i]], i)
	}
	return groups
}

func (c *Csr) csr(n int, edges [][2]int) {
	c.start = make([]int, n+1)
	c.elist = make([]int, len(edges))
	for _, e := range edges {
		c.start[e[0]+1]++
	}
	for i := 1; i <= n; i++ {
		c.start[i] += c.start[i-1]
	}
	counter := make([]int, n+1)
	copy(counter, c.start)
	for _, e := range edges {
		c.elist[counter[e[0]]] = e[1]
		counter[e[0]]++
	}
}

func (scc *SccGraph) SccIds() (int, []int) {
	_min := func(x, y int) int {
		if x < y {
			return x
		}
		return y
	}

	g := new(Csr)
	g.csr(scc.n, scc.edges)
	nowOrd, groupNum := 0, 0
	visited, low := make([]int, 0, scc.n), make([]int, scc.n)
	ord, ids := make([]int, scc.n), make([]int, scc.n)
	for i := 0; i < scc.n; i++ {
		ord[i] = -1
	}
	var dfs func(v int)
	dfs = func(v int) {
		low[v], ord[v] = nowOrd, nowOrd
		nowOrd++
		visited = append(visited, v)
		for i := g.start[v]; i < g.start[v+1]; i++ {
			to := g.elist[i]
			if ord[to] == -1 {
				dfs(to)
				low[v] = _min(low[v], low[to])
			} else {
				low[v] = _min(low[v], ord[to])
			}
		}
		if low[v] == ord[v] {
			for {
				u := visited[len(visited)-1]
				visited = visited[:len(visited)-1]
				ord[u] = scc.n
				ids[u] = groupNum
				if u == v {
					break
				}
			}
			groupNum++
		}
	}
	for i := 0; i < scc.n; i++ {
		if ord[i] == -1 {
			dfs(i)
		}
	}
	for i := 0; i < len(ids); i++ {
		ids[i] = groupNum - 1 - ids[i]
	}
	return groupNum, ids
}

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

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

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

// mod can calculate a right residual whether value is positive or negative.
func mod(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

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

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

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

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

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

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

	return s
}

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

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

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

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

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

/*********** Input ***********/

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

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

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

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

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

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

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

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

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

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

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

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

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

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

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

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

package main

import "fmt"

func circular(s string) bool {
	left, right := false, false
	for i := range s {
		if s[i] == '<' {
			left = true
		}
		if s[i] == '>' {
			right = true
		}
		if left && right {
			return false
		}
	}
	return true
}

func returnableRooms(n int, s string) int {
	if circular(s) {
		return n
	}
	rooms := make(map[int]bool)
	for i := range s {
		if s[i] == '-' {
			rooms[i] = true
			rooms[(i+1)%n] = true
		}
	}

	return len(rooms)
}

func main() {

	t := 0
	fmt.Scanf("%d\n", &t)

	for t > 0 {
		n := 0
		fmt.Scanf("%d\n", &n)
		var s string
		fmt.Scanf("%s\n", &s)
		fmt.Printf("%d\n", returnableRooms(n, s))
		t -= 1
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

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

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

		var cBelt, ccBelt int
		var oneOff int
		for j := range s {
			rBelt := s[j]
			lBelt := s[(j-1+n)%n]
			if rBelt == '>' {
				cBelt++
			}

			if rBelt == '<' {
				ccBelt++
			}

			if rBelt == '-' || lBelt == '-' {
				oneOff++
			}
		}

		var ans int
		if cBelt == 0 || ccBelt == 0 {
			ans = n
		} else {
			ans = oneOff
		}

		fmt.Println(ans)
	}
}

package main

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

func configure(scanner *bufio.Scanner) {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 1000005), 1000005)
}
func getNextString(scanner *bufio.Scanner) string {
	scanned := scanner.Scan()
	if !scanned {
		panic("scan failed")
	}
	return scanner.Text()
}
func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}
func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}
func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}
func main() {
	fp := os.Stdin
	wfp := os.Stdout
	extra := 0
	if os.Getenv("I") == "IronMan" {
		fp, _ = os.Open(os.Getenv("END_GAME"))
		extra = 100
	}
	scanner := bufio.NewScanner(fp)
	configure(scanner)
	writer := bufio.NewWriter(wfp)
	defer func() {
		r := recover()
		if r != nil {
			fmt.Fprintln(writer, r)
		}
		writer.Flush()
	}()
	solve(scanner, writer)
	for i := 0; i < extra; i++ {
		fmt.Fprintln(writer, "-----------------------------------")
		solve(scanner, writer)
	}
}
func solve(scanner *bufio.Scanner, writer *bufio.Writer) {
	t := getNextInt(scanner)
	for t > 0 {
		t--
		func() {
			n := getNextInt(scanner)
			s := getNextString(scanner)
			l := 0
			r := 0
			can := make([]bool, n)
			for i := 0; i < n; i++ {
				switch s[i] {
				case '>':
					r++
				case '<':
					l++
				default:
					l++
					r++
					can[i] = true
					can[(i+1)%n] = true
				}
			}
			if l == n || r == n {
				fmt.Fprintln(writer, n)
				return
			}
			var ans int
			for i := 0; i < n; i++ {
				if can[i] {
					ans++
				}
			}
			fmt.Fprintln(writer, ans)
		}()
	}
}

package main

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

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := 0; i < t; i++ {
		n := ReadInt()
		s := ReadString()
		Println(solve(n, s))
	}

}

func solve(n int, s string) int {
	di := make(map[int]bool)
	for i := 0; i < n; i++ {
		if s[i] == '-' {
			di[i] = true
			di[(i+1)%n] = true
		}
	}
	if len(di) > 0 {
		return len(di)
	}

	lt := 0
	gt := 0
	for i := 0; i < n; i++ {
		if s[i] == '<' {
			lt++
		} else {
			gt++
		}
	}
	if lt == 0 || gt == 0 {
		return n
	} else {
		return 0
	}
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func Print(a ...interface{})            { fmt.Fprint(_w, a...) }
func Printf(f string, a ...interface{}) { fmt.Fprintf(_w, f, a...) }
func Println(a ...interface{})          { fmt.Fprintln(_w, a...) }
func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(_r, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) (a []int) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt())
	}
	return
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int) (a []int64) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt64())
	}
	return
}

package main

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

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := 0; i < t; i++ {
		n := ReadInt()
		s := ReadString()
		Println(solve(n, s))
	}

}

func solve(n int, s string) int {
	lt := 0
	gt := 0
	for i := 0; i < n; i++ {
		if s[i] == '<' {
			lt++
		} else {
			gt++
		}
	}
	if lt == 0 || gt == 0 {
		return n
	}

	di := make(map[int]bool)
	for i := 0; i < n; i++ {
		if s[i] == '-' {
			di[i] = true
			di[(i+1)%n] = true
		}
	}
	return len(di)
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func Print(a ...interface{})            { fmt.Fprint(_w, a...) }
func Printf(f string, a ...interface{}) { fmt.Fprintf(_w, f, a...) }
func Println(a ...interface{})          { fmt.Fprintln(_w, a...) }
func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(_r, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) (a []int) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt())
	}
	return
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int) (a []int64) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt64())
	}
	return
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

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

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

		var stuck int
		var oneOff int
		for j := range s {
			rBelt := s[j]
			lBelt := s[(j-1+n)%n]
			if rBelt == '<' && lBelt == '>' {
				stuck++
			}

			if rBelt == '-' || lBelt == '-' {
				oneOff++
			}
		}

		var ans int
		if stuck == 0 {
			ans = n
		} else {
			ans = oneOff
		}

		fmt.Println(ans)
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

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

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

		var cBelt, ccBelt int
		var oneOff int
		for j := range s {
			rBelt := s[j]
			lBelt := s[(j-1+n)%n]
			if rBelt == '>' {
				cBelt++
			}

			if rBelt == '<' {
				lBelt++
			}

			if rBelt == '-' || lBelt == '-' {
				oneOff++
			}
		}

		var ans int
		if cBelt == 0 || ccBelt == 0 {
			ans = n
		} else {
			ans = oneOff
		}

		fmt.Println(ans)
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

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

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

		var stuck int
		var oneOff int
		for j := range s {
			rBelt := s[j]
			lBelt := s[(j-1+n)%n]
			if (rBelt == '<' && lBelt == '>') || (rBelt == '>' && lBelt == '<') {
				stuck++
			}

			if rBelt == '-' || lBelt == '-' {
				oneOff++
			}
		}

		var ans int
		if stuck == 0 {
			ans = n
		} else {
			ans = oneOff
		}

		fmt.Println(ans)
	}
}


There are $$$n$$$ shovels in the nearby shop. The $$$i$$$-th shovel costs $$$a_i$$$ bourles.Misha has to buy exactly $$$k$$$ shovels. Each shovel can be bought no more than once.Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.There are also $$$m$$$ special offers in the shop. The $$$j$$$-th of them is given as a pair $$$(x_j, y_j)$$$, and it means that if Misha buys exactly $$$x_j$$$ shovels during one purchase then $$$y_j$$$ most cheapest of them are for free (i.e. he will not pay for $$$y_j$$$ most cheapest shovels during the current purchase).Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).Your task is to calculate the minimum cost of buying $$$k$$$ shovels, if Misha buys them optimally.

The first line of the input contains three integers $$$n, m$$$ and $$$k$$$ ($$$1 \le n, m \le 2 \cdot 10^5, 1 \le k \le min(n, 2000)$$$) — the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the cost of the $$$i$$$-th shovel. The next $$$m$$$ lines contain special offers. The $$$j$$$-th of them is given as a pair of integers $$$(x_i, y_i)$$$ ($$$1 \le y_i \le x_i \le n$$$) and means that if Misha buys exactly $$$x_i$$$ shovels during some purchase, then he can take $$$y_i$$$ most cheapest of them for free.

Print one integer — the minimum cost of buying $$$k$$$ shovels if Misha buys them optimally.

NoteIn the first example Misha can buy shovels on positions $$$1$$$ and $$$4$$$ (both with costs $$$2$$$) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions $$$3$$$ and $$$6$$$ (with costs $$$4$$$ and $$$3$$$) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position $$$7$$$ with cost $$$1$$$. So the total cost is $$$4 + 2 + 1 = 7$$$.In the second example Misha can buy shovels on positions $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$ and $$$8$$$ (costs are $$$6$$$, $$$8$$$, $$$5$$$, $$$1$$$ and $$$2$$$) and get three cheapest (with costs $$$5$$$, $$$1$$$ and $$$2$$$) for free. And then he can buy shovels on positions $$$6$$$, $$$7$$$ and $$$9$$$ (all with costs $$$1$$$) without using any special offers. So the total cost is $$$6 + 8 + 1 + 1 + 1 = 17$$$.In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost $$$17$$$.

package main

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

type IntF []int

func (m IntF) Swap(a, b int) {
	m[a],m[b] = m[b],m[a]
}
func (m IntF) Less(a, b int) bool {
	return m[a]<m[b]
}
func (m IntF) Len() int {
	return len(m)
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n, m, k int
	var x, y int
	fmt.Fscanf(buf, "%d %d %d\n", &n, &m, &k)
	dp := make([]int, k+1)
	mat := make([]int, n)
	maxd := make([]int,n+1)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &mat[i])
	}
	fmt.Fscanf(buf, "\n")
	//fmt.Printf("%v\n",mat)
	dp[k] = 0
	for i := 0; i < m; i++ {
		fmt.Fscanf(buf, "%d %d\n", &x, &y)
		if y > maxd[x]{
			maxd[x] = y
		}

	}
	sort.Sort(IntF(mat))
	sum := make([]int,k+1)
	for i:= 1;i <= k;i++{

			sum[i] = mat[i-1]+sum[i-1]

	}
//	fmt.Printf("%v\ns=%v\n",mat,sum)
	for i := 1; i <= k; i++ {
		dp[i] = -1
		for j:=i-1;j >= 0;j--{
			if maxd[i-j] <=0 {
				continue
			}
			if dp[i] == -1||dp[i] < dp[j]+sum[j+maxd[i-j]]-sum[j] {
				dp[i] = dp[j] + sum[j+maxd[i-j]] - sum[j]
			}
		}
		if dp[i] == -1{
			dp[i]=0
		}
	}
	//fmt.Printf("%v\n",dp)
	fmt.Printf("%d\n", sum[k]-dp[k])

}


Arkady and Masha want to choose decorations for thier aquarium in Fishdom game. They have n decorations to choose from, each of them has some cost. To complete a task Arkady and Masha need to choose exactly m decorations from given, and they want to spend as little money as possible.There is one difficulty: Masha likes some a of the given decorations, Arkady likes some b of the given decorations. Some decorations may be liked by both Arkady and Masha, or not be liked by both. The friends want to choose such decorations so that each of them likes at least k decorations among the chosen. Help Masha and Arkady find the minimum sum of money they need to spend.

The first line contains three integers n, m and k (1 ≤ n ≤ 200000, 1 ≤ m ≤ n, 1 ≤ k ≤ n) — the number of decorations, how many decorations the friends should choose, how many decorations each of them should like among the chosen. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 109) — decorations costs. The third line contains single integer a (1 ≤ a ≤ n) — the number of decorations liked by Masha. The fourth line contains a distinct integers x1, x2, ..., xa (1 ≤ xi ≤ n) — the ids of decorations liked by Masha. The next two lines describe decorations liked by Arkady in the same format.

Print single integer: the minimum sum of money the friends should spend to fulfill all constraints. If it is not possible, print -1.

NoteIn the first example the only possible variant to choose 3 decorations having all conditions satisfied is to choose decorations 1, 2, 3.In the second example friends can choose decoration 4 instead of decoration 3, because this one is one coin cheaper.In the third example it's not possible to choose 2 decorations in a way that both are liked by both Masha and Arkady.

package main

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

type decoration struct {
	cost, like int
	taken      bool
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 2<<16)
	var n, m, k int
	fmt.Fscan(in, &n, &m, &k)
	if k > m {
		fmt.Println(-1)
		return
	}
	decos := make([]decoration, n)
	for i := range decos {
		fmt.Fscan(in, &decos[i].cost)
	}
	var a, x int
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 1
	}
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 2
	}

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

	var byLike [4][]*decoration
	for i, d := range decos {
		byLike[d.like] = append(byLike[d.like], &decos[i])
	}

	if len(byLike[1])+len(byLike[3]) < k || len(byLike[2])+len(byLike[3]) < k || (k-len(byLike[3]))*2+len(byLike[3]) > m {
		fmt.Println(-1)
		return
	}

	ans := int64(0)
	var t [4]int
	for t[3] < k && t[3] < len(byLike[3]) {
		byLike[3][t[3]].taken = true
		ans += int64(byLike[3][t[3]].cost)
		t[3]++
	}
	for _, i := range []int{1, 2} {
		for t[i]+t[3] < k {
			byLike[i][t[i]].taken = true
			ans += int64(byLike[i][t[i]].cost)
			t[i]++
		}
	}

	var because []*decoration
	var nextBI int
	for i, d := range decos {
		if d.taken {
			continue
		}
		if t[0]+t[1]+t[2]+t[3] == m {
			break
		}
		d.taken = true
		ans += int64(d.cost)
		t[d.like]++
		because = append(because, &decos[i])
		nextBI = i + 1
	}

loop:
	for t[3] > 0 {
		var need []*decoration
		for _, i := range []int{1, 2} {
			if t[3]-1+t[i] < k {
				if t[i] == len(byLike[i]) {
					break loop
				}
				need = append(need, byLike[i][t[i]])
			}
		}
		the := byLike[3][t[3]-1]
		switch len(need) {
		case 0:
			for nextBI < n && decos[nextBI].taken {
				nextBI++
			}
			if nextBI == n || decos[nextBI].cost >= the.cost {
				break loop
			}
			add := &decos[nextBI]
			add.taken = true
			ans += int64(add.cost)
			t[add.like]++
			because = append(because, add)
			nextBI++
		case 1:
			if need[0].cost >= the.cost {
				break loop
			}
			need[0].taken = true
			ans += int64(need[0].cost)
			t[need[0].like]++
		case 2:
			if len(because) == 0 {
				break loop
			}
			b := because[len(because)-1]
			for b.like != 0 {
				because = because[:len(because)-1]
				if len(because) == 0 {
					break loop
				}
				b = because[len(because)-1]
			}
			if len(because) == 0 || need[0].cost+need[1].cost >= the.cost+b.cost {
				break loop
			}
			for _, need := range need {
				need.taken = true
				ans += int64(need.cost)
				t[need.like]++
			}
			t[b.like]--
			b.taken = false
			ans -= int64(b.cost)
			because = because[:len(because)-1]
		}
		the.taken = false
		ans -= int64(the.cost)
		t[3]--
	}

	fmt.Println(ans)
}

package main

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

type decoration struct {
	cost, like int
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 2<<16)
	var n, m, k int
	fmt.Fscan(in, &n, &m, &k)
	if k > m {
		fmt.Println(-1)
		return
	}
	decos := make([]decoration, n)
	for i := range decos {
		fmt.Fscan(in, &decos[i].cost)
	}
	var a, x int
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 1
	}
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 2
	}

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

	var byLike [4][]int
	for _, d := range decos[:m] {
		byLike[d.like] = append(byLike[d.like], d.cost)
	}

	i := m
	for (len(byLike[3])+len(byLike[1]) < k || len(byLike[3])+len(byLike[2]) < k || len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m) && i < n {
		switch like := decos[i].like; like {
		case 1, 2:
			if len(byLike[0]) == 0 {
				i++
				continue
			}
			if len(byLike[3])+len(byLike[like]) < k {
				byLike[like] = append(byLike[like], decos[i].cost)
			}
			if len(byLike[3])+len(byLike[2]) < k {
				byLike[2] = append(byLike[2], decos[i].cost)
			}
		case 3:
			byLike[3] = append(byLike[3], decos[i].cost)
		}
	loop:
		for len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m {
			switch {
			case len(byLike[3])+len(byLike[1]) > k:
				if len(byLike[0]) == 0 || byLike[0][len(byLike[0])-1] < byLike[1][len(byLike[1])-1] {
					byLike[1] = byLike[1][:len(byLike[1])-1]
				} else {
					byLike[0] = byLike[0][:len(byLike[0])-1]
				}
			case len(byLike[3])+len(byLike[2]) > k:
				if len(byLike[0]) == 0 || byLike[0][len(byLike[0])-1] < byLike[2][len(byLike[2])-1] {
					byLike[2] = byLike[2][:len(byLike[2])-1]
				} else {
					byLike[0] = byLike[0][:len(byLike[0])-1]
				}
			case len(byLike[0]) > 0:
				byLike[0] = byLike[0][:len(byLike[0])-1]
			default:
				break loop
			}
		}
		i++
	}

	if len(byLike[3])+len(byLike[1]) < k || len(byLike[3])+len(byLike[2]) < k || len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m {
		fmt.Println(-1)
		return
	}
	ans := 0
	for _, l := range byLike {
		for _, v := range l {
			ans += v
		}
	}
	fmt.Println(ans)
}

package main

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

type decoration struct {
	cost, like int
}

func last(s []int) int {
	return s[len(s)-1]
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 2<<16)
	var n, m, k int
	fmt.Fscan(in, &n, &m, &k)
	if k > m {
		fmt.Println(-1)
		return
	}
	decos := make([]decoration, n)
	for i := range decos {
		fmt.Fscan(in, &decos[i].cost)
	}
	var a, x int
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 1
	}
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 2
	}

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

	var byLike [4][]int
	for _, d := range decos[:m] {
		byLike[d.like] = append(byLike[d.like], d.cost)
	}

	i := m
	var out []int
	pop := func(s *[]int) {
		nl := len(*s) - 1
		out = append(out, (*s)[nl])
		*s = (*s)[:nl]
	}
	for (len(byLike[3])+len(byLike[1]) < k || len(byLike[3])+len(byLike[2]) < k || len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m) && i < n {
		switch like := decos[i].like; like {
		case 1, 2:
			if len(byLike[0]) == 0 {
				i++
				continue
			}
			if len(byLike[3])+len(byLike[like]) < k {
				byLike[like] = append(byLike[like], decos[i].cost)
			}
			if len(byLike[3])+len(byLike[2]) < k {
				byLike[2] = append(byLike[2], decos[i].cost)
			}
		case 3:
			byLike[3] = append(byLike[3], decos[i].cost)
		}
	loop:
		for len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m {
			switch {
			case len(byLike[3])+len(byLike[1]) > k:
				if len(byLike[0]) == 0 || last(byLike[0]) < last(byLike[1]) {
					pop(&byLike[1])
				} else {
					pop(&byLike[0])
				}
			case len(byLike[3])+len(byLike[2]) > k:
				if len(byLike[0]) == 0 || last(byLike[0]) < last(byLike[2]) {
					pop(&byLike[2])
				} else {
					pop(&byLike[0])
				}
			case len(byLike[0]) > 0:
				pop(&byLike[0])
			default:
				break loop
			}
		}
		i++
	}

	if len(byLike[3])+len(byLike[1]) < k || len(byLike[3])+len(byLike[2]) < k || len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m {
		fmt.Println(-1)
		return
	}
	sort.Ints(out)
	ans := 0
	for i < n && len(out) > 0 && len(byLike[1]) > 0 && len(byLike[2]) > 0 && last(byLike[1])+last(byLike[2]) > out[0]+decos[i].cost {
		if decos[i].like != 3 {
			i++
			continue
		}
		ans += out[0] + decos[i].cost
		out = out[1:]
		pop(&byLike[1])
		pop(&byLike[2])
		i++
	}
	for _, l := range byLike {
		for _, v := range l {
			ans += v
		}
	}
	fmt.Println(ans)
}

package main

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

var in = bufio.NewScanner(os.Stdin)

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

type decoration struct {
	cost int64
	like byte
}

type byCost []decoration

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

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	m := int(readInt())
	k := int(readInt())
	if k > m {
		fmt.Println(-1)
		return
	}

	dec := make([]decoration, n)
	for i := range dec {
		dec[i].cost = readInt()
	}

	for a := readInt(); a > 0; a-- {
		dec[readInt()-1].like ^= 1
	}
	for b := readInt(); b > 0; b-- {
		dec[readInt()-1].like ^= 2
	}

	sort.Sort(byCost(dec))

	var tot int64
	var byLike [4][]int64
	for i, d := range dec {
		add := func() {
			byLike[d.like] = append(byLike[d.like], d.cost)
			tot += d.cost
		}
		if i < m {
			add()
			continue
		}
		if len(byLike[1])+len(byLike[3]) >= k && len(byLike[2])+len(byLike[3]) >= k {
			fmt.Println(tot)
			return
		}
		switch d.like {
		case 0:
		case 1:
			if len(byLike[1])+len(byLike[3]) >= k {
				break
			}
			if len(byLike[2])+len(byLike[3]) > k && len(byLike[2]) > 0 && (len(byLike[0]) == 0 || byLike[0][len(byLike[0])-1] < byLike[2][len(byLike[2])-1]) {
				nl := len(byLike[2]) - 1
				tot -= byLike[2][nl]
				byLike[2] = byLike[2][:nl]
				add()
			} else if len(byLike[0]) > 0 {
				nl := len(byLike[0]) - 1
				tot -= byLike[0][nl]
				byLike[0] = byLike[0][:nl]
				add()
			}
		case 2:
			if len(byLike[2])+len(byLike[3]) >= k {
				break
			}
			if len(byLike[1])+len(byLike[3]) > k && len(byLike[1]) > 0 && (len(byLike[0]) == 0 || byLike[0][len(byLike[0])-1] < byLike[1][len(byLike[1])-1]) {
				nl := len(byLike[1]) - 1
				tot -= byLike[1][nl]
				byLike[1] = byLike[1][:nl]
				add()
			} else if len(byLike[0]) > 0 {
				nl := len(byLike[0]) - 1
				tot -= byLike[0][nl]
				byLike[0] = byLike[0][:nl]
				add()
			}
		case 3:
			best := -1
			if len(byLike[0]) > 0 {
				best = 0
			}
			if len(byLike[1]) > 0 && len(byLike[1])+len(byLike[3]) >= k && (best == -1 || byLike[best][len(byLike[best])-1] < byLike[1][len(byLike[1])-1]) {
				best = 1
			}
			if len(byLike[2]) > 0 && len(byLike[2])+len(byLike[3]) >= k && (best == -1 || byLike[best][len(byLike[best])-1] < byLike[2][len(byLike[2])-1]) {
				best = 2
			}
			if best == -1 {
				if len(byLike[1]) > 0 && (len(byLike[2]) == 0 || byLike[1][len(byLike[1])-1] > byLike[2][len(byLike[2])-1]) {
					best = 1
				} else {
					best = 2
				}
			}
			nl := len(byLike[best]) - 1
			tot -= byLike[best][nl]
			byLike[best] = byLike[best][:nl]
			add()
		}
	}
	if len(byLike[1])+len(byLike[3]) >= k && len(byLike[2])+len(byLike[3]) >= k {
		fmt.Println(tot)
	} else {
		fmt.Println(-1)
	}
}

package main

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

type decoration struct {
	cost, like int
}

func last(s []int) int {
	return s[len(s)-1]
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 2<<16)
	var n, m, k int
	fmt.Fscan(in, &n, &m, &k)
	if k > m {
		fmt.Println(-1)
		return
	}
	decos := make([]decoration, n)
	for i := range decos {
		fmt.Fscan(in, &decos[i].cost)
	}
	var a, x int
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 1
	}
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 2
	}

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

	var byLike [4][]int
	for _, d := range decos[:m] {
		byLike[d.like] = append(byLike[d.like], d.cost)
	}

	i := m
	var out []int
	pop := func(s *[]int) {
		nl := len(*s) - 1
		out = append(out, (*s)[nl])
		*s = (*s)[:nl]
	}
	for (len(byLike[3])+len(byLike[1]) < k || len(byLike[3])+len(byLike[2]) < k || len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m) && i < n {
		switch like := decos[i].like; like {
		case 1, 2:
			if len(byLike[0]) == 0 {
				i++
				continue
			}
			if len(byLike[3])+len(byLike[like]) < k {
				byLike[like] = append(byLike[like], decos[i].cost)
			}
			if len(byLike[3])+len(byLike[2]) < k {
				byLike[2] = append(byLike[2], decos[i].cost)
			}
		case 3:
			byLike[3] = append(byLike[3], decos[i].cost)
		}
	loop:
		for len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m {
			switch {
			case len(byLike[3])+len(byLike[1]) > k:
				if len(byLike[0]) == 0 || last(byLike[0]) < last(byLike[1]) {
					pop(&byLike[1])
				} else {
					pop(&byLike[0])
				}
			case len(byLike[3])+len(byLike[2]) > k:
				if len(byLike[0]) == 0 || last(byLike[0]) < last(byLike[2]) {
					pop(&byLike[2])
				} else {
					pop(&byLike[0])
				}
			case len(byLike[0]) > 0:
				pop(&byLike[0])
			default:
				break loop
			}
		}
		i++
	}

	if len(byLike[3])+len(byLike[1]) < k || len(byLike[3])+len(byLike[2]) < k || len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m {
		fmt.Println(-1)
		return
	}
	sort.Ints(out)
	ans := 0
	for i < n && len(out) > 0 && len(byLike[1]) > 0 && len(byLike[2]) > 0 && last(byLike[1])+last(byLike[2]) > out[0]+decos[i].cost {
		if decos[i].like != 3 {
			i++
			continue
		}
		ans += out[0] + decos[i].cost
		pop(&byLike[1])
		pop(&byLike[2])
		i++
	}
	for _, l := range byLike {
		for _, v := range l {
			ans += v
		}
	}
	fmt.Println(ans)
}

package main

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

type decoration struct {
	cost, like int
	taken      bool
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 2<<16)
	var n, m, k int
	fmt.Fscan(in, &n, &m, &k)
	if k > m {
		fmt.Println(-1)
		return
	}
	decos := make([]decoration, n)
	for i := range decos {
		fmt.Fscan(in, &decos[i].cost)
	}
	var a, x int
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 1
	}
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 2
	}

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

	var byLike [4][]*decoration
	for i, d := range decos {
		byLike[d.like] = append(byLike[d.like], &decos[i])
	}

	if len(byLike[1])+len(byLike[3]) < k || len(byLike[2])+len(byLike[3]) < k || (k-len(byLike[3]))*2+len(byLike[3]) > m {
		fmt.Println(-1)
		return
	}

	ans := int64(0)
	var t [4]int
	for t[3] < k && t[3] < len(byLike[3]) {
		byLike[3][t[3]].taken = true
		ans += int64(byLike[3][t[3]].cost)
		t[3]++
	}
	for _, i := range []int{1, 2} {
		for t[i]+t[3] < k {
			byLike[i][t[i]].taken = true
			ans += int64(byLike[i][t[i]].cost)
			t[i]++
		}
	}

	var because []*decoration
	var nextBI int
	for i, d := range decos {
		if d.taken {
			continue
		}
		if t[0]+t[1]+t[2]+t[3] == m {
			break
		}
		d.taken = true
		ans += int64(d.cost)
		t[d.like]++
		because = append(because, &decos[i])
		nextBI = i + 1
	}

loop:
	for t[3] > 0 {
		var need []*decoration
		for _, i := range []int{1, 2} {
			if t[3]-1+t[i] < k {
				if t[i] == len(byLike[i]) {
					break loop
				}
				need = append(need, byLike[i][t[i]])
			}
		}
		the := byLike[3][t[3]-1]
		switch len(need) {
		case 0:
			for nextBI < n && decos[nextBI].taken {
				nextBI++
			}
			if nextBI == n || decos[nextBI].cost >= the.cost {
				break loop
			}
			add := &decos[nextBI]
			add.taken = true
			ans += int64(add.cost)
			t[add.like]++
			because = append(because, add)
			nextBI++
		case 1:
			if need[0].cost >= the.cost {
				break loop
			}
			need[0].taken = true
			ans += int64(need[0].cost)
			t[need[0].like]++
		case 2:
			if len(because) == 0 {
				break loop
			}
			b := because[len(because)-1]
			if len(because) == 0 || need[0].cost+need[1].cost >= the.cost+b.cost {
				break loop
			}
			for _, need := range need {
				need.taken = true
				ans += int64(need.cost)
				t[need.like]++
			}
			t[b.like]--
			b.taken = false
			ans -= int64(b.cost)
			because = because[:len(because)-1]
		}
		the.taken = false
		ans -= int64(the.cost)
		t[3]--
	}

	fmt.Println(ans)
}

package main

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

var in = bufio.NewScanner(os.Stdin)

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

type decoration struct {
	cost int64
	like byte
}

type byCost []decoration

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

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	m := int(readInt())
	k := int(readInt())
	if k > m {
		fmt.Println(-1)
		return
	}

	dec := make([]decoration, n)
	for i := range dec {
		dec[i].cost = readInt()
	}

	for a := readInt(); a > 0; a-- {
		dec[readInt()-1].like ^= 1
	}
	for b := readInt(); b > 0; b-- {
		dec[readInt()-1].like ^= 2
	}

	sort.Sort(byCost(dec))

	var tot int64
	var byLike [4][]int64
	for i, d := range dec {
		add := func() {
			byLike[d.like] = append(byLike[d.like], d.cost)
			tot += d.cost
		}
		rem := func(l int) {
			nl := len(byLike[l]) - 1
			tot -= byLike[l][nl]
			byLike[l] = byLike[l][:nl]
		}
		if i < m {
			add()
			continue
		}
		if len(byLike[1])+len(byLike[3]) >= k && len(byLike[2])+len(byLike[3]) >= k {
			fmt.Println(tot)
			return
		}
		switch d.like {
		case 0:
		case 1:
			if len(byLike[1])+len(byLike[3]) >= k {
				break
			}
			if len(byLike[2])+len(byLike[3]) > k && len(byLike[2]) > 0 && (len(byLike[0]) == 0 || byLike[0][len(byLike[0])-1] < byLike[2][len(byLike[2])-1]) {
				rem(2)
				add()
			} else if len(byLike[0]) > 0 {
				rem(0)
				add()
			}
		case 2:
			if len(byLike[2])+len(byLike[3]) >= k {
				break
			}
			if len(byLike[1])+len(byLike[3]) > k && len(byLike[1]) > 0 && (len(byLike[0]) == 0 || byLike[0][len(byLike[0])-1] < byLike[1][len(byLike[1])-1]) {
				rem(1)
				add()
			} else if len(byLike[0]) > 0 {
				rem(0)
				add()
			}
		case 3:
			best := -1
			if len(byLike[0]) > 0 {
				best = 0
			}
			if len(byLike[1]) > 0 && len(byLike[1])+len(byLike[3]) >= k && (best == -1 || byLike[best][len(byLike[best])-1] < byLike[1][len(byLike[1])-1]) {
				best = 1
			}
			if len(byLike[2]) > 0 && len(byLike[2])+len(byLike[3]) >= k && (best == -1 || byLike[best][len(byLike[best])-1] < byLike[2][len(byLike[2])-1]) {
				best = 2
			}
			if best == -1 && len(byLike[1])+len(byLike[3]) < k && len(byLike[2])+len(byLike[3]) < k {
				if len(byLike[1]) > 0 && (len(byLike[2]) == 0 || byLike[1][len(byLike[1])-1] > byLike[2][len(byLike[2])-1]) {
					best = 1
				} else {
					best = 2
				}
			}
			if best != -1 {
				rem(best)
				add()
			}
		}
	}
	if len(byLike[1])+len(byLike[3]) >= k && len(byLike[2])+len(byLike[3]) >= k {
		fmt.Println(tot)
	} else {
		fmt.Println(-1)
	}
}

package main

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

type decoration struct {
	cost, like int
}

func last(s []int) int {
	return s[len(s)-1]
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 2<<16)
	var n, m, k int
	fmt.Fscan(in, &n, &m, &k)
	if k > m {
		fmt.Println(-1)
		return
	}
	decos := make([]decoration, n)
	for i := range decos {
		fmt.Fscan(in, &decos[i].cost)
	}
	var a, x int
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 1
	}
	fmt.Fscan(in, &a)
	for i := 0; i < a; i++ {
		fmt.Fscan(in, &x)
		decos[x-1].like |= 2
	}

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

	var byLike [4][]int
	for _, d := range decos[:m] {
		byLike[d.like] = append(byLike[d.like], d.cost)
	}

	i := m
	var out []int
	pop := func(s *[]int) {
		nl := len(*s) - 1
		out = append(out, (*s)[nl])
		*s = (*s)[:nl]
	}
	for (len(byLike[3])+len(byLike[1]) < k || len(byLike[3])+len(byLike[2]) < k || len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m) && i < n {
		switch like := decos[i].like; like {
		case 1, 2:
			if len(byLike[0]) == 0 {
				i++
				continue
			}
			if len(byLike[3])+len(byLike[like]) < k {
				byLike[like] = append(byLike[like], decos[i].cost)
			}
			if len(byLike[3])+len(byLike[2]) < k {
				byLike[2] = append(byLike[2], decos[i].cost)
			}
		case 3:
			byLike[3] = append(byLike[3], decos[i].cost)
		}
	loop:
		for len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m {
			switch {
			case len(byLike[3])+len(byLike[1]) > k:
				if len(byLike[0]) == 0 || last(byLike[0]) < last(byLike[1]) {
					pop(&byLike[1])
				} else {
					pop(&byLike[0])
				}
			case len(byLike[3])+len(byLike[2]) > k:
				if len(byLike[0]) == 0 || last(byLike[0]) < last(byLike[2]) {
					pop(&byLike[2])
				} else {
					pop(&byLike[0])
				}
			case len(byLike[0]) > 0:
				pop(&byLike[0])
			default:
				break loop
			}
		}
		i++
	}

	if len(byLike[3])+len(byLike[1]) < k || len(byLike[3])+len(byLike[2]) < k || len(byLike[0])+len(byLike[1])+len(byLike[2])+len(byLike[3]) > m {
		fmt.Println(-1)
		return
	}
	sort.Ints(out)
	ans := int64(0)
	for i < n && len(out) > 0 && len(byLike[1]) > 0 && len(byLike[2]) > 0 && last(byLike[1])+last(byLike[2]) > out[0]+decos[i].cost {
		if decos[i].like != 3 {
			i++
			continue
		}
		ans += int64(out[0] + decos[i].cost)
		out = out[1:]
		pop(&byLike[1])
		pop(&byLike[2])
		i++
	}
	for _, l := range byLike {
		for _, v := range l {
			ans += int64(v)
		}
	}
	fmt.Println(ans)
}


This is an interactive problem. The only difference between the easy and hard version is the limit on number of questions.There are $$$n$$$ players labelled from $$$1$$$ to $$$n$$$. It is guaranteed that $$$n$$$ is a multiple of $$$3$$$.Among them, there are $$$k$$$ impostors and $$$n-k$$$ crewmates. The number of impostors, $$$k$$$, is not given to you. It is guaranteed that $$$\frac{n}{3} < k < \frac{2n}{3}$$$.In each question, you can choose three distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a, b, c \le n$$$) and ask: "Among the players labelled $$$a$$$, $$$b$$$ and $$$c$$$, are there more impostors or more crewmates?" You will be given the integer $$$0$$$ if there are more impostors than crewmates, and $$$1$$$ otherwise.Find the number of impostors $$$k$$$ and the indices of players that are impostors after asking at most $$$n+6$$$ questions.The jury is adaptive, which means the indices of impostors may not be fixed beforehand and can depend on your questions. It is guaranteed that there is at least one set of impostors which fulfills the constraints and the answers to your questions at any time.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of each test case contains a single integer $$$n$$$ ($$$6 \le n < 10^4$$$, $$$n$$$ is a multiple of $$$3$$$) — the number of players. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^4$$$.

NoteExplanation for example interaction (note that this example only exists to demonstrate the interaction procedure and does not provide any hint for the solution):For the first test case:Question "? 1 2 3" returns $$$0$$$, so there are more impostors than crewmates among players $$$1$$$, $$$2$$$ and $$$3$$$.Question "? 3 4 5" returns $$$1$$$, so there are more crewmates than impostors among players $$$3$$$, $$$4$$$ and $$$5$$$.Outputting "! 3 4 1 2" means that one has found all the impostors, by some miracle. There are $$$k = 3$$$ impostors. The players who are impostors are players $$$4$$$, $$$1$$$ and $$$2$$$.For the second test case:Question "? 7 1 9" returns $$$1$$$, so there are more crewmates than impostors among players $$$7$$$, $$$1$$$ and $$$9$$$.Outputting "! 4 2 3 6 8" means that one has found all the impostors, by some miracle. There are $$$k = 4$$$ impostors. The players who are impostors are players $$$2$$$, $$$3$$$, $$$6$$$ and $$$8$$$.

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	// defer writer.Flush()
	// redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int
	scan(&n)

	var (
		rs     = make([][2]int, 0, n/3-2)
		s0, s1 = -1, -1
	)
	for x := 1; x <= n; x += 3 {
		r := request(x, x+1, x+2)
		if r == 0 && s0 == -1 {
			s0 = x
			continue
		}
		if r == 1 && s1 == -1 {
			s1 = x
			continue
		}
		rs = append(rs, [2]int{x, r})
	}

	var (
		a0, b0, c0   = s0, s0 + 1, s0 + 2
		a1, b1, c1   = s1, s1 + 1, s1 + 2
		tmpval       = make([][2]int, 0, 4)
		meet0, meet1 = false, false
	)
	for _, x := range [...]int{b0, c0, b1, c1} {
		r := request(a0, a1, x)
		tmpval = append(tmpval, [2]int{x, r})
		meet0 = meet0 || r == 0
		meet1 = meet1 || r == 1
	}
	var (
		val   = make([]int, n+1)
		valof = [2]int{-1, -1}
	)
	if meet0 && meet1 {
		for _, i := range tmpval {
			x, r := i[0], i[1]
			val[x] = r
			if r == 0 {
				valof[0] = x
			}
			if r == 1 {
				valof[1] = x
			}
		}
		val[a0] = request(valof[0], valof[1], a0)
		val[a1] = request(valof[0], valof[1], a1)
	} else if meet0 {
		valof[0], valof[1] = a1, b1
		val[a0] = 0
		val[b0] = request(valof[0], valof[1], b0)
		val[c0] = request(valof[0], valof[1], c0)
		val[a1] = 0
		val[b1] = 1
		val[c1] = 1
	} else {
		valof[0], valof[1] = b0, a0
		val[a0] = 1
		val[b0] = 0
		val[c0] = 0
		val[a1] = 1
		val[b1] = request(valof[0], valof[1], b1)
		val[c1] = request(valof[0], valof[1], c1)
	}
	// no case for (!meet0 && !meet1)

	for _, i := range rs {
		a, r := i[0], i[1]
		b, c := a+1, a+2
		ab, bc := request(valof[r^1], a, b), request(valof[r^1], b, c)
		if ab == r^1 && bc == r^1 {
			val[a] = r
			val[b] = r ^ 1
			val[c] = r
		} else if ab == r^1 {
			val[a] = r ^ 1
			val[b] = r
			val[c] = r
		} else if bc == r^1 {
			val[a] = r
			val[b] = r
			val[c] = r ^ 1
		} else {
			val[a] = r
			val[b] = r
			val[c] = r
		}
	}

	var k int
	for i := 1; i <= n; i++ {
		if val[i] == 0 {
			k++
		}
	}

	printf("! %v ", k)
	for i := 1; i <= n; i++ {
		if val[i] == 0 {
			printf("%v ", i)
		}
	}
	printf("\n")
	writer.Flush()
}

func request(a, b, c int) (x int) {
	printf("? %v %v %v\n", a, b, c)
	writer.Flush()
	scan(&x)
	return
}

package main

import (
	"fmt"
	"os"
)

var n int
var ans []int

func ask(a, b, c int) int {
	fmt.Printf("? %d %d %d\n", a, b, c)
	var r int
	fmt.Scan(&r)
	if r == -1 {
		os.Exit(0)
	}
	return r
}

func setAnswer(i, v int) {
	ans[i] = v
}

func solveDifferentTrios(i, j, ansi int) (int, int) {
	var fixedi = i
	if ask(i, i+1, j) == ansi && ask(i, i+1, j+1) == ansi {
		setAnswer(i, ansi)
		setAnswer(i+1, ansi)
	} else if ask(i, i+2, j) == ansi && ask(i, i+2, j+1) == ansi {
		setAnswer(i, ansi)
		setAnswer(i+2, ansi)
	} else {
		setAnswer(i, ansi^1)
		fixedi = i + 1
		setAnswer(i+1, ansi)
		setAnswer(i+2, ansi)
	}

	var fixedj = j
	if ask(fixedi, j, j+1) != ansi {
		setAnswer(j, ansi^1)
		setAnswer(j+1, ansi^1)
	} else if ask(fixedi, j, j+2) != ansi {
		setAnswer(j, ansi^1)
		setAnswer(j+2, ansi^1)
	} else {
		setAnswer(j, ansi)
		fixedj = j + 1
		setAnswer(j+1, ansi^1)
		setAnswer(j+2, ansi^1)
	}

	for _, k := range []int{i, i + 1, i + 2, j, j + 1, j + 2} {
		if ans[k] == -1 {
			ans[k] = ask(fixedi, fixedj, k)
		}
	}

	if ansi == 0 {
		return fixedi, fixedj
	}
	return fixedj, fixedi
}

func printAnswer() {
	fmt.Printf("!")
	var count0 = 0
	for i := 1; i <= n; i++ {
		if ans[i] == 0 {
			count0 += 1
		}
	}

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

func solveCase() {
	fmt.Scan(&n)
	ans = make([]int, n+1)
	for i := 1; i <= n; i++ {
		ans[i] = -1
	}
	var ans123 = ask(1, 2, 3)
	var differentTrioStart = 4
	for ask(differentTrioStart, differentTrioStart+1, differentTrioStart+2) == ans123 {
		differentTrioStart += 3
	}

	idx0, idx1 := solveDifferentTrios(1, differentTrioStart, ans123)

	for i := differentTrioStart + 3; i <= n; i++ {
		ans[i] = ask(idx0, idx1, i)
	}

	var idx = idx0
	if ans123 == 0 {
		idx = idx1
	}

	for i := 4; i < differentTrioStart; i += 3 {
		if ask(i, i+1, idx) == ans123 {
			ans[i] = ans123
			ans[i+1] = ans123
			ans[i+2] = ask(idx0, idx1, i+2)
		} else {
			ans[i] = ask(idx0, idx1, i)
			ans[i+1] = ans[i] ^ 1
			ans[i+2] = ans123
		}
	}
	printAnswer()
}

func main() {
	var ntc int
	fmt.Scan(&ntc)
	for t := 0; t < ntc; t++ {
		solveCase()
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
type (
	initData struct{ n int }
	request  struct{ i, j, k int }
	response struct{ v int }
	answer   struct{ ans []int }
)

type interaction interface {
	readInitData() initData
	query(request) response
	printAnswer(answer)
}

type io struct {
	in  *bufio.Reader
	out *bufio.Writer
}

func (io io) readInitData() (d initData) {
	Fscan(io.in, &d.n)
	return
}

func (io io) query(req request) (resp response) {
	Fprintln(io.out, "?", req.i, req.j, req.k)
	io.out.Flush()
	Fscan(io.in, &resp.v)
	if resp.v < 0 {
		panic(-1)
	}
	return
}

func (io io) printAnswer(a answer) {
	Fprint(io.out, "! ", len(a.ans))
	for _, v := range a.ans {
		Fprint(io.out, " ", v)
	}
	Fprintln(io.out)
	io.out.Flush()
}

func doInteraction(it interaction) {
	q := func(i, j, k int) (good bool) { return it.query(request{i, j, k}).v == 1 }
	dt := it.readInitData()
	n := dt.n
	ans := []int{}
	defer func() { it.printAnswer(answer{ans}) }()

	if n == 6 {
		// 特判？
	}

	var goods, bads [][3]int
	for i := 1; ; i += 3 {
		if q(i, i+1, i+2) {
			goods = append(goods, [3]int{i, i + 1, i + 2})
		} else {
			bads = append(bads, [3]int{i, i + 1, i + 2})
		}
		if goods != nil && bads != nil {
			break
		}
	}

	var badman, goodman int
	good := goods[0]
	bad := bads[0]
	for _, id := range good {
		if q(bad[0], bad[1], id) {
			goodman = id
			badman = bad[2]
			break
		}
	}
	if goodman == 0 {
		badman = bad[0]
		if q(good[0], good[1], badman) {
			goodman = good[0]
		} else if q(good[0], good[2], badman) {
			goodman = good[0]
		} else {
			goodman = good[1]
		}
	}

	vis := make([]bool, n+1)
	vis[goodman] = true
	vis[badman] = true
	ans = append(ans, badman)

	if len(bads) > 1 {
		for _, b := range bads[1:] {
			if q(goodman, b[0], b[1]) {
				ans = append(ans, b[2]) // bad!
				if q(goodman, badman, b[0]) { // b[0] is good
					ans = append(ans, b[1]) // bad!
				} else {
					ans = append(ans, b[0])
				}
				for _, i := range b {
					vis[i] = true
				}
			} else {
				ans = append(ans, b[0], b[1])
				// b[2] 后面问
				vis[b[0]] = true
				vis[b[1]] = true
			}
		}
	}
	if len(goods) > 1 {
		for _, b := range goods[1:] {
			if !q(badman, b[0], b[1]) {
				//ans = append(ans, b[2]) // bad!
				if q(goodman, badman, b[0]) { // b[0] is good
					ans = append(ans, b[1]) // bad!
				} else {
					ans = append(ans, b[0])
				}
				for _, i := range b {
					vis[i] = true
				}
			} else { // good
				// b[2] 后面问
				vis[b[0]] = true
				vis[b[1]] = true
			}
		}
	}

	for i := 1; i <= n; i++ {
		if !vis[i] {
			if !q(goodman, badman, i) {
				ans = append(ans, i)
			}
		}
	}
}

// TODO: check output format before submit
func run() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)

	T := 1
	Fscan(in, &T)
	for ; T > 0; T-- {
		doInteraction(io{in, out})
	}
}

func main() { run() }


One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides, any two neighboring parts were painted different colors, that is, the red and the blue color were alternating, i. e. followed one after the other. The outer area of the wall (the area that lied outside all circles) was painted blue. Help Sherlock Holmes determine the total area of red parts of the wall.Let us remind you that two circles are called concentric if their centers coincide. Several circles are called concentric if any two of them are concentric.

The first line contains the single integer n (1 ≤ n ≤ 100). The second line contains n space-separated integers ri (1 ≤ ri ≤ 1000) — the circles' radii. It is guaranteed that all circles are different.

Print the single real number — total area of the part of the wall that is painted red. The answer is accepted if absolute or relative error doesn't exceed 10 - 4.

NoteIn the first sample the picture is just one circle of radius 1. Inner part of the circle is painted red. The area of the red part equals π × 12 = π.In the second sample there are three circles of radii 1, 4 and 2. Outside part of the second circle is painted blue. Part between the second and the third circles is painted red. Part between the first and the third is painted blue. And, finally, the inner part of the first circle is painted red. Overall there are two red parts: the ring between the second and the third circles and the inner part of the first circle. Total area of the red parts is equal (π × 42 - π × 22) + π × 12 = π × 12 + π = 13π

package main
import (
	"fmt"
	//"bufio"
	//"os"
	//"strconv"
	"sort"
)

func main() {
	pi:=3.14159265358979323846
	var n,p int
	fmt.Scan(&n)
	r:=make([]int,n+1)
	for i:=1;i<=n;i++ {
		fmt.Scan(&r[i])
	}
	r[0]=0
	sort.Ints(r)
	for i:=n;i>=1;i-=2 {
		p+=r[i]*r[i]-r[i-1]*r[i-1]
	}
	//fmt.Println(p)
	hsl:=float64(p)*pi
	fmt.Println(hsl)
}

package main

import (
    "fmt"
    "math"
    "sort"
)

func main() {
    var n int
    fmt.Scan(&n)
    r := make([]float64,n)
    for i := 0; i < n; i++ { fmt.Scan(&r[i]) }
    sort.Float64s(r)
    ans, sign := float64(0), float64(1)
    for i := n-1; i >= 0; i-- {
        ans += sign*(math.Pi*r[i]*r[i])
        sign *= -1
    }
    fmt.Println(ans)
}

// 157B-mic
package main

import (
    "fmt"
    "sort"
)

func main() {
    var n int
    pi := 3.1415926536
    fmt.Scan(&n)
    a := make([]float64, n+1)
    var area float64
    a[0] = 0.0
    for i := 1; i <= n; i++ {
        fmt.Scan(&a[i])
    }
    sort.Sort(sort.Float64Slice(a))
    for i := n; i > 0; i = i - 2 {
        area += pi*a[i]*a[i] - pi*a[i-1]*a[i-1]
    }
    fmt.Println(area)

}


A bracket sequence is a string, containing only characters "(", ")", "[" and "]".A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition.A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition.You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible.

The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters.

In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them.

package main

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

// stack
type Stack struct {
    arr []int
}

func (s *Stack) Len() int {
    return len(s.arr)
}

func (s *Stack) Push(a int) {
    s.arr = append(s.arr, a)
}

func (s *Stack) Pop() int {
    v := s.arr[s.Len()-1]
    s.arr = s.arr[:s.Len()-1]
    return v
}

func (s *Stack) Top() int {
    return s.arr[s.Len()-1]
}

// start
var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

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

func main() {
    defer writer.Flush()

    var s string
    scanf("%s\n", &s)
    solve(s)
}

func solve(s string) {
    mcount, mstart, mend := 0, -1, -1
    stk := &Stack{}
    cstk := &Stack{}
    stk.Push(-1)
    cstk.Push(0)
    for i := range s {
        // pp(stk, cstk)
        if s[i] == '(' || s[i] == '[' {
            stk.Push(i)
            cstk.Push(0)
        } else {
            if stk.Len() == 1 {
                stk = &Stack{}
                cstk = &Stack{}
                stk.Push(i)
                cstk.Push(0)
                continue
            }
            last, clast := stk.Pop(), cstk.Pop()
            if s[i] == ')' {
                if s[last] != '(' {
                    stk = &Stack{}
                    cstk = &Stack{}
                    stk.Push(i)
                    cstk.Push(0)
                    continue
                }
                last2, clast2 := stk.Pop(), cstk.Pop()
                clast2 += clast
                if clast2 > mcount {
                    mcount, mstart, mend = clast2, last2, i
                }
                stk.Push(last2)
                cstk.Push(clast2)
            } else {
                if s[last] != '[' {
                    stk = &Stack{}
                    cstk = &Stack{}
                    stk.Push(i)
                    cstk.Push(0)
                    continue
                }
                last2, clast2 := stk.Pop(), cstk.Pop()
                clast2 += clast + 1
                if clast2 > mcount {
                    mcount, mstart, mend = clast2, last2, i
                }
                stk.Push(last2)
                cstk.Push(clast2)
            }
        }
    }
    // pp(stk, cstk)
    // pp(mstart, mend)
    printf("%d\n%s\n", mcount, s[mstart+1:mend+1])
}


Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met:  the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.

The first line contains a single integer n (1 ≤ n ≤ 100 000) — the numeber of measurements made by Kirill. The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≤ xi ≤ 100 000) — the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.

In the first line print the minimum possible number of equal measurements. In the second line print n integers y1, y2, ..., yn — the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values. If there are multiple answers, print any of them.

NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5.

package main

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

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	x := make([]int, n)
	var max, min int
	for i := 0;i < n;i ++ {
		fmt.Fscanf(reader, "%d", &x[i])
		if i == 0 {
			max, min = x[0], x[0]
		} else {
			if max < x[i] {
				max = x[i]
			}
			if min > x[i] {
				min = x[i]
			}
		}
	}
	if max - min < 2 {
		fmt.Printf("%d\n", n)
		for i := 0;i < n;i ++ {
			fmt.Printf("%d ", x[i])
		}
		return
	}
	var maxCount, minCount, midCount int
	for i := 0;i < n;i ++ {
		switch x[i] {
		case max:
			maxCount ++
		case min:
			minCount ++
		default:
			midCount ++
		}
	}
	merge := maxCount
	if merge > minCount {
		merge = minCount
	}
	split := midCount / 2
	if split > merge {
		fmt.Printf("%d\n", n - 2 * split)
		maxCount, minCount, midCount = maxCount + split, minCount + split, midCount - 2 * split
	} else {
		fmt.Printf("%d\n", n - 2 * merge)
		maxCount, minCount, midCount = maxCount - merge, minCount - merge, midCount + 2 * merge
	}
	for i := 0;i < maxCount;i ++ {
		fmt.Printf("%d ", max)
	}
	for i := 0;i < minCount;i ++ {
		fmt.Printf("%d ", min)
	}
	for i := 0;i < midCount;i ++ {
		fmt.Printf("%d ", min + 1)
	}

}

package main

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

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

	var n int
	Fscan(in, &n)
	a := make([]int, n)
	c := map[int]int{}
	for i := range a {
		Fscan(in, &a[i])
		c[a[i]]++
	}
	b := []int{}
	for k := range c {
		b = append(b, k)
	}
	sort.Ints(b)
	if len(b) == 2 && b[0]+2 == b[1] {
		b = []int{b[0], b[0] + 1, b[1]}
	}
	if len(b) == 3 {
		min02 := c[b[0]]
		if c[b[2]] < min02 {
			min02 = c[b[2]]
		}
		if c[b[1]]/2 > min02 {
			c[b[1]] &^= 1
			n -= c[b[1]]
			for i, v := range a {
				if v == b[1] && c[v] > 0 {
					a[i] = b[c[v]&1<<1]
					c[v]--
				}
			}
		} else {
			n -= 2 * min02
			c[b[0]] = min02
			c[b[2]] = min02
			for i, v := range a {
				if v != b[1] && c[v] > 0 {
					a[i] = b[1]
					c[v]--
				}
			}
		}
	}
	Fprintln(out, n)
	for _, v := range a {
		Fprint(out, v, " ")
	}
}

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

package main

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

const (
  INF = 1234567890
)

func Init() {
}

func Solve(io *FastIO) {
  N := io.NextInt()
  X := io.NextIntArray(N)

  lo := INF
  hi := -INF
  for _, v := range X {
    lo = Min(lo, v)
    hi = Max(hi, v)
  }

  if hi - lo < 2 {
    io.Println(N)
    for _, v := range X {
      io.Printf("%d ", v)
    }
    io.Println()
    return
  }

  neg := 0
  zero := 0
  pos := 0
  for i := range X {
    X[i] -= lo + 1
    if X[i] < 0 {
      neg++
    } else if X[i] > 0 {
      pos++
    } else {
      zero++
    }
  }

  // extraNeg := 0
  // extraPos := 0
  // if neg > pos {
  //   extraNeg = neg - pos
  //   neg = pos
  // } else {
  //   extraPos = pos - neg
  //   pos = neg
  // }

  // fmt.Println(X)
  // fmt.Printf("neg = %d, pos = %d\n", neg, pos)

  n, z, p := neg, zero, pos
  for n > 0 && p > 0 {
    n--
    z += 2
    p--
  }

  bn, bz, bp := -1, -1, -1
  bestDiff := -1
  for z >= 0 {
    d := Diff(neg, zero, pos, n, z, p)
    if d >= bestDiff {
      bestDiff = d
      bn, bz, bp = n, z, p
    }
    n++
    z -= 2
    p++
  }

  io.Println(N - bestDiff)
  for i := 0; i < bn; i++ {
    io.Printf("%d ", lo)
  }
  for i := 0; i < bz; i++ {
    io.Printf("%d ", lo + 1)
  }
  for i := 0; i < bp; i++ {
    io.Printf("%d ", hi)
  }
  io.Println()

  // bestNZ := 0
  // bestDiff := -1
  // for i := 0; (i << 1) <= N; i++ {
  //   d := Diff(neg, zero, pos, i, zero + (i << 1), i)
  //   // fmt.Printf("i = %d, d = %d\n", i, d)
  //   if d >= bestDiff {
  //     bestDiff = d
  //     bestNZ = i
  //   }
  // }

  // io.Println(N - bestDiff)

  // cnt := 0
  // for i := 0; i < bestNZ; i++ {
  //   io.Printf("%d %d ", lo, hi)
  //   cnt += 2
  // }
  // for i := 0; i < extraNeg; i++ {
  //   io.Printf("%d ", lo)
  //   cnt++
  // }
  // for i := 0; i < extraPos; i++ {
  //   io.Printf("%d ", hi)
  //   cnt++
  // }
  // for cnt < N {
  //   io.Printf("%d ", lo + 1)
  //   cnt++
  // }
  // io.Println()
}

func Diff(n0, z0, p0, n1, z1, p1 int) int {
  n0 -= Min(n0, n1)
  z0 -= Min(z0, z1)
  p0 -= Min(p0, p1)
  return n0 + z0 + p0
}

func Min(args ...int) int {
	min := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] < min {
			min = args[i]
		}
	}
	return min
}

func Max(args ...int) int {
	max := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] > max {
			max = args[i]
		}
	}
	return max
}

type FastIO struct {
	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 sgn * res
}

func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = (res * 10) + int64(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

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"
	"fmt"
	"os"
	"sort"
)

var n int
var a map[int]int

func printSolution(eq int, a map[int]int) {
	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	fmt.Fprintln(outBuf, eq)

	for k, v := range a {
		for i := 0; i < v; i++ {
			fmt.Fprintf(outBuf, "%d ", k)
		}
	}
}

func main() {
	inBuf := bufio.NewReader(os.Stdin)
	a := make(map[int]int)
	fmt.Fscanf(inBuf, "%d\n", &n)
	for i := 0; i < n; i++ {
		var tmp int
		fmt.Fscanf(inBuf, "%d", &tmp)
		a[tmp]++
	}
	keys := make([]int, 0)
	for k, _ := range a {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })

	if len(a) < 3 {
		if len(a) == 2 && keys[1] - keys[0] == 2 {
			t1 := a[keys[0]]
			if t1 > a[keys[1]] {
				t1 = a[keys[1]]
			}
			a[keys[0]+1] += 2*t1
			a[keys[0]] -= t1
			a[keys[1]] -= t1
			n -= 2*t1
		}
		printSolution(n, a)
		return
	}

	t1 := a[keys[0]]
	if t1 > a[keys[2]] {
		t1 = a[keys[2]]
	}
	t2 := a[keys[1]] / 2
	ans := 0
	if t2 > t1 {
		ans = n - 2 * t2
		a[keys[0]] += t2
		a[keys[2]] += t2
		a[keys[1]] -= 2*t2
	}  else {
		ans = n - 2*t1
		a[keys[0]] -= t1
		a[keys[2]] -= t1
		a[keys[1]] += 2*t1
	}
	printSolution(ans, a)
}

package main

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

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

	var n int
	Fscan(in, &n)
	a := make([]int, n)
	c := map[int]int{}
	for i := range a {
		Fscan(in, &a[i])
		c[a[i]]++
	}
	if len(c) == 3 {
		b := []int{}
		for k := range c {
			b = append(b, k)
		}
		sort.Ints(b)
		min02 := c[b[0]]
		if c[b[2]] < min02 {
			min02 = c[b[2]]
		}
		if c[b[1]]/2 > min02 {
			c[b[1]] &^= 1
			n -= c[b[1]]
			for i, v := range a {
				if v == b[1] && c[v] > 0 {
					a[i] = b[c[v]&1<<1]
					c[v]--
				}
			}
		} else {
			n -= 2 * min02
			c[b[0]] = min02
			c[b[2]] = min02
			for i, v := range a {
				if v != b[1] && c[v] > 0 {
					a[i] = b[1]
					c[v]--
				}
			}
		}
	}
	Fprintln(out, n)
	for _, v := range a {
		Fprint(out, v, " ")
	}
}

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

package main

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

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

	var n int
	Fscan(in, &n)
	a := make([]int, n)
	c := map[int]int{}
	for i := range a {
		Fscan(in, &a[i])
		c[a[i]]++
	}
	if len(c) == 3 {
		b := []int{}
		for k := range c {
			b = append(b, k)
		}
		sort.Ints(b)
		if c[b[0]] < c[b[2]] {
			c[b[2]] = c[b[0]]
		} else {
			c[b[0]] = c[b[2]]
		}
		n -= 2 * c[b[0]]
		for i, v := range a {
			if v != b[1] && c[v] > 0 {
				a[i] = b[1]
				c[v]--
			}
		}
	}
	Fprintln(out, n)
	for _, v := range a {
		Fprint(out, v, " ")
	}
}

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

package main

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

const (
  INF = 1234567890
)

func Init() {
}

func Solve(io *FastIO) {
  N := io.NextInt()
  X := io.NextIntArray(N)

  lo := INF
  hi := -INF
  for _, v := range X {
    lo = Min(lo, v)
    hi = Max(hi, v)
  }

  if hi - lo < 2 {
    io.Println(N)
    for _, v := range X {
      io.Printf("%d ", v)
    }
    io.Println()
    return
  }

  neg := 0
  zero := 0
  pos := 0
  for i := range X {
    X[i] -= lo + 1
    if X[i] < 0 {
      neg++
    } else if X[i] > 0 {
      pos++
    } else {
      zero++
    }
  }

  extraNeg := 0
  extraPos := 0
  if neg > pos {
    extraNeg = neg - pos
    neg = pos
  } else {
    extraPos = pos - neg
    pos = neg
  }

  // fmt.Println(X)
  // fmt.Printf("neg = %d, pos = %d\n", neg, pos)

  bestNZ := 0
  bestDiff := -1
  for i := 0; i <= neg; i++ {
    d := Diff(neg, zero, pos, i, zero + (i << 1), i)
    // fmt.Printf("i = %d, d = %d\n", i, d)
    if d >= bestDiff {
      bestDiff = d
      bestNZ = i
    }
  }

  io.Println(N - bestDiff)

  cnt := 0
  for i := 0; i < bestNZ; i++ {
    io.Printf("%d %d ", lo, hi)
    cnt += 2
  }
  for i := 0; i < extraNeg; i++ {
    io.Printf("%d ", lo)
    cnt++
  }
  for i := 0; i < extraPos; i++ {
    io.Printf("%d ", hi)
    cnt++
  }
  for cnt < N {
    io.Printf("%d ", lo + 1)
    cnt++
  }
  io.Println()
}

func Diff(n0, z0, p0, n1, z1, p1 int) int {
  n0 -= Min(n0, n1)
  z0 -= Min(z0, z1)
  p0 -= Min(p0, p1)
  return n0 + z0 + p0
}

func Min(args ...int) int {
	min := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] < min {
			min = args[i]
		}
	}
	return min
}

func Max(args ...int) int {
	max := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] > max {
			max = args[i]
		}
	}
	return max
}

type FastIO struct {
	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 sgn * res
}

func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = (res * 10) + int64(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

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"
	"fmt"
	"os"
	"sort"
)

var n int
var a map[int]int

func printSolution(eq int, a map[int]int) {
	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	fmt.Fprintln(outBuf, eq)

	for k, v := range a {
		for i := 0; i < v; i++ {
			fmt.Fprintf(outBuf, "%d ", k)
		}
	}
}

func main() {
	inBuf := bufio.NewReader(os.Stdin)
	a := make(map[int]int)
	fmt.Fscanf(inBuf, "%d\n", &n)
	for i := 0; i < n; i++ {
		var tmp int
		fmt.Fscanf(inBuf, "%d", &tmp)
		a[tmp]++
	}

	if len(a) < 3 {
		printSolution(n, a)
		return
	}

	keys := make([]int, 0)
	for k, _ := range a {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })

	t1 := a[keys[0]]
	if t1 > a[keys[2]] {
		t1 = a[keys[2]]
	}
	t2 := a[keys[1]] / 2
	ans := 0
	if t2 > t1 {
		ans = n - a[keys[1]]
		a[keys[0]] += t2
		a[keys[2]] += t2
		a[keys[1]] -= 2*t2
	}  else {
		ans = n - 2*t1
		a[keys[0]] -= t1
		a[keys[2]] -= t1
		a[keys[1]] += 2*t1
	}
	printSolution(ans, a)
}

package main

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

var n int
var a map[int]int

func printSolution(eq int, a map[int]int) {
	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() }()

	fmt.Fprintln(outBuf, eq)

	for k, v := range a {
		for i := 0; i < v; i++ {
			fmt.Fprintf(outBuf, "%d ", k)
		}
	}
}

func main() {
	inBuf := bufio.NewReader(os.Stdin)
	a := make(map[int]int)
	fmt.Fscanf(inBuf, "%d\n", &n)
	for i := 0; i < n; i++ {
		var tmp int
		fmt.Fscanf(inBuf, "%d", &tmp)
		a[tmp]++
	}

	if len(a) < 3 {
		printSolution(n, a)
		return
	}

	keys := make([]int, 0)
	for k, _ := range a {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })

	t1 := a[keys[0]]
	if t1 > a[keys[2]] {
		t1 = a[keys[2]]
	}
	t2 := a[keys[1]] / 2
	ans := 0
	if t2 > t1 {
		ans = n - 2 * t2
		a[keys[0]] += t2
		a[keys[2]] += t2
		a[keys[1]] -= 2*t2
	}  else {
		ans = n - 2*t1
		a[keys[0]] -= t1
		a[keys[2]] -= t1
		a[keys[1]] += 2*t1
	}
	printSolution(ans, a)
}


Colossal! — exclaimed Hawk-nose. — A programmer! That's exactly what we are looking for.Arkadi and Boris Strugatsky. Monday starts on SaturdayReading the book "Equations of Mathematical Magic" Roman Oira-Oira and Cristobal Junta found an interesting equation: $$$a - (a \oplus x) - x = 0$$$ for some given $$$a$$$, where $$$\oplus$$$ stands for a bitwise exclusive or (XOR) of two integers (this operation is denoted as ^ or xor in many modern programming languages). Oira-Oira quickly found some $$$x$$$, which is the solution of the equation, but Cristobal Junta decided that Oira-Oira's result is not interesting enough, so he asked his colleague how many non-negative solutions of this equation exist. This task turned out to be too difficult for Oira-Oira, so he asks you to help.

Each test contains several possible values of $$$a$$$ and your task is to find the number of equation's solution for each of them. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of these values. The following $$$t$$$ lines contain the values of parameter $$$a$$$, each value is an integer from $$$0$$$ to $$$2^{30} - 1$$$ inclusive.

For each value of $$$a$$$ print exactly one integer — the number of non-negative solutions of the equation for the given value of the parameter. Print answers in the same order as values of $$$a$$$ appear in the input. One can show that the number of solutions is always finite.

NoteLet's define the bitwise exclusive OR (XOR) operation. Given two integers $$$x$$$ and $$$y$$$, consider their binary representations (possibly with leading zeroes): $$$x_k \dots x_2 x_1 x_0$$$ and $$$y_k \dots y_2 y_1 y_0$$$. Here, $$$x_i$$$ is the $$$i$$$-th bit of the number $$$x$$$ and $$$y_i$$$ is the $$$i$$$-th bit of the number $$$y$$$. Let $$$r = x \oplus y$$$ be the result of the XOR operation of $$$x$$$ and $$$y$$$. Then $$$r$$$ is defined as $$$r_k \dots r_2 r_1 r_0$$$ where:$$$$$$ r_i = \left\{ \begin{aligned} 1, ~ \text{if} ~ x_i \ne y_i \\ 0, ~ \text{if} ~ x_i = y_i \end{aligned} \right. $$$$$$For the first value of the parameter, only $$$x = 0$$$ is a solution of the equation.For the second value of the parameter, solutions are $$$x = 0$$$ and $$$x = 2$$$.

package main

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

var scanner *bufio.Scanner

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

func nextInt() int {
	num, err := strconv.Atoi(next())
	if err != nil {
		panic(err.Error())
	}
	return num
}

func main() {
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	T := nextInt()
	for ; T>0; T-- {
		num := nextInt()
		calc := 1 << uint(bits.OnesCount(uint(num)))
		fmt.Println(calc)
	}

}

package main

import "fmt"

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

    var arr [100005]int
    for i:= 1; i <= n; i++ {
        fmt.Scanf("%d\n", &arr[i])
    }

    for i:= 1; i <= n; i++ {
        bitCnt := 0
        for j:= 0; j < 30; j++ {
            if arr[i] & (1 << uint(j)) > 0 {
                bitCnt++;
            }
        }
        fmt.Printf("%d\n", 1<<uint(bitCnt))
    }
}

package main

import (
	"fmt"
	"math"
)

func calcBitCount(num int64) int {
	count := 0
	for num > 0 {
		if num%2 == 1 {
			count++
		}
		num /= 2
	}
	return count
}

func main() {
	C := 0
	fmt.Scan(&C)
	for i := 0; i < C; i++ {
		num := int64(0)
		fmt.Scan(&num)
		if num == 0 {
			fmt.Println(1)
			continue
		}
		bitCount := calcBitCount(num)
		fmt.Println(int64(math.Exp2(float64(bitCount))))
	}
}


This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.There is a city in which Dixit lives. In the city, there are $$$n$$$ houses. There is  exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the $$$i$$$-th house is $$$k_i$$$.Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B.Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of $$$|k_A - k_B|$$$, where $$$k_i$$$ is the number of roads leading to the house $$$i$$$. If more than one optimal pair exists, any of them is suitable.Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist?In the problem input, you are not given the direction of each road. You are given — for each house — only the number of incoming roads to that house ($$$k_i$$$).You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice.Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit.See the Interaction section below for more details.

The first line contains a single integer $$$n$$$ ($$$3 \le n \le 500$$$) denoting the number of houses in the city. The next line contains $$$n$$$ space-separated integers $$$k_1, k_2, \dots, k_n$$$ ($$$0 \le k_i \le n - 1$$$), the $$$i$$$-th of them represents the number of incoming roads to the $$$i$$$-th house.

NoteIn the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house $$$1$$$ to house $$$2$$$. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits.In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city.

package main
import(."fmt";"sort")

// github.com/EndlessCheng/codeforces-go
func main(){
	var n,s,j,v,w int;d:=-1
	Scan(&n)
	a:=make([]struct{k,i int},n)
	for i:=range a{Scan(&a[i].k);a[i].i=i+1}
	sort.Slice(a,func(i,j int)bool{return a[i].k<a[j].k})
	for i,p:=range a{
		if s+=p.k-i;s==0{
			if j!=i&&p.k-a[j].k>d{d,v,w=p.k-a[j].k,p.i,a[j].i}
			j=i+1
		}
	}
	Println("!",v,w)
}