Suppose you have an integer $$$v$$$. In one operation, you can:   either set $$$v = (v + 1) \bmod 32768$$$  or set $$$v = (2 \cdot v) \bmod 32768$$$. You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. What is the minimum number of operations you need to make each $$$a_i$$$ equal to $$$0$$$?

The first line contains the single integer $$$n$$$ ($$$1 \le n \le 32768$$$) — the number of integers. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < 32768$$$).

Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the minimum number of operations required to make $$$a_i$$$ equal to $$$0$$$.

NoteLet's consider each $$$a_i$$$:   $$$a_1 = 19$$$. You can, firstly, increase it by one to get $$$20$$$ and then multiply it by two $$$13$$$ times. You'll get $$$0$$$ in $$$1 + 13 = 14$$$ steps.  $$$a_2 = 32764$$$. You can increase it by one $$$4$$$ times: $$$32764 \rightarrow 32765 \rightarrow 32766 \rightarrow 32767 \rightarrow 0$$$.  $$$a_3 = 10240$$$. You can multiply it by two $$$4$$$ times: $$$10240 \rightarrow 20480 \rightarrow 8192 \rightarrow 16384 \rightarrow 0$$$.  $$$a_4 = 49$$$. You can multiply it by two $$$15$$$ times.

package main

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

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

const M uint64 = 32768

func A(_r io.Reader, _w io.Writer) {
	in, out := bufio.NewReader(_r), bufio.NewWriterSize(_w, 102400000)
	defer out.Flush()

	f := [32770]uint64{}
	for i := range f {
		f[i] = 1e10
	}
	f[0] = 0
	f[32768] = 0
	que := []uint64{32768}
	for len(que) > 0 {
		top := que[0]
		que = que[1:]
		//v+1
		if top != 0 && f[top]+1 < f[top-1] {
			f[top-1] = f[top] + 1
			que = append(que, top-1)
		}
		//v*2
		if k := top / 2; top%2 == 0 && f[top]+1 < f[k] {
			f[k] = f[top] + 1
			que = append(que, k)
		}
		if k := (top + M) / 2; k%2 == 0 && k/2 <= 32768 && f[top]+1 < f[k] {
			f[k] = f[top] + 1
			que = append(que, k)
		}
	}
	var c int
	var n int
	Fscan(in, &c)
	for i := 1; i <= c; i++ {
		Fscan(in, &n)
		Fprintf(out, "%d%s", f[n], " ")
	}
}

package main

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

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

	var n int
	fmt.Fscan(in, &n)

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

		min := 32768 - v
		for j := 0; j < 16; j++ {
			if v+j == 0 {
				min = 0
				break
			}

			trail := 16 - bits.TrailingZeros(uint(v+j)) + j - 1
			if trail < min {
				min = trail
			}
		}
		fmt.Fprintf(out, "%d ", min)
	}
	fmt.Fprintln(out)
}

package main

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

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {
		var n int
		fmt.Fscan(r, &n)

		res := 15
		for i := 0; i < 14; i++ {
			for j := 0; i + j < res; j++ {
				if ( (n+i)*(1<<j) ) % 32768 == 0 {
					res = i + j
				}
			}
		}
		fmt.Fprintf(w, "%d ", res)
	}
	fmt.Fprintln(w, "")
}

package main

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

/*
type deque interface {
	emplace(n int)
	top() int
	bottom() int
	popback() int
	popfront() int
	empty() bool
}
*/
type deque struct {
	q []int
}

func (q *deque) emplace(n int) {
	(*q).q = append((*q).q, n)
}

func (q deque) empty() bool {
	return len(q.q) == 0
}

func (q deque) top() int {
	if q.empty() {
		panic("top() performed on empty deque")
	}
	return q.q[len(q.q)-1]
}

func (q *deque) popback() int {
	if q.empty() {
		panic("popback() performed on empty deque")
	}
	res := (*q).top()
	(*q).q = (*q).q[:len((*q).q)-1]
	return res
}

func (q deque) bottom() int {
	if q.empty() {
		panic("bottom() performed on empty deque")
	}
	return q.q[0]
}

func (q *deque) popfront() int {
	if q.empty() {
		panic("popfront() performed on empty deque")
	}
	res := (*q).bottom()
	(*q).q = (*q).q[1:]
	return res
}

func right(n int) int {
	if n % 2 == 1 { return 0 }
	return n/2
}

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

	N := 32768

	vis := make([]bool, N)
	dis := make([]int, N)

	q := deque{ make([]int, 0, N+7) }
	q.emplace(0)
	vis[0] = true

	for ! q.empty() {
		nd := q.popfront()
		for _, nxt := range []int{ (N+nd-1)%N, right(nd), right(N+nd) } {
			if !vis[nxt] {
				vis[nxt] = true
				dis[nxt] = dis[nd] + 1
				q.emplace(nxt)
			}
		}
	}

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {
		var n int
		fmt.Fscan(r, &n)
		fmt.Fprintf(w, "%d ", dis[n])
	}
	fmt.Fprintln(w, "")

}

package main

import (
	"fmt"
	"math"
)

var step [32769]int64
var MOD int64 = 32768

func initStep() {
	for i := int64(0); i < MOD; i++ {
		step[i] = math.MaxInt
	}
	var queue []int64
	queue = append(queue, MOD)
	ct := 1000000
	for len(queue) > 0 && ct > 0 {
		now := queue[0]
		queue = queue[1:]
		if now%2 == 0 {
			next1 := now / 2
			if step[next1] == math.MaxInt {
				step[next1] = step[now] + 1
				queue = append(queue, next1)
			}
		}
		if (now+MOD)%2 == 0 {
			next2 := (now + MOD) / 2
			if step[next2] == math.MaxInt {
				step[next2] = step[now] + 1
				queue = append(queue, next2)
			}
		}
		if now-1 >= 0 {
			next3 := now - 1
			if step[next3] == math.MaxInt {
				step[next3] = step[now] + 1
				queue = append(queue, next3)
			}
		}

	}
	step[0] = 0
}

func main() {
	initStep()
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])

		fmt.Println(step[a[i]])
	}
}

package main

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

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}
func readInt64(in *bufio.Reader) int64 {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.ParseInt(nStr, 10, 64)
	return n
}
func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}
func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

func main() {
	ip := bufio.NewReader(os.Stdin)
	_ = readInt(ip)
	a := readArrInt(ip)
	for i := range a {
		fuck(a[i])
	}

}

func min(i, j int) int {
	if i > j {
		return j
	}
	return i
}

func fuck(a int) {
	if a == 0 {
		fmt.Print(0, " ")
		return
	}
	res := int(1e9)
	tmp := 0
	for a <= 32768 {
		cnt := 0
		p := a
		for p%2 == 0 {
			cnt++
			p >>= 1
		}

		res = min(res, 15-cnt+tmp)
		tmp += lb(a)
		a += lb(a)
	}

	fmt.Print(res, " ")
}

func lb(x int) int {
	return x & -x
}

package main

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

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

func b1661(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T int
	var x int
	mod := 32768

	dp := make([]int, mod+1)
	st := []int{32768}
	dp[32768] = 0
	for len(st) > 0 {
		ns := []int{}
		for _, v := range st {
			pre := v - 1
			if pre > 0 && dp[pre] == 0 {
				dp[pre] = dp[v] + 1
				ns = append(ns, pre)
			}

			if v%2 == 0 {
				d := v/2
				if dp[d] == 0 {
					dp[d] = dp[v]+1
					ns = append(ns,d)
				}

				div := ((v + mod) / 2) % mod
				if dp[div] == 0 {
					dp[div] = dp[v] + 1
					ns = append(ns, div)
				}
			}
		}
		st = ns
	}
	dp[0] = 0
	//Println(dp[mod/2])
	//Println(dp[mod/4])

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &x)

		Fprintln(out, dp[x])
	}
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"math/bits"
	"os"
)

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

	var n, v int
	for Fscan(in, &n); n > 0; n-- {
		Fscan(in, &v)
		if v == 0 {
			Fprint(out, "0 ")
			continue
		}
		ans := 15
		for i := 0; i < 15; i++ {
			ans = min(ans, i+15-bits.TrailingZeros(uint(v+i)))
		}
		Fprint(out, ans, " ")
	}
}

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

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

package main

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

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

	const mx = 32768
	g := [mx][]int{}
	for w := range g {
		v := (w + 1) % mx
		g[v] = append(g[v], w)
		v = w * 2 % mx
		g[v] = append(g[v], w)
	}
	dis := [mx]int{-1}
	q := []int{0}
	for k := 1; len(q) > 0; k++ {
		tmp := q
		q = nil
		for _, v := range tmp {
			for _, w := range g[v] {
				if dis[w] == 0 {
					dis[w] = k
					q = append(q, w)
				}
			}
		}
	}
	dis[0] = 0

	var n, v int
	for Fscan(in, &n); n > 0; n-- {
		Fscan(in, &v)
		Fprint(out, dis[v], " ")
	}
}

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

package main

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

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
)

func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	defer out.Flush()

	N := 32768
	count := make([]int, N+1)
	for i := 0; i < len(count); i++ {
		count[i] = -1
	}
	count[N] = 0
	count[0] = 0

	stack := make([][]int, 0)
	stack = append(stack, []int{N, 0})
	index := 0
	for index < len(stack) {
		s, l := stack[index][0], stack[index][1]
		index++

		if s > 0 {
			if s%2 == 0 {
				{
					s := s / 2
					if count[s] == -1 {
						count[s] = l + 1
						stack = append(stack, []int{s, l + 1})
					}
				}
				{
					s := (s + N) / 2
					if count[s] == -1 {
						count[s] = l + 1
						stack = append(stack, []int{s, l + 1})
					}
				}
			}
			s = s - 1
			if count[s] == -1 {
				count[s] = l + 1
				stack = append(stack, []int{s, l + 1})
			}
		}

	}

	// fmt.Fprintln(out, count)

	var n int
	fmt.Fscan(in, &n)

	a := make([]int64, n)

	for i := 0; i < len(a); i++ {
		fmt.Fscan(in, &a[i])
	}

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

package main

import (
	"bufio"
	"fmt"
	"os"
	"runtime/debug"
)

/* begin of MyIO */
const eof = 0

type any = interface{}

type MyIO struct {
	in  *os.File
	out *bufio.Writer
	_i  int
	_n  int
	buf []byte
}

func NewIO(in *os.File, out *os.File) *MyIO {
	return &MyIO{
		in,
		bufio.NewWriter(out),
		0, 0, make([]byte, 1<<12),
	}
}

func (myio *MyIO) rc() byte {
	if myio._i == myio._n {
		myio._n, _ = myio.in.Read(myio.buf)
		if myio._n == 0 { // EOF
			return eof
		}
		myio._i = 0
	}
	b := myio.buf[myio._i]
	myio._i++
	return b
}

func (myio *MyIO) ReadInt() (x int) {
	rc := myio.rc
	b := rc()
	neg := false
	for ; '0' > b || b > '9'; b = rc() {
		if b == eof {
			return
		}
		if b == '-' {
			neg = true
		}
	}
	for ; '0' <= b && b <= '9'; b = rc() {
		x = x*10 + int(b&15)
	}
	if neg {
		return -x
	}
	return
}

func (myio *MyIO) ReadInt64() (x int64) {
	rc := myio.rc
	b := rc()
	neg := false

	for ; '0' > b || b > '9'; b = rc() {
		if b == eof {
			return
		}
		if b == '-' {
			neg = true
		}
	}
	for ; '0' <= b && b <= '9'; b = rc() {
		x = x*10 + int64(b&15)
	}
	if neg {
		return -x
	}
	return x
}

func (myio *MyIO) ReadBytes() (s []byte) {
	rc := myio.rc
	b := rc()
	for ; b <= ' '; b = rc() {
	}
	for ; b > ' '; b = rc() {
		s = append(s, b)
	}
	return
}

func (myio *MyIO) ReadStr() (s string) {
	return string(myio.ReadBytes())
}

func (myio *MyIO) Flush() {
	myio.out.Flush()
}

func (myio *MyIO) Printf(format string, a ...any) (n int, err error) {
	return fmt.Fprintf(myio.out, format, a...)
}

func (myio *MyIO) Println(a ...any) (n int, err error) {
	return fmt.Fprintln(myio.out, a...)
}

func (myio *MyIO) Print(a ...any) (n int, err error) {
	return fmt.Fprint(myio.out, a...)
}

var myio *MyIO

func ri() int {
	return myio.ReadInt()
}

func ri64() int64 {
	return myio.ReadInt64()
}

func ria(_n int) []int {
	a := make([]int, _n)
	for i := range a {
		a[i] = ri()
	}
	return a
}

/* End of MyIO */

func getN(v int) int {
	v = v & -v
	t := 0
	for (v & 32767) != 0 {
		v <<= 1
		t++
	}
	return t
}

func sol() {
	z := ri()
	r := 30
	for i := 0; i < 30; i++ {
		t := i + getN(z+i)
		if r > t {
			r = t
		}
	}
	fmt.Print(r, " ")
}

func main() {
	debug.SetGCPercent(-1)
	in, out := os.Stdin, os.Stdout
	myio = NewIO(in, out)
	defer myio.Flush()

	var t = 1
	t = ri()
	for ; t > 0; t-- {
		sol()
	}
}

package main

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

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

func init() {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 4096), 1e9)
}

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

func _int() int {
	s := _string()
	i := 0
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int(r - '0')
	}
	return i
}

func _int64() int64 {
	s := _string()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func _string() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

const C = 32768

func main() {
	defer writer.Flush()
	n := _int()
	for i := 0; i < n; i++ {
		printf("%d ", sol(_int()))
	}
}

func sol(i int) int {
	res := 16
	for add := 0; add <= 15; add++ {
		curr := 1
		for mul := 0; mul <= 15; mul++ {
			if ((i+add)*curr)%C == 0 {
				res = min(res, add+mul)
			}
			curr *= 2
		}
	}
	return res
}

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

package main

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

func solve(a []uint64) []uint64 {
	getPow := func(d uint64) uint64 {
		i := uint64(0)
		for d%2 == 0 && d > 1 {
			d = d >> 1
			i++
		}

		return i
	}

	getMin := func(n uint64) uint64 {
		max := 15 - getPow(n)
		res := max

		for i := uint64(0); i <= max; i++ {
			t := (n + i) % 32768
			r := i
			if t > 0 {
				r += 15 - getPow(t)
			}
			if r < res {
				res = r
			}
		}

		return uint64(res)
	}

	for i, n := range a {
		a[i] = getMin(n % 32768)
	}

	return a
}

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

	var n uint64

	fmt.Scan(&n)
	b := make([]uint64, n)

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range b {
		scanner.Scan()
		b[i] = toInt(scanner.Bytes())
	}

	a := solve(b)
	for _, x := range a {
		fmt.Print(x, " ")
	}
	fmt.Println()
}

package main

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

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	dp := make([]int, 32769)
	dp[0] = 0

	var cal func(i int, visited map[int]bool) int
	cal = func(i int, visited map[int]bool) int {
		if i == 0 || i == 32768 {
			return 0
		}
		if dp[i] > 0 {
			return dp[i]
		}
		if visited[i] {
			return 32768 - i
		}
		visited[i] = true
		a, b := (i*2)%32768, (i+1)%32768
		ans := min(cal(a, visited), cal(b, visited)) + 1
		dp[i] = ans
		return ans
	}
	for ii := 0; ii < t; ii++ {
		m := 0
		fmt.Fscan(in, &m)
		ans := 15
		for i := 0; i <= 15; i++ {
			temp := i
			a := (m + i) % 32768
			for a != 0 {
				a = a * 2
				a %= 32768
				temp++
			}
			//fmt.Println(i, ans)
			if temp < ans {
				ans = temp
			}
		}
		fmt.Fprint(out, ans)
		if ii == t-1 {
			fmt.Fprintln(out)
		} else {
			fmt.Fprint(out, " ")
		}
	}
}

package main

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

/*
1
19
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n int
	scanf("%d\n", &n)

	for i := 0; i < n; i++ {
		var num int
		scanf("%d", &num)

		minCnt := 32768 - num

		for j := 0; j < 16; j++ {
			cnt := j
			rem := num + j
			for rem != 0 {
				rem = 2 * rem % 32768
				cnt++
			}

			minCnt = min(minCnt, cnt)
		}

		fmt.Fprintf(writer, "%d ", minCnt)
	}
}

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

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

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

const maxUint = ^uint(0)

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

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

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

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

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

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

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

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

	return minNumIdx
}

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

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

	return maxNumIdx
}

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

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

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

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

	return true
}

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

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

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

	num = abs(num)

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

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

package main

import (
	"bufio"
	"container/list"
	. "fmt"
	"os"
)

const (
	INF = 3e5 + 10
	MOD = 32768
)

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

	var n int
	Fscan(in, &n)

	dp := make([]int, MOD)
	vis := make([]bool, MOD)

	queue := list.New()

	queue.PushBack(0)
	vis[0] = true

	for queue.Len() > 0 {
		newQueue := list.New()
		for e := queue.Front(); e != nil; e = e.Next() {
			x := e.Value.(int)
			if vis[(x+MOD-1)%MOD] == false {
				dp[(x+MOD-1)%MOD] = dp[x] + 1
				newQueue.PushBack((x + MOD - 1) % MOD)
				vis[(x+MOD-1)%MOD] = true

			}
			if x%2 == 0 && vis[x>>1] == false {
				dp[x>>1] = dp[x] + 1
				newQueue.PushBack(x >> 1)
				vis[x>>1] = true
			}

			if x%2 == 0 && vis[(x+MOD)>>1] == false {
				dp[(x+MOD)>>1] = dp[x] + 1
				newQueue.PushBack((x + MOD) >> 1)
				vis[(x+MOD)>>1] = true
			}
		}
		queue = newQueue
	}

	for i := 0; i < n; i++ {
		var x int
		Fscan(in, &x)
		Fprint(out, dp[x], " ")
	}

}

package main

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

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

const M uint64 = 32768

func A(_r io.Reader, _w io.Writer) {
	in, out := bufio.NewReader(_r), bufio.NewWriterSize(_w, 102400000)
	defer out.Flush()

	f := [32770]uint64{}
	for i := range f {
		f[i] = 1e10
	}
	f[0] = 0
	que := []uint64{32768}
	for len(que) > 0 {
		top := que[0]
		que = que[1:]
		//v+1
		if top != 0 && f[top]+1 < f[top-1] {
			f[top-1] = f[top] + 1
			que = append(que, top-1)
		}
		//v*2
		if k := top / 2; top%2 == 0 && f[top]+1 < f[k] {
			f[k] = f[top] + 1
			que = append(que, k)
		}
		if k := (top + M) / 2; k%2 == 0 && k/2 <= 32768 && f[top]+1 < f[k] {
			f[k] = f[top] + 1
			que = append(que, k)
		}
	}
	var c int
	var n int
	Fscan(in, &c)
	for i := 1; i <= c; i++ {
		Fscan(in, &n)
		Fprintf(out, "%d%s", f[n], " ")
	}
}

package main

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

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

const M uint64 = 32768

func A(_r io.Reader, _w io.Writer) {
	in, out := bufio.NewReader(_r), bufio.NewWriter(_w)
	defer out.Flush()

	f := [32769]uint64{}
	for i := range f {
		f[i] = 1e10
	}
	f[32768] = 0
	que := []uint64{32768}
	for len(que) > 0 {
		top := que[0]
		que = que[1:]
		//v+1
		if top != 0 && f[top]+1 < f[top-1] {
			f[top-1] = f[top] + 1
			que = append(que, top-1)
		}
		//v*2
		if k := top / 2; top%2 == 0 && f[top]+1 < f[k] {
			f[k] = f[top] + 1
			que = append(que, k)
		}
		if k := (top + M) / 2; k%2 == 0 && k/2 <= 32768 && f[top]+1 < f[k] {
			f[k] = f[top] + 1
			que = append(que, k)
		}
	}
	var c int
	var n int
	Fscan(in, &c)
	for i := 1; i <= c; i++ {
		Fscan(in, &n)
		if i == 18833 {
			Println("this", n)
		}
		Fprintf(out, "%d%s", f[n], " ")
	}
}

package main

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

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

const M uint64 = 32768

func A(_r io.Reader, _w io.Writer) {
	in, out := bufio.NewReader(_r), bufio.NewWriter(_w)
	defer out.Flush()

	f := [32769]uint64{}
	for i := range f {
		f[i] = 1e10
	}
	f[32768] = 0
	que := []uint64{32768}
	for len(que) > 0 {
		top := que[0]
		que = que[1:]
		//v+1
		if top != 0 && f[top]+1 < f[top-1] {
			f[top-1] = f[top] + 1
			que = append(que, top-1)
		}
		//v*2
		if k := top / 2; top%2 == 0 && f[top]+1 < f[k] {
			f[k] = f[top] + 1
			que = append(que, k)
		}
		if k := (top + M) / 2; k%2 == 0 && k/2 <= 32768 && f[top]+1 < f[k] {
			f[k] = f[top] + 1
			que = append(que, k)
		}
	}
	var c int
	var n int
	Fscan(in, &c)
	for ; c > 0; c-- {
		Fscan(in, &n)
		Fprintf(out, "%d%s", f[n], " ")
	}
}

package main

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

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

func A(_r io.Reader, _w io.Writer) {
	in, out := bufio.NewReader(_r), bufio.NewWriter(_w)
	defer out.Flush()

	var c int
	Fscan(in, &c)
	for ; c > 0; c-- {
		vis := make(map[uint64]bool)
		var n uint64
		Fscan(in, &n)
		Println(n)
		que := []uint64{n}
		step := 0
		for {
			k := len(que)
			for i := 0; i < k; i++ {
				cur := que[0]
				que = que[1:]
				if cur == 0 {
					Fprint(out, step, " ")
					goto h1
				}
				if vis[cur] {
					continue
				} else {
					vis[cur] = true
				}
				que = append(que, (cur+1)%32768)
				que = append(que, (cur * 2 % 32768))
			}
			step++
		}
	h1:
	}
}

package main

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

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

	var n int
	fmt.Fscan(in, &n)

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

		var c int
		if v%2 != 0 {
			c++
			v++
		}

		var z int
		if v > 0 {
			z = 16 - bits.TrailingZeros(uint(v)) - 1
			if 32768-v < z {
				z = 32768 - v
			}
		}
		if z+c == 0 {
			z = 1
		}
		fmt.Fprintf(out, "%d ", z+c)
	}
	fmt.Fprintln(out)
}

package main

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

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

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

	var n int
	fmt.Fscan(in, &n)

	for i := 0; i < n; i++ {
		var v int64
		fmt.Fscan(in, &v)

		trail := func(n int64) int64 {
			if n <= 0 {
				return 0
			}

			var c int64
			for n%32768 != 0 {
				c++
				n *= 2
			}
			return c
		}

		c := min(32768-v, trail(v), trail(v+1)+1)
		if c == 0 {
			c = 1
		}
		fmt.Fprintf(out, "%d ", c)
	}
	fmt.Fprintln(out)
}

package main

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

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

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

	var n int
	fmt.Fscan(in, &n)

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

		trail := func(n int) int {
			if n <= 0 {
				return 0
			}

			var c int
			for n%32768 != 0 {
				c++
				n *= 2
			}
			return c
		}

		c := min(32768-v, trail(v), trail(v+1)+1)
		if c == 0 {
			c = 1
		}
		fmt.Fprintf(out, "%d ", c)
	}
	fmt.Fprintln(out)
}

package main

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

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

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

	var n int
	fmt.Fscan(in, &n)

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

		trail := func(n int) int {
			if n <= 0 {
				return 0
			}

			var c int
			for n%32768 != 0 {
				c++
				n *= 2
			}
			return c
		}

		c := min(32768-v, trail(v), trail(v+1)+1)
		fmt.Fprintf(out, "%d ", c)
	}
	fmt.Fprintln(out)
}

package main

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

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

	var n int
	fmt.Fscan(in, &n)

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

		t := v
		var c int
		if v%2 != 0 {
			c++
			v++
		}

		for v%32768 != 0 {
			c++
			v *= 2
		}

		if 32768-t < c {
			c = 32768 - t
		}

		fmt.Fprintf(out, "%d ", c)
	}
	fmt.Fprintln(out)
}

package main

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

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

	var n int
	fmt.Fscan(in, &n)

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

		var c int
		if v%2 != 0 {
			c++
			v++
		}

		var z int
		if v > 0 {
			z = 16 - bits.TrailingZeros(uint(v)) - 1
			if 32768-v < z {
				z = 32768 - v
			}
		}
		fmt.Fprintf(out, "%d ", z+c)
	}
	fmt.Fprintln(out)
}

package main

import (
	"fmt"
	"math"
)

var step [32769]int64
var MOD int64 = 32768

func initStep() {
	for i := int64(0); i < MOD; i++ {
		step[i] = math.MaxInt
	}
	var queue []int64
	queue = append(queue, MOD)
	ct := 102768
	for len(queue) > 0 && ct > 0 {
		now := queue[0]
		queue = queue[1:]
		if now%2 == 0 {
			next1 := now / 2
			if step[next1] == math.MaxInt {
				step[next1] = step[now] + 1
				queue = append(queue, next1)
			}
		}
		if (now+MOD)%2 == 0 {
			next2 := (now + MOD) / 2
			if step[next2] == math.MaxInt {
				step[next2] = step[now] + 1
				queue = append(queue, next2)
			}
		}
		if now-1 >= 0 {
			next3 := now - 1
			if step[next3] == math.MaxInt {
				step[next3] = step[now] + 1
				queue = append(queue, next3)
			}
		}

	}

}

func main() {
	initStep()
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])

		fmt.Println(step[a[i]])
	}
}

package main

import (
	"fmt"
	"math"
)

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

var step [32769]int
var MOD int = 32768

func initStep() {
	for i := 0; i < MOD; i++ {
		step[i] = math.MaxInt
	}
	var queue []int
	queue = append(queue, MOD)
	ct := 102768
	for len(queue) > 0 && ct > 0 {
		now := queue[0]
		queue = queue[1:]
		if now%2 == 0 {
			next1 := now / 2
			if step[next1] == math.MaxInt {
				step[next1] = step[now] + 1
				queue = append(queue, next1)
			}
		}
		if (now+MOD)%2 == 0 {
			next2 := (now + MOD) / 2
			if step[next2] == math.MaxInt {
				step[next2] = step[now] + 1
				queue = append(queue, next2)
			}
		}
		if now-1 > 0 {
			next3 := now - 1
			if step[next3] == math.MaxInt {
				step[next3] = step[now] + 1
				queue = append(queue, next3)
			}
		}

	}

}

func main() {
	initStep()
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])

		fmt.Println(step[a[i]])
	}
}

package main

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

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}
func readInt64(in *bufio.Reader) int64 {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.ParseInt(nStr, 10, 64)
	return n
}
func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}
func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

func main() {
	ip := bufio.NewReader(os.Stdin)
	_ = readInt(ip)
	a := readArrInt(ip)
	ans := 0
	for i := range a {
		if a[i]==0{
			fmt.Print(0, " ")
			continue
		}
		ans = 0
		tmp := 0
		if a[i]%2 == 1 {
			ans++
			a[i]++
		}
		p := a[i]
		for p%2 == 0 {
			p >>= 1
			tmp++
		}
		ans += min(15-tmp, 32768-a[i])
		fmt.Print(ans, " ")
	}

}

func min(i, j int) int {
	if i > j {
		return j
	}
	return i
}

package main

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

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

func b1661(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T int
	var x int
	mod := 32768

	dp := make([]int, mod+1)
	st := []int{32768}
	dp[32768] = 0
	for len(st) > 0 {
		ns := []int{}
		for _, v := range st {
			pre := v - 1
			if pre > 0 && dp[pre] == 0 {
				dp[pre] = dp[v] + 1
				ns = append(ns, pre)
			}

			if v%2 == 0 {
				d := v/2
				if dp[d] == 0 {
					dp[d] = dp[v]+1
					ns = append(ns,d)
				}

				div := ((v + mod) / 2) % mod
				if dp[div] == 0 {
					dp[div] = dp[v] + 1
					ns = append(ns, div)
				}
			}
		}
		st = ns
	}
	//Println(dp[mod/2])
	//Println(dp[mod/4])

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &x)

		Fprintln(out, dp[x])
	}
}

package main

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

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
)

func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	defer out.Flush()

	N := 32768
	count := make([]int, N+1)
	for i := 0; i < len(count); i++ {
		count[i] = -1
	}
	count[N] = 0

	stack := make([][]int, 0)
	stack = append(stack, []int{N, 0})
	index := 0
	for index < len(stack) {
		s, l := stack[index][0], stack[index][1]
		index++

		if s > 0 {
			if s%2 == 0 {
				{
					s := s / 2
					if count[s] == -1 {
						count[s] = l + 1
						stack = append(stack, []int{s, l + 1})
					}
				}
				{
					s := (s + N) / 2
					if count[s] == -1 {
						count[s] = l + 1
						stack = append(stack, []int{s, l + 1})
					}
				}
			}
			s = s - 1
			if count[s] == -1 {
				count[s] = l + 1
				stack = append(stack, []int{s, l + 1})
			}
		}

	}

	// fmt.Fprintln(out, count)

	var n int
	fmt.Fscan(in, &n)

	a := make([]int64, n)

	for i := 0; i < len(a); i++ {
		fmt.Fscan(in, &a[i])
	}

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


Alice and Bob play a game. There is a paper strip which is divided into n + 1 cells numbered from left to right starting from 0. There is a chip placed in the n-th cell (the last one).Players take turns, Alice is first. Each player during his or her turn has to move the chip 1, 2 or k cells to the left (so, if the chip is currently in the cell i, the player can move it into cell i - 1, i - 2 or i - k). The chip should not leave the borders of the paper strip: it is impossible, for example, to move it k cells to the left if the current cell has number i < k. The player who can't make a move loses the game.Who wins if both participants play optimally?Alice and Bob would like to play several games, so you should determine the winner in each game.

The first line contains the single integer T (1 ≤ T ≤ 100) — the number of games. Next T lines contain one game per line. All games are independent. Each of the next T lines contains two integers n and k (0 ≤ n ≤ 109, 3 ≤ k ≤ 109) — the length of the strip and the constant denoting the third move, respectively.

For each game, print Alice if Alice wins this game and Bob otherwise.

package main

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

func (io *IO) Solve_() bool {
	n, k := io.Int64(), io.Int64()
	if k%3 != 0 {
		return n%3 != 0
	}
	if n%(k+1) == k {
		return true
	}
	if (n%(k+1))%3 == 0 {
		return false
	}
	return true
}

func (io *IO) Solve() {
	t := io.Int()
	for i := 0; i < t; i++ {
		if io.Solve_() {
			io.Print("Alice\n")
		} else {
			io.Print("Bob\n")
		}
	}
}

func main() {
	NewIO().Solve()
}

type IO struct {
	scanner *bufio.Scanner
	writer  io.Writer
}

func NewIO() *IO {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return &IO{scanner, os.Stdout}
}

func (io *IO) Skip() {
	io.scanner.Scan()
}

func (io *IO) Int32() (n int32) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	for _, v := range buf {
		n = n*10 + int32(v-'0')
	}
	return
}

func (io *IO) Int64() (n int64) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	for _, v := range buf {
		n = n*10 + int64(v-'0')
	}
	return
}

func (io *IO) Int() (n int) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	for _, v := range buf {
		n = n*10 + int(v-'0')
	}
	return
}

func (io *IO) UInt() (n uint) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	for _, v := range buf {
		n = n*10 + uint(v-'0')
	}
	return
}

func (io *IO) Bytes() (s []byte) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	s = make([]byte, len(buf))
	copy(s, buf)
	return
}

func (io *IO) IntArray(n int) (arr []int) {
	arr = make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = io.Int()
	}
	return
}

func (io *IO) UIntArray(n int) (arr []uint) {
	arr = make([]uint, n)
	for i := 0; i < n; i++ {
		arr[i] = io.UInt()
	}
	return
}

func (io *IO) Print(a interface{}) {
	fmt.Fprint(io.writer, a)
}

func (io *IO) Printf(format string, a interface{}) {
	fmt.Fprintf(io.writer, format, a)
}

func (io *IO) setBuffer() {
	io.scanner.Buffer(make([]byte, 4096), 512*1024)
}

package main

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

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

	var t, n, k int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n, &k)
		if k%3 == 0 {
			n %= k + 1
			if n == k {
				Fprintln(out, "Alice")
				continue
			}
		}
		if n%3 != 0 {
			Fprintln(out, "Alice")
		} else {
			Fprintln(out, "Bob")
		}
	}
}

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


Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:  it is up to a passenger to choose a plane to fly on;  if the chosen plane has x (x > 0) empty seats at the given moment, then the ticket for such a plane costs x zlotys (units of Polish currency). The only ticket office of the airport already has a queue of n passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all n passengers buy tickets according to the conditions of this offer?The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to n-th person.

The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 1000) — ai stands for the number of empty seats in the i-th plane before the ticket office starts selling tickets. The numbers in the lines are separated by a space. It is guaranteed that there are at least n empty seats in total.

Print two integers — the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly.

NoteIn the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 2-nd plane, the 3-rd person — to the 3-rd plane, the 4-th person — to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 1-st plane, the 3-rd person — to the 2-nd plane, the 4-th person — to the 2-nd plane.

package main
import (
	"fmt"
)

func main() {
	var a,g,h,j,k,i,mi,in int
	fmt.Scan(&a,&k)
	d:=make([]int,1000)
	f:=make([]int,1000)
	for i=0;i<k;i++ {
		fmt.Scan(&d[i])
		f[i]=d[i]
	}
	for i=0;i<a;i++ {
		mi=10000
		in=-1
		for j=0;j<k;j++ {
			if d[j]<mi && d[j]>0 {
				mi=d[j]
				in=j
			}
		}
		if in==-1 {
			break
		}
		g+=d[in]
		d[in]--
	}
	for i=0;i<a;i++ {
		mi=0
		in=-1
		for j=0;j<k;j++ {
			if f[j]>mi && f[j]>0 {
				mi=f[j]
				in=j
			}
		}
		if in==-1 {
			break
		}
		h+=f[in]
		f[in]--

	}
	fmt.Print(h," ",g)
}

package main

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

func scanInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	x, _ := strconv.Atoi(scanner.Text())
	return x
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	n, m := scanInt(scanner), scanInt(scanner)
	minPlanes, maxPlanes := make([]int, m), make([]int, m)
	for i := 0; i < m; i++ {
		minPlanes[i] = scanInt(scanner)
		maxPlanes[i] = minPlanes[i]
	}
	minCost, maxCost := 0, 0
	nonzero := 0
	for i := 0; i < n; i++ {
		sort.Ints(minPlanes)
		for minPlanes[nonzero] == 0 {
			nonzero++
		}
		minCost += minPlanes[nonzero]
		minPlanes[nonzero]--
		sort.Ints(maxPlanes)
		maxCost += maxPlanes[m-1]
		maxPlanes[m-1]--
	}
	writer.WriteString(fmt.Sprintf("%d %d\n", maxCost, minCost))
}

package main

import "fmt"

func main() {
    var n,m,a int
    var cnt [1001]int
    fmt.Scan(&n,&m)
    for i := 0; i < m; i++ {
        fmt.Scan(&a)
        cnt[a]++
    }
    min, n_min := 0, n
    for i := 1; (i <= 1000) && (n_min > 0); i++ {
        for j := 0; (j < cnt[i]) && (n_min > 0); j++ {
            total := (i*(i+1))/2
            if n_min < i {
                d := i-n_min
                total -= (d*(d+1))/2
            }
            n_min -= i
            min += total
        }
    }
    max, n_max := 0, n
    for i := 1000; (i >= 1) && (n_max > 0); {
        if cnt[i] != 0 {
            max += i
            n_max -= 1
            cnt[i-1]++
            cnt[i]--
        } else {
            i--
        }
    }
    fmt.Println(max,min)
}

package main

import "fmt"

func main() {
    var n,m,a int						// membuat variabel n,m,a dengan jenis int
    var cnt [1001]int					// membuat variabel cnt[1001] dengan jenis int
    fmt.Scan(&n,&m)						// mengambil input
    for i := 0; i < m; i++ {			// looping 1
        fmt.Scan(&a)					// mengambil input kedua
        cnt[a]++						// cnt[a] ditambah terus
    }
    min, n_min := 0, n					// membuat variabel min dan n_min kemudian diisi dengan 0 dan n
    for i := 1; (i <= 1000) && (n_min > 0); i++ {  // looping ke 2
        for j := 0; (j < cnt[i]) && (n_min > 0); j++ {  // looping ke 3
            total := (i*(i+1))/2		// membuat variabel total dan diisi dengan hasil dari (i*(i+1))/2
            if n_min < i {				// if n_min lebih kecil dari i
                d := i-n_min			// maka buat variabel d dan diisi dengan hasil dari i-n_min
                total -= (d*(d+1))/2   // total dikurang (d*(d+1))/2
            }
            n_min -= i				// n_min dikurang i
            min += total			// min ditambah total
        }
    }
    max, n_max := 0, n					// membuat variabel max dan n_max dan diisi dengan 0 dan n
    for i := 1000; (i >= 1) && (n_max > 0); { // looping ke empat
        if cnt[i] != 0 {				// if cnt[i] tidak sama dengan 0
            max += i					// maka max ditambah i
            n_max -= 1					// n_max dikurang 1
            cnt[i-1]++					// cnt [i-1] ditambah terus
            cnt[i]--					// cnt[i] dikurang terus
        } else {						// lainnya
            i--							// i dikurang terus
        }
    }
    fmt.Println(max,min)				// cetak hasil max dan min
}

// 218B-mic
package main

import (
    "fmt"
)

func main() {
    var n, m, r1, r2 int
    var a1, a2 [1005]int
    fmt.Scan(&n, &m)
    for i := 0; i < m; i++ {
        fmt.Scan(&a1[i])
        a2[i] = a1[i]
    }

    for i := 0; i < n; i++ {
        max := -1
        min := 1005
        mi_ind := -1
        ma_ind := -1
        for j := 0; j < m; j++ {
            if a1[j] > max {
                max = a1[j]
                ma_ind = j
            }
            if a2[j] < min && a2[j] > 0 {
                min = a2[j]
                mi_ind = j
            }
        }
        r1 += max
        r2 += min

        a1[ma_ind]--
        a2[mi_ind]--
    }
    fmt.Print(r1)
    fmt.Print(" ")
    fmt.Print(r2)
    fmt.Println()
}

package main

import "fmt"

func main() {
    var n,m,a int
    var cnt [1001]int
    fmt.Scan(&n,&m)
    for i := 0; i < m; i++ {
        fmt.Scan(&a)
        cnt[a]++
    }
    min, n_min := 0, n
    for i := 1; (i <= 1000) && (n_min > 0); i++ {
        for j := 0; j < cnt[i]; j++ {
            total := (i*(i+1))/2
            if n_min < i {
                d := i-n_min
                total -= (d*(d+1))/2
            }
            n_min -= i
            min += total
        }
    }
    max, n_max := 0, n
    for i := 1000; (i >= 1) && (n_max > 0); {
        if cnt[i] != 0 {
            max += i
            n_max -= 1
            cnt[i-1]++
            cnt[i]--
        } else {
            i--
        }
    }
    fmt.Println(max,min)
}


Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7).

The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1.  It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation.

Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7).

NoteFor the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
	scanner.Scan()
	x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return x
}
func getI() int {
	return int(getI64())
}
func getF() float64 {
	scanner.Scan()
	x, _ := strconv.ParseFloat(scanner.Text(), 64)
	return x
}
func getS() string {
	scanner.Scan()
	return scanner.Text()
}

const MOD = int64(1000000007)
const MAXN = 2000 + 10

func main(){

	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	n := getI()

	var sol int64
	var a [MAXN]int
	var cant [MAXN]bool
	for i := 1 ; i <= n ; i ++ {

		a[i] = getI()
	}
	wang := 0
	for i := 1 ; i <= n ; i ++{

		if a[i] != -1 {
			cant[a[i]] = true
			cant[i] = true
		}else{
			wang ++
		}

		if a[i] == i {
			fmt.Println(0)
			return
		}

	}

	tmp := 0
	for i := 1 ; i <= n ; i ++ {
		if !cant[i] {
			tmp ++
		}
	}

	var C [MAXN][MAXN]int64
	C[0][0] = int64(1)
	for i := 1 ; i < MAXN ; i ++ {
	//	fmt.Println("-----",i)
		for j := 0 ; j <= i ; j ++ {
		//	fmt.Println("!!",j)
			if j == 0 || j == i {
				C[i][j] = int64(1)
			} else {
				C[i][j] = (C[i-1][j-1] + C[i-1][j] )%MOD
			}
		}
	}

	var fac [MAXN]int64

	fac[0] = int64(1)

	for i := 1 ; i < MAXN ; i ++{
		fac[i] = fac[i-1]* int64(i)
		fac[i] %= MOD
	}

	for i := 0 ; i <= tmp ; i ++{
		if i%2 == 0 {
			sol += C[tmp][i] * fac[wang-i]
		} else {
			sol -= C[tmp][i] * fac[wang-i]
		}
		sol %= MOD

	}
	sol = ( sol+MOD ) %MOD

	fmt.Println(sol)
}


Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?

The first input line contains integer n (1 ≤ n ≤ 105) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.

Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n := getI()
  xs := make([]int, n)
  total := 0
  for i := range xs {
    xs[i] = getI()
    total += xs[i]
  }
  if total % 3 != 0 {
    writer.WriteString("0\n")
    return
  }
  third := total / 3
  suffix := make([]int64, n)
  sum, count := 0, int64(0)
  for i := n-1; i >= 0; i-- {
    sum += xs[i]
    if sum == third {
      count++
    }
    suffix[i] = count
  }
  result := int64(0)
  sum, count = 0, 0
  for i := 0; i < n-2; i++ {
    sum += xs[i]
    if sum == third {
      count++
      result += suffix[i+2]
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n := getI()
  xs := make([]int, n)
  total := 0
  for i := range xs {
    xs[i] = getI()
    total += xs[i]
  }
  if total % 3 != 0 {
    writer.WriteString("0\n")
    return
  }
  third := total / 3
  suffix := make([]int64, n)
  sum, count := 0, int64(0)
  for i := n-1; i >= 0; i-- {
    sum += xs[i]
    if sum == third {
      count++
      writer.WriteString(fmt.Sprintf("suffix at i = %d\n", i))
    }
    suffix[i] = count
  }
  result := int64(0)
  sum, count = 0, 0
  for i := 0; i < n-2; i++ {
    sum += xs[i]
    if sum == third {
      count++
      result += suffix[i+2]
      writer.WriteString(fmt.Sprintf("prefix at i = %d\n", i))
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n := getI()
  xs := make([]int, n)
  total := 0
  for i := range xs {
    xs[i] = getI()
    total += xs[i]
  }
  if total % 3 != 0 {
    writer.WriteString("0\n")
    return
  }
  third := total / 3
  suffix := make([]int64, n)
  sum, count := 0, int64(0)
  for i := n-1; i >= 0; i-- {
    sum += xs[i]
    if sum == third {
      count++
    }
    suffix[i] = count
  }
  result := int64(0)
  sum, count = 0, 0
  for i := 0; i < n-2; i++ {
    sum += xs[i]
    if sum == third {
      count++
      result += count*suffix[i+2]
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n := getI()
  xs := make([]int, n)
  total := 0
  for i := range xs {
    xs[i] = getI()
    total += xs[i]
  }
  if total % 3 != 0 {
    writer.WriteString("0\n")
    return
  }
  third := total / 3
  suffix := make([]int64, n)
  sum, count := 0, int64(0)
  for i := n-1; i >= 0; i-- {
    sum += xs[i]
    if sum == third {
      count++
    }
    suffix[i] = count
  }
  result := int64(0)
  sum, count = 0, 0
  for i := 0; i < n-1; i++ {
    sum += xs[i]
    if sum == third {
      count++
      result += count*suffix[i+1]
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}


The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.

The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.

In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.

package main

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

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

	var n, v, w int
	Fscan(in, &n)
	g := make([]map[int]bool, n)
	for i := range g {
		g[i] = map[int]bool{}
	}
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		g[v-1][w-1] = true
		g[w-1][v-1] = false
	}
	inv := make([]int, n)
	var f func(v, fa int)
	f = func(v, fa int) {
		for w, b := range g[v] {
			if w != fa {
				if !b {
					inv[0]++
				}
				f(w, v)
			}
		}
	}
	f(0, -1)
	f = func(v, fa int) {
		if g[v][fa] {
			inv[v] = inv[fa] - 1
		} else {
			inv[v] = inv[fa] + 1
		}
		for w := range g[v] {
			if w != fa {
				f(w, v)
			}
		}
	}
	for v := range g[0] {
		f(v, 0)
	}
	min := n
	for _, v := range inv {
		if v < min {
			min = v
		}
	}
	Fprintln(out, min)
	for i, v := range inv {
		if v == min {
			Fprint(out, i+1, " ")
		}
	}
}

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

package main

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

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

	var n, v, w int
	Fscan(in, &n)
	type edge struct{ to, ord int }
	g := make([][]edge, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], edge{w, 1})
		g[w] = append(g[w], edge{v, -1})
	}
	inv := make([]int, n)
	var f func(v, fa int)
	f = func(v, fa int) {
		for _, e := range g[v] {
			if w := e.to; w != fa {
				if e.ord == -1 {
					inv[0]++
				}
				f(w, v)
			}
		}
	}
	f(0, -1)
	f = func(v, fa int) {
		for _, e := range g[v] {
			if w := e.to; w != fa {
				inv[w] = inv[v] + e.ord
				f(w, v)
			}
		}
	}
	f(0, -1)
	min := n
	for _, v := range inv {
		if v < min {
			min = v
		}
	}
	Fprintln(out, min)
	for i, v := range inv {
		if v == min {
			Fprint(out, i+1, " ")
		}
	}
}

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

package main

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

type EdgeEle struct {
   to int
   flag bool
}
var edge[200010][] EdgeEle
var son[200010][] EdgeEle
var visit[200010] bool
var din[200010] int
var dout[200010] int
var ansCost int
var ansList[] int
var ansEach[200010] int

func DfsFirst(nowPoint int,){
   visit[nowPoint] = true
   for _, toPoint := range edge[nowPoint]{
      if !visit[toPoint.to]{
         son[nowPoint] = append(son[nowPoint], toPoint)
         DfsFirst(toPoint.to)
         din[nowPoint] += din[toPoint.to]
         dout[nowPoint] += dout[toPoint.to]
         if toPoint.flag{
            din[nowPoint]++
         }else{
            dout[nowPoint]++
         }
      }
   }
}

func DfsSecond(nowPoint , parentPoint int, flag bool){
   //难道改的只有一条边？

   ansTmp := ansEach[parentPoint]
   if flag{
      ansTmp--
   }else{
      ansTmp++
   }
   //fmt.Println(nowPoint, ansTmp)
   ansEach[nowPoint] = ansTmp
   if ansTmp == ansCost{
      ansList = append(ansList, nowPoint)
   }else if ansTmp < ansCost{
      ansList = ansList[0:0]
      ansCost = ansTmp
      ansList = append(ansList, nowPoint)
   }
   for _, toPoint := range son[nowPoint]{
      DfsSecond(toPoint.to, nowPoint, toPoint.flag)
   }
}

func main(){
   in := bufio.NewReader(os.Stdin)
   var n int
   fmt.Fscan(in, &n)
   for i := 1; i < n; i++{
      var p, q int
      fmt.Fscan(in, &p, &q)
      edge[p] = append(edge[p], EdgeEle{q, false})
      edge[q] = append(edge[q], EdgeEle{p, true})
   }
   DfsFirst(1)
   for i := 1; i <= n; i++{
      //fmt.Println("du", din[i], dout[i])
   }
   ansCost = din[1]
   ansList = append(ansList, 1)
   ansEach[1] = din[1]
   for _, toPoint := range edge[1]{
      DfsSecond(toPoint.to, 1, toPoint.flag)
   }
   fmt.Println(ansCost)
   sort.Ints(ansList)
   fmt.Printf("%d", ansList[0])
   for i := 1; i < len(ansList); i++{
      fmt.Printf(" %d", ansList[i])
   }
   fmt.Println()
}

package main

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

const Inf = int(1e9)

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

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

	edges := make(map[int64]bool)
	g := make(map[int][]int)
	for i := 0; i < n-1; i++ {
		var u, v int
		fmt.Fscanf(r, "%d %d\n", &u, &v)
		g[u] = append(g[u], v)
		g[v] = append(g[v], u)
		edges[Hash(u, v)] = true
	}

	initCost := dfs1(1, -1, g, edges)
	costs := dfs2(1, -1, g, edges, initCost)

	best := Inf
	var vs []int
	for u := 1; u <= n; u++ {
		cost, ok := costs[u]
		if !ok {
			panic("Impossible")
		}
		if best > cost {
			best = cost
			vs = []int{u}
		} else if best == cost {
			vs = append(vs, u)
		}
	}

	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	fmt.Fprintf(w, "%d\n", best)
	for _, v := range vs {
		fmt.Fprintf(w, "%d ", v)
	}
	fmt.Fprintf(w, "\n")
}

func Hash(u, v int) int64 {
	return int64(u)*int64(3e5) + int64(v)
}

func dfs1(r, p int, g map[int][]int, edges map[int64]bool) int {
	ret := 0
	for _, v := range g[r] {
		if v == p {
			continue
		}
		ret += dfs1(v, r, g, edges) + (1 - hasEdge(r, v, edges))
	}
	return ret
}

func dfs2(r, p int, g map[int][]int, edges map[int64]bool, pCost int) map[int]int {
	curCost := pCost
	if p != -1 {
		curCost += 2*hasEdge(p, r, edges) - 1
	}

	mp := map[int]int{r: curCost}
	for _, v := range g[r] {
		if v == p {
			continue
		}
		m := dfs2(v, r, g, edges, curCost)
		mp = merge(mp, m)
	}
	mp[r] = curCost

	return mp
}

func merge(m1, m2 map[int]int) map[int]int {
	if len(m1) < len(m2) {
		return merge(m2, m1)
	}
	for k, v := range m2 {
		m1[k] = v
	}
	return m1
}

func hasEdge(from, to int, edges map[int64]bool) int {
	if edges[Hash(from, to)] {
		return 1
	}
	return 0
}


Roma works in a company that sells TVs. Now he has to prepare a report for the last year.Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.The operation of changing a number's sign is the operation of multiplying this number by -1.Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.

The first line contains two integers n and k (1 ≤ n, k ≤ 105), showing, how many numbers are in the sequence and how many swaps are to be made. The second line contains a non-decreasing sequence, consisting of n integers ai (|ai| ≤ 104). The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.

In the single line print the answer to the problem — the maximum total income that we can obtain after exactly k changes.

NoteIn the first sample we can get sequence [1, 1, 1], thus the total income equals 3.In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.

package main
import (
	"fmt"
	"bufio"
	"os"
	"strconv"
	//"sort"
)
func abs(a int) int{
	if a<0 {
		a*=(-1)
	}
	return a
}

func main() {
	var n,k,a,b int
	sum:=0
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&n,&k)
	b=10001
 	for i:=0;i<n;i++ {
 	        input.Scan()
 	        aa,_:=strconv.Atoi(input.Text())
 	        a=aa
 	        if b>abs(a) {
 	        	b=abs(a)
 	        }
 	        if a<0 && k>0 {
 	        	k--
 	        	sum+=-a
 	        } else {
 	        	sum+=a
 	        }
 	}
 	if k%2 !=0 {
 		sum-=b*2
 	}
 	fmt.Println(sum)
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	k, _ := strconv.Atoi(scanner.Text())
	a := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		a[i], _ = strconv.Atoi(scanner.Text())
		if (a[i] < 0 && k != 0) {
			a[i] *= -1
			k--
		}
	}
	if (k%2 == 1) {
		sort.Ints(a)
		a[0] *= -1
	}
	sum := 0
	for i := 0; i < n; i++ {
		sum += a[i]
	}
	writer.WriteString(strconv.Itoa(sum))
	writer.WriteString("\n")
	writer.Flush()
}

package main

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

func Income(a []int, k int) {
	n := len(a)
	sum := 0
	if k < n && a[k-1] < 0 {
		for i := 0; i < k; i++ {
			a[i] *= -1
		}
	} else {
		changes := 0
		for i := 0; i < k && i < n; i++ {
			if a[i] < 0 {
				a[i] *= -1
				changes++
			} else {
				break
			}
		}
		sort.IntSlice(a).Sort()
		k = k - changes
		if k%2 != 0 {
			a[0] *= -1
		}
	}
	for i := 0; i < n; i++ {
		sum += a[i]
	}
	fmt.Println(sum)
}

func main() {
	var n, k int
	r := bufio.NewReader(os.Stdin)
	fmt.Scanln(&n, &k)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(r, &a[i])
	}
	Income(a, k)
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)

    ScanInts := func(a... *int) {
        for i := 0; i < len(a); i++ {
            scanner.Scan()
            *(a[i]), _ = strconv.Atoi(scanner.Text())
        }
    }

    var n,k,a int
    ScanInts(&n,&k)
    sum, min := 0, 1000000000
    for i := 0; i < n; i++ {
        ScanInts(&a)
        if (a < 0) && (k > 0) {
            a *= -1
            k--
        }
        if min > a { min = a }
        sum += a
    }
    if k%2 == 1 { sum -= (2*min) }
    fmt.Println(sum)
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)

    ScanInts := func(a... *int) {
        for i := 0; i < len(a); i++ {
            scanner.Scan()
            *(a[i]), _ = strconv.Atoi(scanner.Text())
        }
    }

    var n,k,a int
    ScanInts(&n,&k)
    sum, min := 0, 1000000000
    for i := 0; i < n; i++ {
        ScanInts(&a)
        if (a < 0) && (k > 0) {
            a *= -1
            k--
        }
        if min > a { min = a }
        sum += a
    }
    if (k > 0) {
        if k%2 == 1 { sum -= (2*min) }
    }
    fmt.Println(sum)
}

package main

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

func solve(arr []int, k int, negativeCount int, total int, min int) int {
	id := 0

	for negativeCount > 0 && k > 0 {
		total += arr[id] * -2
		id++
		negativeCount--
		k--
	}

	if k%2 != 0 {
		total -= 2 * min
	}

	return total
}

func findMin(n1 int, n2 int) int {
	if n1 < n2 {
		return n1
	}

	return n2
}

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

	return n
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, k, total, negativeCount int
	fmt.Fscanf(r, "%d %d\n", &n, &k)
	min := int(1e9 + 7)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscanf(r, "%d", &arr[i])
		total += arr[i]
		min = findMin(min, abs(arr[i]))
		if arr[i] < 0 {
			negativeCount++
		}
	}

	fmt.Fprintf(os.Stdout, "%d\n", solve(arr, k, negativeCount, total, min))
}

package main

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

func solve(arr []int, k int, negativeCount int, min int) int {
	total, id := 0, 0
	sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] })

	for negativeCount > 0 && k > 0 {
		arr[id] *= -1
		id++
		negativeCount--
		k--
	}

	if k%2 != 0 {
		total -= 2* min
	}

	for i := range arr {
		total += arr[i]
	}

	return total
}

func findMin(n1 int, n2 int) int {
	if n1 < n2 {
		return n1
	}

	return n2
}

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

	return n
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, k, negativeCount int
	fmt.Fscanf(r, "%d %d\n", &n, &k)
	min := int(1e9 + 7)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscanf(r, "%d", &arr[i])
		min = findMin(min, abs(arr[i]))
		if arr[i] < 0 {
			negativeCount++
		}
	}

	fmt.Fprintf(os.Stdout, "%d\n", solve(arr, k, negativeCount, min))
}

package main

import (
    "fmt"
    "math"
)

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

    a := make([]int, n);
    var min float64 = 1e6;
    minInd := -1;

    for i := 0; i < n; i++ {
        d := 0;
        fmt.Scanf("%d", &d);
        a[i] = d;

        abs := math.Abs(float64(d));
        if abs < min {
            minInd = i;
            min = abs;
        }
    }

    for i, v := range(a) {
        if (v < 0) {
            a[i] = -v;
            k -= 1;
            if (k == 0) {
                break;
            }
        }
    }

    if k > 0 {
        for ; k > 0; k-- {
            a[minInd] *= -1;
        }
    }

    sum := 0;
    for _, v := range(a) {
        if k > 0 {
            v *= -1;
            k -= 1;
        }
        sum += v;
    }
    fmt.Printf("%d\n", sum);
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, k int
	fmt.Scanf("%d%d", &n, &k)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &a[i])
		if (a[i] < 0 && k != 0) {
			a[i] *= -1
			k--
		}
	}
	if (k%2 == 1) {
		sort.Ints(a)
		a[0] *= -1
	}
	sum := 0
	for i := 0; i < n; i++ {
		sum += a[i]
	}
	fmt.Printf("n = %d, sum = %d\n", n, sum)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, k int
	fmt.Scanf("%d%d", &n, &k)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &a[i])
		if (a[i] < 0 && k != 0) {
			a[i] *= -1
			k--
		}
	}
	if (k%2 == 1) {
		sort.Ints(a)
		a[0] *= -1
	}
	sum := 0
	for i := 0; i < n; i++ {
		sum += a[i]
	}
	fmt.Printf("%d\n", sum)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, k int
	fmt.Scanf("%d%d", &n, &k)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &a[i])
		if (a[i] < 0 && k != 0) {
			a[i] *= -1
			k--
		}
	}
	if (k%2 == 1) {
		sort.Ints(a)
		a[0] *= -1
	}
	sum := 0
	for i := 0; i < n; i++ {
		sum += a[i]
		fmt.Printf("%d ", a[i])
	}
	fmt.Printf("; n = %d, sum = %d\n", n, sum)
}

package main

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

func Income(a []int, k int) {
	n := len(a)
	sum := 0
	remain := 0
	if k < n && a[k-1] < 0 {
		i := 0
		for ; i < k; i++ {
			a[i] *= -1
			sum += a[i]
		}
		remain = i
	} else {
		i := 0
		for ; i < k && i < n; i++ {
			if a[i] < 0 {
				a[i] *= -1
				sum += a[i]
			} else {
				if (k-i)%2 != 0 {
					a[i] *= -1
				}
				break
			}
		}

		remain = i
	}
	for i := remain; i < n; i++ {
		sum += a[i]
	}
	fmt.Println(sum)
}

func main() {
	var n, k int
	r := bufio.NewReader(os.Stdin)
	fmt.Scanln(&n, &k)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(r, &a[i])
	}
	Income(a, k)
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)

    ScanInts := func(a... *int) {
        for i := 0; i < len(a); i++ {
            scanner.Scan()
            *(a[i]), _ = strconv.Atoi(scanner.Text())
        }
    }

    var n,k,a int
    ScanInts(&n,&k)
    sum := 0
    for i := 0; i < n; i++ {
        ScanInts(&a)
        if i < k { a *= -1 }
        sum += a
    }
    fmt.Println(sum)
}

//https://codeforces.com/problemset/problem/262/B
//http://bigocoder.com/courses/ORANGE03/ORANGE03_LEC05/ORANGE_L05P02/statement
package main

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

func solve(arr []int, k int, negativeCount int, min int) int {
	total, id := 0, 0
	sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] })

	for negativeCount > 0 && k > 0 {
		arr[id] *= -1
		id++
		negativeCount--
		k--
	}

	if k%2 != 0 {
		total -= 2
	}

	for i := range arr {
		total += arr[i]
	}

	return total
}

func findMin(n1 int, n2 int) int {
	if n1 < n2 {
		return n1
	}

	return n2
}

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

	return n
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, k, negativeCount int
	fmt.Fscanf(r, "%d %d\n", &n, &k)
	min := int(1e9 + 7)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscanf(r, "%d", &arr[i])
		if arr[i] <= 0 {
			negativeCount++
			min = findMin(min, abs(arr[i]))
		}
	}

	fmt.Fprintf(os.Stdout, "%d\n", solve(arr, k, negativeCount, min))
}

package main

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

func solve(arr []int, k int, negativeCount int) int {
	total, id := 0, 0
	nC := negativeCount
	sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] })

	for nC > 0 && k > 0 {
		arr[id] *= -1
		id++
		nC--
		k--
	}

	if k > 0 && k%2 != 0 {
		if negativeCount > 0 {
			arr[negativeCount-1] *= -1
		} else {
			arr[0] *= -1
		}
	}

	for i := range arr {
		total += arr[i]
	}

	return total
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, k, negativeCount int
	fmt.Fscanf(r, "%d %d\n", &n, &k)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscanf(r, "%d", &arr[i])
		if arr[i] < 0 {
			negativeCount++
		}
	}

	fmt.Fprintf(os.Stdout, "%d\n", solve(arr, k, negativeCount))
}

package main

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

func solve(arr []int, k int, negativeCount int) int {
	total, id := 0, 0
	nC := negativeCount
	sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] })

	for nC > 0 && k > 0 {
		arr[id] *= -1
		id++
		nC--
		k--
	}

	if k > 0 && k%2 != 0 {
		if negativeCount > 0 {
			arr[negativeCount-1] *= -1
		} else {
			arr[0] *= -1
		}
	}

	for i := range arr {
		total += arr[i]
	}

	return total
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, k, negativeCount int
	fmt.Fscanf(r, "%d %d\n", &n, &k)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscanf(r, "%d", &arr[i])
		if arr[i] <= 0 {
			negativeCount++
		}
	}

	fmt.Fprintf(os.Stdout, "%d\n", solve(arr, k, negativeCount))
}

//https://codeforces.com/problemset/problem/262/B
//http://bigocoder.com/courses/ORANGE03/ORANGE03_LEC05/ORANGE_L05P02/statement
package main

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

func solve(arr []int, k int, negativeCount int) int {
	total, id := 0, 0
	sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] })

	if negativeCount > 0 {
		for negativeCount > 0 && k > 0 {
			arr[id] *= -1
			id++
			negativeCount--
			k--
		}
	}

	if k > 0 && k%2 != 0 {
		arr[0] *= -1
	}

	for i := range arr {
		total += arr[i]
	}

	return total
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, k, negativeCount int
	fmt.Fscanf(r, "%d %d\n", &n, &k)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscanf(r, "%d", &arr[i])
		if arr[i] < 0 {
			negativeCount++
		}
	}

	fmt.Fprintf(os.Stdout, "%d\n", solve(arr, k, negativeCount))
}

//https://codeforces.com/problemset/problem/262/B
//http://bigocoder.com/courses/ORANGE03/ORANGE03_LEC05/ORANGE_L05P02/statement
package main

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

func solve(arr []int, k int, negativeCount int, min int) int {
	total, id := 0, 0
	sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] })

	for negativeCount > 0 && k > 0 {
		arr[id] *= -1
		id++
		negativeCount--
		k--
	}

	if k%2 != 0 {
		total -= 2
	}

	for i := range arr {
		total += arr[i]
	}

	return total
}

func findMin(n1 int, n2 int) int {
	if n1 < n2 {
		return n1
	}

	return n2
}

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

	return n
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, k, negativeCount int
	fmt.Fscanf(r, "%d %d\n", &n, &k)
	min := int(1e9 + 7)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscanf(r, "%d", &arr[i])
		min = findMin(min, abs(arr[i]))
		if arr[i] < 0 {
			negativeCount++
		}
	}

	fmt.Fprintf(os.Stdout, "%d\n", solve(arr, k, negativeCount, min))
}

//https://codeforces.com/problemset/problem/262/B
//http://bigocoder.com/courses/ORANGE03/ORANGE03_LEC05/ORANGE_L05P02/statement
package main

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

func solve(arr []int, k int) int {
	total := 0
	sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] })

	for i := 0; i < k; i++ {
		if arr[i] > 0 {
			break
		}
		arr[i] *= -1
	}

	for i := range arr {
		total += arr[i]
	}

	return total
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, k int
	fmt.Fscanf(r, "%d %d\n", &n, &k)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscanf(r, "%d", &arr[i])
	}

	fmt.Fprintf(os.Stdout, "%d\n", solve(arr, k))
}

//https://codeforces.com/problemset/problem/262/B
//http://bigocoder.com/courses/ORANGE03/ORANGE03_LEC05/ORANGE_L05P02/statement
package main

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

func solve(arr []int, k int) int {
	total := 0
	sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] })

	if k%2 != 0 {
		arr[0] *= -1
	}

	for i := range arr {
		total += arr[i]
	}

	return total
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, k int
	fmt.Fscanf(r, "%d %d\n", &n, &k)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscanf(r, "%d", &arr[i])
	}

	fmt.Fprintf(os.Stdout, "%d\n", solve(arr, k))
}

package main

import (
    "fmt"
)

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

    a := make([]int, n);
    for i := 0; i < n; i++ {
        d := 0;
        fmt.Scanf("%d", &d);
        a[i] = d;
    }

    sum := 0;
    for _, v := range(a) {
        if k > 0 {
            v *= -1;
            k -= 1;
        }
        sum += v;
    }
    fmt.Printf("%d\n", sum);
}

package main

import (
    "fmt"
)

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

    a := make([]int, n);
    for i := 0; i < n; i++ {
        fmt.Scanf("%d", &a[i]);
    }

    sum := 0;
    for i := 0; i < n; i++ {
        if (k > 0) && (a[i] < 0) {
            a[i] *= -1;
            k -= 1;
        }
        sum += a[i];
    }
    fmt.Printf("%d\n", sum);
}

package main

import (
    "fmt"
)

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

    a := make([]int, n);
    for i := 0; i < n; i++ {
        fmt.Scanf("%d", &a[i]);
    }

    sum := 0;
    for _, v := range(a) {
        if k > 0 {
            v *= -1;
            k -= 1;
        }
        sum += v;
    }
    fmt.Printf("%d\n", sum);
}

package main

import (
    "fmt"
    "math"
)

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

    a := make([]int, n);
    var min float64 = 1e6;
    minInd := -1;

    for i := 0; i < n; i++ {
        d := 0;
        fmt.Scanf("%d", &d);
        a[i] = d;
        abs := math.Abs(float64(d));
        if abs < min {
            minInd = i;
            min = abs;
        }
    }

    for i, v := range(a) {
        if (v < 0) {
            a[i] = -v;
            k -= 1;
            if (k == 0) {
                break;
            }
        }
    }

    if k > 0 {
        for ; k >= 0; k-- {
            a[minInd] *= -1;
        }
    }

    sum := 0;
    for _, v := range(a) {
        if k > 0 {
            v *= -1;
            k -= 1;
        }
        sum += v;
    }
    fmt.Printf("%d\n", sum);
}

package main

import (
    "fmt"
    "math"
)

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

    a := make([]int, n);
    var min float64 = 1e6;
    minInd := -1;

    for i := 0; i < n; i++ {
        d := 0;
        fmt.Scanf("%d", &d);
        a[i] = d;

        abs := math.Abs(float64(d));
        if abs < min {
            minInd = i;
            min = abs;
        }
    }

    for i, v := range(a) {
        if (v < 0) {
            a[i] = -v;
            k -= 1;
            if (k == 0) {
                break;
            }
        }
    }

    if k >= 0 {
        for ; k >= 0; k-- {
            a[minInd] *= -1;
        }
    }

    sum := 0;
    for _, v := range(a) {
        if k > 0 {
            v *= -1;
            k -= 1;
        }
        sum += v;
    }
    fmt.Printf("%d\n", sum);
}

package main

import (
    "fmt"
)

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

    a := make([]int, n);
    for i := 0; i < n; i++ {
        fmt.Scanf("%d", &a[i]);
    }

    sum := 0;
    for i := n - 1; i >= 0; i-- {
        if (k > 0) && (a[i] < 0) {
            a[i] *= -1;
            k -= 1;
        }
        sum += a[i];
    }
    fmt.Printf("%d\n", sum);
}


A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and "(()" are not.We can see that each opening bracket in RBS is paired with some closing bracket, and, using this fact, we can define nesting depth of the RBS as maximum number of bracket pairs, such that the $$$2$$$-nd pair lies inside the $$$1$$$-st one, the $$$3$$$-rd one — inside the $$$2$$$-nd one and so on. For example, nesting depth of "" is $$$0$$$, "()()()" is $$$1$$$ and "()((())())" is $$$3$$$.Now, you are given RBS $$$s$$$ of even length $$$n$$$. You should color each bracket of $$$s$$$ into one of two colors: red or blue. Bracket sequence $$$r$$$, consisting only of red brackets, should be RBS, and bracket sequence, consisting only of blue brackets $$$b$$$, should be RBS. Any of them can be empty. You are not allowed to reorder characters in $$$s$$$, $$$r$$$ or $$$b$$$. No brackets can be left uncolored.Among all possible variants you should choose one that minimizes maximum of $$$r$$$'s and $$$b$$$'s nesting depth. If there are multiple solutions you can print any of them.

The first line contains an even integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of RBS $$$s$$$. The second line contains regular bracket sequence $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{$$$"(", ")"$$$\}$$$).

Print single string $$$t$$$ of length $$$n$$$ consisting of "0"-s and "1"-s. If $$$t_i$$$ is equal to 0 then character $$$s_i$$$ belongs to RBS $$$r$$$, otherwise $$$s_i$$$ belongs to $$$b$$$.

NoteIn the first example one of optimal solutions is $$$s = $$$ "$$$\color{blue}{()}$$$". $$$r$$$ is empty and $$$b = $$$ "$$$()$$$". The answer is $$$\max(0, 1) = 1$$$.In the second example it's optimal to make $$$s = $$$ "$$$\color{red}{(}\color{blue}{(}\color{red}{)}\color{blue}{)}$$$". $$$r = b = $$$ "$$$()$$$" and the answer is $$$1$$$.In the third example we can make $$$s = $$$ "$$$\color{red}{(}\color{blue}{((}\color{red}{)()}\color{blue}{)())}$$$". $$$r = $$$ "$$$()()$$$" and $$$b = $$$ "$$$(()())$$$" and the answer is $$$2$$$.

package main

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

func solve(j Jam) {
	_, s := j.Int(), j.Str()
	depth := -1
	for _, r := range []rune(s) {
		if r == '(' {
			depth += 1
		}
		j.P("%d", depth%2)
		if r == ')' {
			depth -= 1
		}
	}
	j.P("\n")
}

func main() {
	jam, closeFunc := JamNew()
	defer closeFunc()
	solve(jam)
}

type Jam interface {
	Scanner() *bufio.Scanner
	Writer() *bufio.Writer
	Close()

	Str() string
	Int() int64
	Float() float64

	P(format string, values ...interface{})
	PF(format string, values ...interface{})
}

func JamNew() (Jam, func()) {
	if len(os.Args) > 1 {
		panic("running with input file path is not supported")
	}

	var scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)

	var writer = bufio.NewWriter(os.Stdout)
	jam := &jam{scanner, writer}
	return jam, jam.Close
}

type jam struct {
	sc *bufio.Scanner
	wr *bufio.Writer
}

func (j *jam) Close() {
	if err := j.wr.Flush(); err != nil {
		panic(err)
	}
}

func (j *jam) Scanner() *bufio.Scanner {
	return j.sc
}

func (j *jam) Writer() *bufio.Writer {
	return j.wr
}

func (j *jam) Str() string {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	return j.sc.Text()
}

func (j *jam) Int() int64 {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	res, err := strconv.ParseInt(j.sc.Text(), 10, 64)
	if err != nil {
		panic(err)
	}

	return res
}

func (j *jam) Float() float64 {
	j.sc.Scan()
	res, err := strconv.ParseFloat(j.sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

func (j *jam) P(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
}

func (j *jam) PF(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
	if err = j.wr.Flush(); err != nil {
		panic(err)
	}
}

package main

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

func (io *IO) Solve() {
	io.setBuffer()
	io.Int()
	s := io.Bytes()
	for i, v := range s {
		if v == '(' && i%2 == 0 || v == ')' && i%2 != 0 {
			io.Print("0")
		} else {
			io.Print("1")
		}
	}
}

func main() {
	NewIO().Solve()
}

type IO struct {
	scanner *bufio.Scanner
	writer  io.Writer
}

func NewIO() *IO {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return &IO{scanner, os.Stdout}
}

func (io *IO) Skip() {
	io.scanner.Scan()
}

func (io *IO) Int32() (n int32) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	for _, v := range buf {
		n = n*10 + int32(v-'0')
	}
	return
}

func (io *IO) Int() (n int) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	for _, v := range buf {
		n = n*10 + int(v-'0')
	}
	return
}

func (io *IO) UInt() (n uint) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	for _, v := range buf {
		n = n*10 + uint(v-'0')
	}
	return
}

func (io *IO) Bytes() []byte {
	io.scanner.Scan()
	return io.scanner.Bytes()
}

func (io *IO) IntArray(n int) (arr []int) {
	arr = make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = io.Int()
	}
	return
}

func (io *IO) UIntArray(n int) (arr []uint) {
	arr = make([]uint, n)
	for i := 0; i < n; i++ {
		arr[i] = io.UInt()
	}
	return
}

func (io *IO) Print(a interface{}) {
	fmt.Fprint(io.writer, a)
}

func (io *IO) Printf(format string, a interface{}) {
	fmt.Fprintf(io.writer, format, a)
}

func (io *IO) setBuffer() {
	io.scanner.Buffer(make([]byte, 4096), 512*1024)
}

func (io *IO) setRuneSplit() {
	io.scanner.Split(bufio.ScanRunes)
}

package main

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

func (io *IO) Solve() {
	io.setBuffer()
	n := io.Int()
	s := io.Bytes()
	res := make([]bool, n)
	for i, v := range s {
		if v == '(' {
			res[i] = i%2 == 0
		} else {
			res[i] = i%2 != 0
		}
	}
	for _, v := range res {
		if v {
			io.Print("0")
		} else {
			io.Print("1")
		}
	}
}

func main() {
	NewIO().Solve()
}

type IO struct {
	scanner *bufio.Scanner
	writer  io.Writer
}

func NewIO() *IO {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return &IO{scanner, os.Stdout}
}

func (io *IO) Skip() {
	io.scanner.Scan()
}

func (io *IO) Int32() (n int32) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	for _, v := range buf {
		n = n*10 + int32(v-'0')
	}
	return
}

func (io *IO) Int() (n int) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	for _, v := range buf {
		n = n*10 + int(v-'0')
	}
	return
}

func (io *IO) UInt() (n uint) {
	io.scanner.Scan()
	buf := io.scanner.Bytes()
	for _, v := range buf {
		n = n*10 + uint(v-'0')
	}
	return
}

func (io *IO) Bytes() []byte {
	io.scanner.Scan()
	return io.scanner.Bytes()
}

func (io *IO) IntArray(n int) (arr []int) {
	arr = make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = io.Int()
	}
	return
}

func (io *IO) UIntArray(n int) (arr []uint) {
	arr = make([]uint, n)
	for i := 0; i < n; i++ {
		arr[i] = io.UInt()
	}
	return
}

func (io *IO) Print(a interface{}) {
	fmt.Fprint(io.writer, a)
}

func (io *IO) Printf(format string, a interface{}) {
	fmt.Fprintf(io.writer, format, a)
}

func (io *IO) setBuffer() {
	io.scanner.Buffer(make([]byte, 4096), 512*1024)
}

package main

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

func main(){
	r:= bufio.NewReader(os.Stdin)
	var n int
	var s string

	fmt.Fscanf(r,"%d\n",&n)
	fmt.Fscanf(r,"%s\n",&s);
	h , k:=0 , 0

	for i:= 0 ; i < n ; i ++ {
		if s[i] == '(' {
			fmt.Printf("%d",h)
			h = 1-h
		} else {
			fmt.Printf("%d",k)
			k = 1-k
		}

	}
}

package main

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

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

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

func main() {
	defer writer.Flush()

	var n int
	scanf("%d\n", &n)
	var s string
	scanf("%s\n", &s)

	l1, l2 := 0, 0
	for i := 0; i < n; i++ {
		if s[i] == '(' {
			if l1 <= l2 {
				l1++
				printf("0")
			} else {
				l2++
				printf("1")
			}
		} else {
			if l1 >= l2 {
				l1--
				printf("0")
			} else {
				l2--
				printf("1")
			}
		}
	}
}

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/1167/D

package main

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

type BracketSequence struct {
	Left  int
	Right int
}

func getNestedDepth(b BracketSequence) int {
	return b.Left - b.Right
}

func Solve(n int, s string) string {
	red := BracketSequence{Left: 0, Right: 0}
	blue := BracketSequence{Left: 0, Right: 0}
	answer := make([]string, n)
	for i := 0; i < n; i++ {
		if string(s[i]) == "(" && getNestedDepth(red) <= getNestedDepth(blue) {
			red.Left += 1
			answer[i] = "0"
		} else if string(s[i]) == "(" && getNestedDepth(blue) < getNestedDepth(red) {
			blue.Left += 1
			answer[i] = "1"
		}
		if string(s[i]) == ")" && getNestedDepth(red) >= getNestedDepth(blue) {
			red.Right += 1
			answer[i] = "0"
		} else if string(s[i]) == ")" && getNestedDepth(red) < getNestedDepth(blue) {
			blue.Right += 1
			answer[i] = "1"
		}
	}
	return strings.Join(answer, "")
}

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

	var n int
	var s string
	fmt.Fscanf(reader, "%d\n%s\n", &n, &s)
	fmt.Fprintf(writer, "%s\n", Solve(n, s))
}

package main

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

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

	defer writer.Flush()

	var n int
	var s string
	fmt.Fscanf(reader, "%d", &n)
	fmt.Fscanf(reader, "%s")
	fmt.Fscanf(reader, "%s", &s)

	var r = 0
	var b = 0
	for i := 0; i < n; i++ {
		if r <= b && s[i] == '(' {
			r++
			fmt.Fprintf(writer, "%d", 0)
		} else if b < r && s[i] == '(' {
			b++
			fmt.Fprintf(writer, "%d", 1)
		} else if r <= b && s[i] == ')' {
			b--
			fmt.Fprintf(writer, "%d", 1)
		} else {
			r--
			fmt.Fprintf(writer, "%d", 0)
		}
	}
	fmt.Fprintln(writer)
}

package main

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

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

	defer writer.Flush()

	var n int
	var s string
	fmt.Fscanf(reader, "%d", &n)
	fmt.Fscanf(reader, "%s")
	fmt.Fscanf(reader, "%s", &s)

	var cur = 0
	for i := 0; i < n; i++ {
		if cur == 0 && s[i] == '(' {
			cur++
			fmt.Fprintf(writer, "%d", 0)
		} else if cur == 1 && s[i] == ')' {
			cur--
			fmt.Fprintf(writer, "%d", 0)
		} else {
			fmt.Fprintf(writer, "%d", 1)
		}
	}
	fmt.Fprintln(writer)
}


Kostya is a progamer specializing in the discipline of Dota 2. Valve Corporation, the developer of this game, has recently released a new patch which turned the balance of the game upside down. Kostya, as the captain of the team, realizes that the greatest responsibility lies on him, so he wants to resort to the analysis of innovations patch from the mathematical point of view to choose the best heroes for his team in every game.A Dota 2 match involves two teams, each of them must choose some heroes that the players of the team are going to play for, and it is forbidden to choose the same hero several times, even in different teams. In large electronic sports competitions where Kostya's team is going to participate, the matches are held in the Captains Mode. In this mode the captains select the heroes by making one of two possible actions in a certain, predetermined order: pick or ban.  To pick a hero for the team. After the captain picks, the picked hero goes to his team (later one of a team members will play it) and can no longer be selected by any of the teams.  To ban a hero. After the ban the hero is not sent to any of the teams, but it still can no longer be selected by any of the teams. The team captain may miss a pick or a ban. If he misses a pick, a random hero is added to his team from those that were available at that moment, and if he misses a ban, no hero is banned, as if there was no ban.Kostya has already identified the strength of all the heroes based on the new patch fixes. Of course, Kostya knows the order of picks and bans. The strength of a team is the sum of the strengths of the team's heroes and both teams that participate in the match seek to maximize the difference in strengths in their favor. Help Kostya determine what team, the first one or the second one, has advantage in the match, and how large the advantage is.

The first line contains a single integer n (2 ≤ n ≤ 100) — the number of heroes in Dota 2. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 106) — the strengths of all the heroes. The third line contains a single integer m (2 ≤ m ≤ min(n, 20)) — the number of actions the captains of the team must perform. Next m lines look like "action team", where action is the needed action: a pick (represented as a "p") or a ban (represented as a "b"), and team is the number of the team that needs to perform the action (number 1 or 2). It is guaranteed that each team makes at least one pick. Besides, each team has the same number of picks and the same number of bans.

Print a single integer — the difference between the strength of the first team and the strength of the second team if the captains of both teams will act optimally well.

package main

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

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

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

	sort.Ints(a)
	for i := 0; i < n/2; i++ {
		j := n - 1 - i
		a[i], a[j] = a[j], a[i]
	}
	if m < n {
		a = a[:m]
	}

	//	fmt.Println(a)
	//	fmt.Println(b)
	//	fmt.Println(c)

	const inf = 0x7fffffff
	cache := make([][]int, m)
	for i := range cache {
		cache[i] = make([]int, 1<<uint(m))
		for j := range cache[i] {
			cache[i][j] = inf
		}
	}
	bit := func(i int) int {
		return 1<<uint(i)
	}
	var dfs func(i, s int) int
	dfs = func(i, s int) (ans int) {
		if i >= m {
			return 0
		}
		if cache[i][s] != inf {
			return cache[i][s]
		}
		defer func() {
			cache[i][s] = ans
		}()

		ans = inf
		if b[i] == "p" {
			j := -1
			for j = 0; j < m; j++ {
				if s&bit(j) == 0 {
					break
				}
			}
			if j >= m { panic(j) }
			ans = dfs(i+1, s|bit(j))
			if c[i] == 1 {
				ans += a[j]
			} else {
				ans -= a[j]
			}
		} else {
			for j := 0; j < m; j++ {
				if s&bit(j) == 0 {
					ans1 := dfs(i+1, s|bit(j))
					if c[i] == 1 {
						if ans == inf || ans1 > ans {
							ans = ans1
						}
					} else {
						if ans == inf || ans1 < ans {
							ans = ans1
						}
					}
				}
			}
		}
		return
	}
	fmt.Println(dfs(0, 0))
}

package main

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

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

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

	sort.Ints(a)
	for i := 0; i < n / 2; i++ {
		j := n - 1 - i
		a[i], a[j] = a[j], a[i]
	}
	if m < n {
		a = a[:m]
	}

//	fmt.Println(a)
//	fmt.Println(b)
//	fmt.Println(c)

	const inf = 0x7fffffff
	cache := make([][]int, m)
	for i := range cache {
		cache[i] = make([]int, 1<<uint(m))
		for j := range cache[i] {
			cache[i][j] = inf
		}
	}
	var dfs func(i, s int) int
	dfs = func(i, s int) (ans int) {
		if i >= m {
			return 0
		}
		if cache[i][s] != inf {
			return cache[i][s]
		}
		defer func() {
			cache[i][s] = ans
		}()

		if b[i] == "p" {
			j := -1
			for j = m-1; j >= 0; j-- {
				if s & (1<<uint(j)) == 0 { break }
			}
			ans = dfs(i + 1, s | (1 << uint(j)))
			if c[i] == 1 {
				ans += a[i]
			} else {
				ans -= a[i]
			}
		} else {
			ans = dfs(i+1, s)
			for j := m-1; j >= 0; j-- {
				if s & (1<<uint(j)) == 0 {
					ans1 := dfs(i+1, s|(1<<uint(j)))
					if c[i] == 1 {
						if ans1 > ans { ans = ans1 }
					} else {
						if ans1 < ans { ans = ans1 }
					}
				}
			}
		}
		return
	}
	fmt.Println(dfs(0, 0))
}