One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple.Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column.Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps).A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step.Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.

The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).

Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

NoteIn the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0,  - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps.In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.

// 152B
package main

import (
	"fmt"
)

func min(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func main() {
	var i, k, n, m, x, y, dx, dy, ans, z1, z2, z int64
	ans = 0
	fmt.Scan(&n, &m, &x, &y, &k)
	for i = 1; i <= k; i++ {
		fmt.Scan(&dx, &dy)
		if dx < 0 {
			z1 = (1 - x) / dx
		} else if dx > 0 {
			z1 = (n - x) / dx
		} else {
			z1 = 1000000000
		}
		if dy < 0 {
			z2 = (1 - y) / dy
		} else if dy > 0 {
			z2 = (m - y) / dy
		} else {
			z2 = 1000000000
		}
		z = min(z1, z2)
		ans += z
		x = x + z*dx
		y = y + z*dy
	}
	fmt.Print(ans)
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)

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

func main() {
	scanner.Split(bufio.ScanWords)
	n, m, x, y, c, sum := scanNum(), scanNum(), scanNum(), scanNum(), scanNum(), int64(0)

	for i := 0; i < c; i++ {
		dx, dy, step := scanNum(), scanNum(), math.MaxInt32
		if dx != 0 {
			newStep := (n - x) / dx
			if dx < 0 {
				newStep = (x - 1) / -dx
			}
			if newStep < step {
				step = newStep
			}
		}
		if dy != 0 {
			newStep := (m - y) / dy
			if dy < 0 {
				newStep = (y - 1) / -dy
			}
			if newStep < step {
				step = newStep
			}
		}
		sum, x, y = sum+int64(step), x+step*dx, y+step*dy
	}

	fmt.Println(sum)
}

package main

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

type sortR [][2]int

func (r sortR) Less(i, j int) bool {
	if r[i][0] == r[j][0] {
		return r[i][1] < r[j][1]
	}
	return r[i][0] < r[j][0]
}
func (r sortR) Len() int      { return len(r) }
func (r sortR) Swap(i, j int) { r[i], r[j] = r[j], r[i] }

func main() {
	n, k, q := 0, 0, 0
	fmt.Scan(&n, &k, &q)
	r := make([][2]int, n)
	qL := make([][2]int, q)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; i < n; i++ {
		scanner.Scan()
		r[i][0], _ = strconv.Atoi(scanner.Text())
		scanner.Scan()
		r[i][1], _ = strconv.Atoi(scanner.Text())
	}
	sort.Sort(sortR(r))
	for i := 0; i < q; i++ {
		scanner.Scan()
		qL[i][0], _ = strconv.Atoi(scanner.Text())
		scanner.Scan()
		qL[i][1], _ = strconv.Atoi(scanner.Text())
	}

	qMap := map[int]bool{}
	for _, v := range qL {
		rCount := 0
		for i := v[0]; i <= v[1]; i++ {
			if res, ok := qMap[i]; ok == true {
				if res {
					rCount++
				}
				continue
			}

			// lower := -1
			// // Search the smallest j that r[j][1] >= i, and has bug here
			// // Because r[0][1] might be much bigger then r[1][1]
			// // And r[1][1] might not match the need for r[j][1] >= i, which break stuff
			// l, h := 0, len(r)-1
			// for l <= h {
			// 	mid := (l + h) / 2
			// 	if r[mid][1] >= i {
			// 		lower = mid
			// 		h = mid - 1
			// 	} else {
			// 		l = mid + 1
			// 	}
			// }
			// if lower == -1 {
			// 	continue
			// }

			upper := -1
			// Search the largest j that r[j][0] <= i
			l, h := 0, len(r)-1
			for l <= h {
				mid := (l + h) / 2
				if r[mid][0] <= i {
					upper = mid
					l = mid + 1
				} else {
					h = mid - 1
				}
			}
			if upper == -1 {
				continue
			}

			count := 0
			for j := 0; j <= upper; j++ {
				if r[j][1] >= i {
					count++
				}
			}

			qMap[i] = false
			if count >= k {
				rCount++
				qMap[i] = true
			}
		}
		fmt.Println(rCount)
	}
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)

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

func main() {
	scanner.Split(bufio.ScanWords)
	n, m, x, y, c, sum := scanNum(), scanNum(), scanNum(), scanNum(), scanNum(), 0

	for i := 0; i < c; i++ {
		dx, dy, step := scanNum(), scanNum(), math.MaxInt32
		if dx != 0 {
			newStep := (n - x) / dx
			if dx < 0 {
				newStep = (x - 1) / -dx
			}
			if newStep < step {
				step = newStep
			}
		}
		if dy != 0 {
			newStep := (m - y) / dy
			if dy < 0 {
				newStep = (y - 1) / -dy
			}
			if newStep < step {
				step = newStep
			}
		}
		sum, x, y = sum+step, x+step*dx, y+step*dy
	}

	fmt.Println(sum)
}


A class of students wrote a multiple-choice test.There are $$$n$$$ students in the class. The test had $$$m$$$ questions, each of them had $$$5$$$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $$$i$$$ worth $$$a_i$$$ points. Incorrect answers are graded with zero points.The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of students in the class and the number of questions in the test. Each of the next $$$n$$$ lines contains string $$$s_i$$$ ($$$|s_i| = m$$$), describing an answer of the $$$i$$$-th student. The $$$j$$$-th character represents the student answer (A, B, C, D or E) on the $$$j$$$-th question. The last line contains $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \le a_i \le 1000$$$) — the number of points for the correct answer for every question.

Print a single integer — the maximum possible total score of the class.

NoteIn the first example, one of the most optimal test answers is "ABCD", this way the total number of points will be $$$16$$$.In the second example, one of the most optimal test answers is "CCC", this way each question will be answered by exactly one student and the total number of points is $$$5 + 4 + 12 = 21$$$.

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

func getNumsFromOneLine(ir *bufio.Reader) []int {
	stream, _ := ir.ReadString('\n')
	// Trims the stream and then splits
	trimmedStream := strings.TrimSpace(stream)
	splitArr := strings.Split(trimmedStream, " ")
	// convert strings to integers and store them in a slice
	nums := make([]int, len(splitArr))
	for index, val := range splitArr {
		nums[index], _ = strconv.Atoi(val)
	}
	return nums
}

func main(){
	ir := bufio.NewReader(os.Stdin)
	nm := getNumsFromOneLine(ir)
	n, m := nm[0], nm[1]

	lookup := make([][5]int, m)
	for i := 0; i < n; i++ {
		ans, _ := ir.ReadString('\n')
    //fmt.Println(ans)
		for j := 0; j < m; j++ {
			lookup[j][ans[j] - 'A'] += 1
		}
	}

  scores := getNumsFromOneLine(ir)
	res := 0
	for i := 0; i < m; i++ {
		max := 0
		for _, cnt := range lookup[i] {
			if cnt > max {
				max = cnt
			}
		}
		score := scores[i]
    //fmt.Println(score)
		res += score * max
	}
	fmt.Println(res)
}

package main

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

/* solution */

func solve() {

	n, m := readInt(), readInt()
	arr := make([][5]int, m)

	for i := 0; i < n; i++ {
		s := readString()
		for num, c := range s {
			arr[num][c-'A']++
		}
	}

	var points = make([]int, m)
	for i := 0; i < m; i++ {
		points[i] = readInt()
	}

	ret := 0

	for i := 0; i < m; i++ {
		max := arr[i][0]
		for c := 'B'; c <= 'E'; c++ {
			if arr[i][c-'A'] > max {
				max = arr[i][c-'A']
			}
		}
		ret += points[i] * max
	}

	println(strconv.Itoa(ret))

}

/* stubs */

func main() {

	var f *os.File
	if runtime.GOROOT() == "C:\\Soft\\Go" {
		f, _ = os.Open("input.txt")
	} else {
		f = os.Stdin
	}
	defer f.Close()

	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	reader = bufio.NewScanner(f)
	reader.Split(bufio.ScanWords)

	solve()

}

var reader *bufio.Scanner
var writer *bufio.Writer

func readInt() int {
	reader.Scan()
	ret, _ := strconv.Atoi(reader.Text())
	return ret
}

func readString() string {
	reader.Scan()
	return reader.Text()
}

func print(s string) {
	writer.WriteString(s)
}

func println(s string) {
	print(s)
	print("\n")
}

package main

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

func main() {
	var n, q, cnt int

	scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Fscanln(scr, &n, &q)
	st := make([]string, n)
	m := make([]int, q)
	choices := make(map[string]int)
	choices["A"] = 0
	choices["B"] = 1
	choices["C"] = 2
	choices["D"] = 3
	choices["E"] = 4

	for i := 0; i < n; i++ {
		fmt.Fscanln(scr, &st[i])
	}
	for i := 0; i < q; i++ {
		fmt.Fscanf(scr, "%d", &m[i])
	}

	for i := 0; i < q; i++ {
		arr := make([]int, 5)
		for _, y := range st {
			arr[choices[string(y[i])]]++
		}

		max := 0
		for _, y := range arr {
			if y > max {
				max = y
			}
		}
		cnt += m[i] * max
	}
	fmt.Println(cnt)
}

//HOWDY! IT'S ME! A HARD BLACKISH DICK MOVE!
package main

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

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

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

//str := PrintlnInts(X...)

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

func main() {
	n, m := ReadInt2()
	dist := make([][5]int, m)
	for i := 0; i < n; i++ {
		s := ReadString()
		for j := 0; j < m; j++ {
			dist[j][s[j]-'A']++
		}
	}
	scores := ReadIntSlice(m)
	ans := 0
	for j := 0; j < m; j++ {
		max := 0
		for k := 0; k < 5; k++ {
			if dist[j][k] > max {
				max = dist[j][k]
			}
		}
		ans += max * scores[j]
	}
	fmt.Println(ans)
}

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

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

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

func _gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return _gcd(b, a%b)
}

func gcd(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	gcd := args[0]
	for i := 1; i < len(args); i++ {
		gcd = _gcd(gcd, args[i])
	}
	return gcd
}

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

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

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

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

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

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

func readInt_64() int64 {
	return readIntNbits(64)
}

func ReadInt2_64() (int64, int64) {
	return readInt_64(), readInt_64()
}

func ReadInt3_64() (int64, int64, int64) {
	return readInt_64(), readInt_64(), readInt_64()
}

func readInt() int {
	return int(readIntNbits(32))
}

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

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

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

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

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

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

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

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

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

	return string(res)
}

package main

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

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

// IO helper functions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// IO functions

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

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

// Read next line as []byte
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b
}

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

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

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

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

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

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

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

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

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

// Simple math functions

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

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

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

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

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

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

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

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

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

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

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

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

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

func main() {
	defer Flush()

	n := readi()
	m := readi()
	A := make([][]byte, n)
	for i := range A {
		A[i] = readb()
	}
	a := make([]int, m)
	for i := range a {
		a[i] = readi()
	}

	var ans int
	for j := range a {
		t := make([]int, 5)
		for i := range A {
			t[A[i][j]-'A']++
		}
		x := 0
		for _, v := range t {
			x = max(x, v)
		}
		ans += a[j] * x
	}
	println(ans)
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n, m, t := 0, 0, 0
	fmt.Sscanf(scanner.Text(), "%d %d", &n, &m)
	r := make([][5]int, m)
	for i := 0; i < n; i++ {
		scanner.Scan()
		for i, a := range scanner.Text() {
			r[i][a-'A']++
		}
	}
	v := make([]int, m)
	scanner.Scan()
	for i, c := range strings.Split(scanner.Text(), " ") {
		v[i], _ = strconv.Atoi(c)
	}
	for i := range r {
		max := 0
		for _, a := range r[i] {
			if a > max {
				max = a
			}
		}
		t += max * v[i]
	}
	fmt.Println(t)
}

package main
import "fmt"

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

	lookup := make([][5]int, m)
	for i := 0; i < n; i++ {
		ans := ""
		fmt.Scanf("%s\n", &ans)
		for j := 0; j < m; j++ {
			lookup[j][ans[j] - 'A'] += 1
		}
	}

	res := 0
	for i := 0; i < m; i++ {
		max := 0
		for _, cnt := range lookup[i] {
			if cnt > max {
				max = cnt
			}
		}
		score := 0
		//fmt.Scanf("%d", &score)
		res += score * max
	}
	fmt.Println(res)
}

package main
import "fmt"

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

	lookup := make([][5]int, m)
	for i := 0; i < n; i++ {
		ans := ""
		fmt.Scanf("%s\n", &ans)
		for j := 0; j < m; j++ {
			lookup[i][ans[j] - 'A'] += 1
		}
	}

	res := 0
	for i := 0; i < m; i++ {
		max := 0
		for _, cnt := range lookup[i] {
			if cnt > max {
				max = cnt
			}
		}
		score := 0
		fmt.Scanf("%d", &score)
		res += score * max
	}
	fmt.Println(res)
}

package main
import "fmt"

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

	lookup := make(map[int]map[byte]int)
	for i := 0; i < n; i++ {
		ans := ""
		fmt.Scanf("%s\n", &ans)
		for j := 0; j < m; j++ {
			if _, ok := lookup[j]; ok {
				if _, o := lookup[j][ans[j]]; o {
					lookup[j][ans[j]] = lookup[j][ans[j]] + 1
				} else {
					lookup[j][ans[j]] = 1
				}
			} else {
				lookup[j] = map[byte]int{ans[j] : 1}
			}

		}
	}

	res := 0
	for i := 0; i < m; i++ {
		max := 0
		for _, cnt := range lookup[i] {
			if cnt > max {
				max = cnt
			}
		}
		score := 0
		fmt.Scanf("%d\n", &score)
		res += score * max
	}
	fmt.Println(res)
}

package main

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

/* solution */

func solve() {

	n, m := readInt(), readInt()
	arr := make([][5]int, m)

	for i := 0; i < n; i++ {
		s := readString()
		for num, c := range s {
			arr[num][c-'A']++
		}
	}

	var points [5]int
	for i := 0; i < m; i++ {
		points[i] = readInt()
	}

	ret := 0

	for i := 0; i < m; i++ {
		ans := 'A'
		max := arr[i][0]
		for c := 'B'; c <= 'E'; c++ {
			if arr[i][c-'A'] > max {
				ans = c
				max = arr[i][c-'A']
			}
		}
		ret += points[ans-'A'] * max
	}

	println(strconv.Itoa(ret))

}

/* stubs */

func main() {

	var f *os.File
	if runtime.GOROOT() == "C:\\Soft\\Go" {
		f, _ = os.Open("input.txt")
	} else {
		f = os.Stdin
	}
	defer f.Close()

	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	reader = bufio.NewScanner(f)
	reader.Split(bufio.ScanWords)

	solve()

}

var reader *bufio.Scanner
var writer *bufio.Writer

func readInt() int {
	reader.Scan()
	ret, _ := strconv.Atoi(reader.Text())
	return ret
}

func readString() string {
	reader.Scan()
	return reader.Text()
}

func print(s string) {
	writer.WriteString(s)
}

func println(s string) {
	print(s)
	print("\n")
}


This is an interactive problem.Baby Ehab loves crawling around his apartment. It has $$$n$$$ rooms numbered from $$$0$$$ to $$$n-1$$$. For every pair of rooms, $$$a$$$ and $$$b$$$, there's either a direct passage from room $$$a$$$ to room $$$b$$$, or from room $$$b$$$ to room $$$a$$$, but never both.Baby Ehab wants to go play with Baby Badawy. He wants to know if he could get to him. However, he doesn't know anything about his apartment except the number of rooms. He can ask the baby sitter two types of questions:   is the passage between room $$$a$$$ and room $$$b$$$ directed from $$$a$$$ to $$$b$$$ or the other way around?  does room $$$x$$$ have a passage towards any of the rooms $$$s_1$$$, $$$s_2$$$, ..., $$$s_k$$$? He can ask at most $$$9n$$$ queries of the first type and at most $$$2n$$$ queries of the second type.After asking some questions, he wants to know for every pair of rooms $$$a$$$ and $$$b$$$ whether there's a path from $$$a$$$ to $$$b$$$ or not. A path from $$$a$$$ to $$$b$$$ is a sequence of passages that starts from room $$$a$$$ and ends at room $$$b$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 30$$$) — the number of test cases you need to solve. Then each test case starts with an integer $$$n$$$ ($$$4 \le n \le 100$$$) — the number of rooms. The sum of $$$n$$$ across the test cases doesn't exceed $$$500$$$.

To print the answer for a test case, print a line containing "3", followed by $$$n$$$ lines, each containing a binary string of length $$$n$$$. The $$$j$$$-th character of the $$$i$$$-th string should be $$$1$$$ if there's a path from room $$$i$$$ to room $$$j$$$, and $$$0$$$ if there isn't. The $$$i$$$-th character of the $$$i$$$-th string should be $$$1$$$ for each valid $$$i$$$. After printing the answer, we will respond with a single integer. If it's $$$1$$$, you printed a correct answer and should keep solving the test cases (or exit if it is the last one). If it's $$$-1$$$, you printed a wrong answer and should terminate to get Wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.

NoteIn the given example:The first query asks whether there's a passage from room $$$3$$$ to any of the other rooms.The second query asks about the direction of the passage between rooms $$$0$$$ and $$$1$$$.After a couple other queries, we concluded that you can go from any room to any other room except if you start at room $$$3$$$, and you can't get out of this room, so we printed the matrix:1111111111110001The interactor answered with $$$1$$$, telling us the answer is correct.

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

// github.com/EndlessCheng/codeforces-go
func main() {
	var T, n, c int
	var ok bool
	for Scan(&T); T > 0; T-- {
		Scan(&n)
		a := make([]int, n)
		for i := range a {
			a[i] = i
		}
		sort.Slice(a, func(i, j int) (d bool) { Println(1, a[j], a[i]); Scan(&d); return })
		g := make([]int, n)
		for i := 0; i < n; {
			c++
			g[a[i]] = c
			i++
			for j := i - 1; j < i; j++ {
				for i < n {
					Print(2, a[j], n-i)
					for _, v := range a[i:] {
						Print(" ", v)
					}
					Println()
					if Scan(&ok); !ok {
						break
					}
					g[a[i]] = c
					i++
				}
			}
		}
		Println(3)
		for _, v := range g {
			s := ""
			for _, w := range g {
				if v < w {
					s+="0"
				} else {
					s+="1"
				}
			}
			Println(s)
		}
		Scan(&n)
	}
}

package main

import (
	. "fmt"
	"sort"
)

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

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

// github.com/EndlessCheng/codeforces-go
func main() {
	var T, n, c int
	var ok bool
	for Scan(&T); T > 0; T-- {
		Scan(&n)
		a := make([]int, n)
		for i := range a {
			a[i] = i
		}
		sort.Slice(a, func(i, j int) (d bool) { Println(1, a[j], a[i]); Scan(&d); return })
		g := make([]int, n)
		for i := 0; i < n; {
			c++
			v := a[i]
			g[v] = c
			for i++; i < n; i++ {
				Print(2, v, n-i)
				for _, w := range a[i:] {
					Print(" ", w)
				}
				Println()
				if Scan(&ok); !ok {
					break
				}
				g[a[i]] = c
			}
		}
		Println(3)
		for _, v := range a {
			for _, w := range a {
				if v < w {
					Print("0")
				} else {
					Print("1")
				}
			}
			Println()
		}
		Scan(&n)
	}
}


In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions:  overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.

The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.

Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.

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

func main() {
	var v [1111111]int
	var i,j,n,m,k int
	fmt.Scan(&n,&m)
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	var a,b [5]int
	out := bufio.NewWriter(os.Stdout)
	for i=1;i<=m; i++{
		t:=0
		for j=1;j<=3;j++{
			input.Scan()
			aa,_:=strconv.Atoi(input.Text())
			b[j]=aa
			//fmt.Scan(&b[j])
			if v[b[j]]!=0 {t=b[j]}
		}
		a[1],a[2],a[3] = 0,0,0
		if t!=0 { a[v[t]] =1}

		for j=1;j<=3;j++{
			if v[b[j]]!=0 { continue }
			for k=1;k<=3;k++{
				if a[k]!=0 { continue}
				v[b[j]] = k
				a[k] = 1
				break
			}
		}
	}
	for i=1;i<=n;i++{
		out.WriteString(strconv.Itoa(v[i])+" ")
	}
	out.Flush()
}

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

func main() {
	var v [1111111]int
	var i,j,n,m,k int
	fmt.Scan(&n,&m)
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	var a,b [5]int
	out := bufio.NewWriter(os.Stdout)
	for i=1;i<=m; i++{
		t:=0
		for j=1;j<=3;j++{
			input.Scan()
			aa,_:=strconv.Atoi(input.Text())
			b[i]=aa
			//fmt.Scan(&b[j])
			if v[b[j]]!=0 {t=b[j]}
		}
		a[1],a[2],a[3] = 0,0,0
		if t!=0 { a[v[t]] =1}

		for j=1;j<=3;j++{
			if v[b[j]]!=0 { continue }
			for k=1;k<=3;k++{
				if a[k]!=0 { continue}
				v[b[j]] = k
				a[k] = 1
				break
			}
		}
	}
	for i=1;i<=n;i++{
		out.WriteString(strconv.Itoa(v[i])+" ")
	}
	out.Flush()
}


Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves:  Value x and some direction are announced, and all boys move x positions in the corresponding direction.  Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy.

The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while  - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type.

Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves.

package main

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

var in = bufio.NewScanner(os.Stdin)

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

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

	n := readInt()

	shift := int64(0)
	oddForw := int64(0)
	for q := readInt(); q > 0; q-- {
		switch readInt() {
		case 1:
			shift += readInt()
			if shift < 0 {
				shift += n
			} else if shift >= n {
				shift -= n
			}
		case 2:
			if (shift+oddForw)%2 == 0 {
				oddForw++
				if oddForw == n {
					oddForw = 0
				}
			} else {
				oddForw--
				if oddForw < 0 {
					oddForw += n
				}
			}
		default:
			panic("switch")
		}
	}
	ans := make([]int64, n)
	for i := int64(1); i < n; i += 2 {
		ans[(i-1+shift+oddForw)%n] = i
	}
	evenForw := (n - oddForw) % n
	for i := int64(2); i <= n; i += 2 {
		ans[(i-1+shift+evenForw)%n] = i
	}
	for i, v := range ans {
		if i+1 == int(n) {
			fmt.Fprintln(out, v)
		} else {
			fmt.Fprint(out, v, " ")
		}
	}
}

package main

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

func main() {
	defer out.Flush()
	n := in.NextInt()
	q := in.NextInt()
	pos1 := 0
	pos2 := 1
	for i := 0; i < q; i++ {
		t := in.NextInt()
		switch t {
		case 1:
			x := in.NextInt()
			pos1 += x
			pos2 += x
		case 2:
			pos1 ^= 1
			pos2 ^= 1
		}
		pos1 = mathmod(pos1, n)
		pos2 = mathmod(pos2, n)
	}
	ans := make([]int, n)
	for i := 0; i < n; i += 2 {
		ans[(pos1+i)%n] = 1 + i
	}
	for i := 0; i < n; i += 2 {
		ans[(pos2+i)%n] = 2 + i
	}
	for i := range ans {
		if i != 0 {
			fmt.Fprint(out, " ")
		}
		fmt.Fprint(out, ans[i])
	}
	fmt.Fprintln(out)
}

func mathmod(a, b int) int {
	if !(0 <= a && a < b) {
		return (a%b + b) % b
	}
	return a
}

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

type FastReader struct {
	r   *bufio.Reader
	buf string
}

func NewFastReader(r io.Reader) *FastReader {
	return &FastReader{
		r: bufio.NewReader(r),
	}
}

func (r *FastReader) advance() {
	for len(r.buf) != 0 && r.buf[0] == ' ' {
		r.buf = r.buf[1:]
	}
	var err error
	for len(r.buf) == 0 && err != io.EOF {
		buf := new(bytes.Buffer)
		for {
			var chunk []byte
			var more bool
			chunk, more, err = r.r.ReadLine()
			buf.Write(chunk)
			if !more {
				break
			}
		}
		r.buf = buf.String()
	}
}

func (r *FastReader) NextLine() string {
	r.advance()
	line := r.buf
	r.buf = ""
	return line
}

func (r *FastReader) NextWord() string {
	r.advance()
	var word string
	wordStart := 0
	for i := 0; i < len(r.buf); i++ {
		b := r.buf[i]
		if b == ' ' {
			if i != wordStart {
				word = r.buf[wordStart:i]
				r.buf = r.buf[i:]
				break
			}
			wordStart = i + 1
		}
	}
	if len(word) == 0 {
		word = r.buf
		r.buf = ""
	}
	return word
}

func (r *FastReader) NextInt() int {
	return parseInt(r.NextWord())
}

func parseInt(word string) int {
	sign := 1
	if word[0] == '-' {
		sign = -1
		word = word[1:]
	}
	result := 0
	for i := 0; i < len(word); i++ {
		result = result*10 + int(word[i]) - '0'
	}
	result *= sign
	return result
}

package main

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

var in = bufio.NewScanner(os.Stdin)

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

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

	n := readInt()

	shift := int64(0)
	oddForw := int64(0)
	for q := readInt(); q > 0; q-- {
		switch readInt() {
		case 1:
			shift += readInt()
			if shift < 0 {
				shift += n
			} else if shift >= n {
				shift -= n
			}
		case 2:
			if shift%2 == 0 {
				oddForw++
				if oddForw == n {
					oddForw = 0
				}
			} else {
				oddForw--
				if oddForw < 0 {
					oddForw += n
				}
			}
		default:
			panic("switch")
		}
	}
	ans := make([]int64, n)
	for i := int64(1); i < n; i += 2 {
		ans[(i-1+shift+oddForw)%n] = i
	}
	evenForw := (n - oddForw) % n
	for i := int64(2); i <= n; i += 2 {
		ans[(i-1+shift+evenForw)%n] = i
	}
	for i, v := range ans {
		if i+1 == int(n) {
			fmt.Fprintln(out, v)
		} else {
			fmt.Fprint(out, v, " ")
		}
	}
}

package main

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

func main() {
	defer out.Flush()
	n := in.NextInt()
	q := in.NextInt()
	flip := 0
	shift := 0
	for i := 0; i < q; i++ {
		t := in.NextInt()
		switch t {
		case 1:
			x := in.NextInt()
			shift += x
			if !(0 <= shift && shift < n) {
				shift = (shift%n + n) % n
			}
		case 2:
			flip = 1 - flip
		}
	}
	ans := make([]int, n)
	for i := 0; i < n; i++ {
		ans[(i+shift)%n] = (i ^ flip) + 1
	}
	for i := range ans {
		if i != 0 {
			fmt.Fprint(out, " ")
		}
		fmt.Fprint(out, ans[i])
	}
	fmt.Fprintln(out)
}

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

type FastReader struct {
	r   *bufio.Reader
	buf string
}

func NewFastReader(r io.Reader) *FastReader {
	return &FastReader{
		r: bufio.NewReader(r),
	}
}

func (r *FastReader) advance() {
	for len(r.buf) != 0 && r.buf[0] == ' ' {
		r.buf = r.buf[1:]
	}
	var err error
	for len(r.buf) == 0 && err != io.EOF {
		buf := new(bytes.Buffer)
		for {
			var chunk []byte
			var more bool
			chunk, more, err = r.r.ReadLine()
			buf.Write(chunk)
			if !more {
				break
			}
		}
		r.buf = buf.String()
	}
}

func (r *FastReader) NextLine() string {
	r.advance()
	line := r.buf
	r.buf = ""
	return line
}

func (r *FastReader) NextWord() string {
	r.advance()
	var word string
	wordStart := 0
	for i := 0; i < len(r.buf); i++ {
		b := r.buf[i]
		if b == ' ' {
			if i != wordStart {
				word = r.buf[wordStart:i]
				r.buf = r.buf[i:]
				break
			}
			wordStart = i + 1
		}
	}
	if len(word) == 0 {
		word = r.buf
		r.buf = ""
	}
	return word
}

func (r *FastReader) NextInt() int {
	return parseInt(r.NextWord())
}

func parseInt(word string) int {
	sign := 1
	if word[0] == '-' {
		sign = -1
		word = word[1:]
	}
	result := 0
	for i := 0; i < len(word); i++ {
		result = result*10 + int(word[i]) - '0'
	}
	result *= sign
	return result
}


Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: red – brown – yellow – red – brown – yellow and so on. There are many chandeliers that differs in color set or order of colors. And the person responsible for the light made a critical mistake — they bought two different chandeliers.Since chandeliers are different, some days they will have the same color, but some days — different. Of course, it looks poor and only annoys Vasya. As a result, at the $$$k$$$-th time when chandeliers will light with different colors, Vasya will become very angry and, most probably, will fire the person who bought chandeliers.Your task is to calculate the day, when it happens (counting from the day chandeliers were installed). You can think that Vasya works every day without weekends and days off.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 500\,000$$$; $$$1 \le k \le 10^{12}$$$) — the number of colors in the first and the second chandeliers and how many times colors should differ to anger Vasya. The second line contains $$$n$$$ different integers $$$a_i$$$ ($$$1 \le a_i \le 2 \cdot \max(n, m)$$$) that describe the first chandelier's sequence of colors. The third line contains $$$m$$$ different integers $$$b_j$$$ ($$$1 \le b_i \le 2 \cdot \max(n, m)$$$) that describe the second chandelier's sequence of colors. At the $$$i$$$-th day, the first chandelier has a color $$$a_x$$$, where $$$x = ((i - 1) \mod n) + 1)$$$ and the second one has a color $$$b_y$$$, where $$$y = ((i - 1) \mod m) + 1)$$$. It's guaranteed that sequence $$$a$$$ differs from sequence $$$b$$$, so there are will be days when colors of chandeliers differs.

Print the single integer — the index of day when Vasya will become angry.

NoteIn the first example, the chandeliers will have different colors at days $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. That's why the answer is $$$5$$$.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1500B(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}

	var n, m, loop int
	var k, cntDiff int64
	Fscan(in, &n, &m, &k)
	a := make([]int, n)
	pos := make([]int, max(n, m)*2+1)
	for i := range pos {
		pos[i] = -1
	}
	diff := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
		pos[a[i]] = i
		diff[i] = m
	}
	b := make([]int, m)
	for i := range b {
		Fscan(in, &b[i])
		if pos[b[i]] >= 0 {
			diff[((pos[b[i]]-i)%n+n)%n]--
		}
	}

	i := 0
	for {
		cntDiff += int64(diff[i])
		loop++
		i = (i + m) % n
		if i == 0 {
			break
		}
	}
	ans := (k - 1) / cntDiff * int64(loop) * int64(m)
	k -= (k - 1) / cntDiff * cntDiff
	for ; k > int64(diff[i]); i = (i + m) % n {
		k -= int64(diff[i])
		ans += int64(m)
	}
	for j := 0; k > 0; j++ {
		if a[i] != b[j] {
			k--
		}
		ans++
		i = (i + 1) % n
	}
	Fprint(out, ans)
}
func main() { CF1500B(os.Stdin, os.Stdout) }

package main

import (
	. "fmt"
	"syscall"
)

// github.com/EndlessCheng/codeforces-go
func main() {
	_i, buf := 1<<12, make([]byte, 1<<12)
	rc := func() byte {
		if _i == 1<<12 {
			syscall.Read(syscall.Stdin, buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	r64 := func() (x int64) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int64(b&15)
		}
		return
	}
	n, m, k := r(), r(), r64()
	p := make([]int, 2*max(n, m)+1)
	for i := range p {
		p[i] = -1
	}
	a := make([]int, n)
	diff := make([]int, n)
	for i := range a {
		a[i] = r()
		p[a[i]] = i
		diff[i] = m
	}
	b := make([]int, m)
	for i := range b {
		b[i] = r()
		if p[b[i]] >= 0 {
			diff[((p[b[i]]-i)%n+n)%n]--
		}
	}
	i, cntD, loop := 0, int64(0), 0
	for {
		cntD += int64(diff[i])
		loop++
		i = (i + m) % n
		if i == 0 {
			break
		}
	}
	ans := (k - 1) / cntD * int64(loop) * int64(m)
	k -= (k - 1) / cntD * cntD
	for ; k > int64(diff[i]); i = (i + m) % n {
		k -= int64(diff[i])
		ans += int64(m)
	}
	for j := 0; k > 0; j++ {
		if a[i] != b[j] {
			k--
		}
		ans++
		i = (i + 1) % n
	}
	Print(ans)
}

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

package main

import (
	. "fmt"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func main() {
	_i, buf := 1<<12, make([]byte, 1<<12)
	rc := func() byte {
		if _i == 1<<12 {
			os.Stdin.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	r64 := func() (x int64) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int64(b&15)
		}
		return
	}
	n, m, k := r(), r(), r64()
	p := make([]int, 2*max(n, m)+1)
	for i := range p {
		p[i] = -1
	}
	a := make([]int, n)
	diff := make([]int, n)
	for i := range a {
		a[i] = r()
		p[a[i]] = i
		diff[i] = m
	}
	b := make([]int, m)
	for i := range b {
		b[i] = r()
		if p[b[i]] >= 0 {
			diff[((p[b[i]]-i)%n+n)%n]--
		}
	}
	i, cntD, loop := 0, int64(0), 0
	for {
		cntD += int64(diff[i])
		loop++
		i = (i + m) % n
		if i == 0 {
			break
		}
	}
	ans := (k - 1) / cntD * int64(loop) * int64(m)
	k -= (k - 1) / cntD * cntD
	for ; k > int64(diff[i]); i = (i + m) % n {
		k -= int64(diff[i])
		ans += int64(m)
	}
	for j := 0; k > 0; j++ {
		if a[i] != b[j] {
			k--
		}
		ans++
		i = (i + 1) % n
	}
	Print(ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	p := [1e6+1]int{}
	for i := 1; i <= 1e6; i++ {
		p[i] = -1
	}
	var n, m, k, i, cntD, loop int64
	Fscan(in, &n, &m, &k)
	a := make([]int, n)
	diff := make([]int64, n)
	for i := range a {
		Fscan(in, &a[i])
		p[a[i]] = i
		diff[i] = m
	}
	b := make([]int, m)
	for i := range b {
		Fscan(in, &b[i])
		if p[b[i]] >= 0 {
			diff[(int64(p[b[i]]-i)%n+n)%n]--
		}
	}
	for {
		cntD += diff[i]
		loop++
		i = (i + m) % n
		if i == 0 {
			break
		}
	}
	ans := (k - 1) / cntD * loop * m
	k -= (k - 1) / cntD * cntD
	for ; k > diff[i]; i = (i + m) % n {
		k -= diff[i]
		ans += m
	}
	for j := 0; k > 0; j++ {
		if a[i] != b[j] {
			k--
		}
		ans++
		i = (i + 1) % n
	}
	Print(ans)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	line, _ := reader.ReadBytes('\n')

	var n, m int
	pos := readInt(line, 0, &n) + 1
	pos = readInt(line, pos, &m) + 1
	var k uint64
	readUint64(line, pos, &k)

	A := readNNums(reader, n)
	B := readNNums(reader, m)
	res := solve(A, B, int64(k))

	fmt.Println(res)
}

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

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

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

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

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

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

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

	return i
}

func extGcd(a, b int, x *int64, y *int64) int {
	if b == 0 {
		*x = 1
		*y = 0
		return a
	}
	var x1, y1 int64
	g := extGcd(b, a%b, &x1, &y1)
	*x = y1
	*y = x1 - int64(a/b)*y1

	return g
}

const MAX = 1000010

func solve(A, B []int, K int64) int64 {
	n := len(A)
	m := len(B)

	pa := make([]int, MAX)

	for i := 0; i < MAX; i++ {
		pa[i] = -1
	}

	for i, a := range A {
		pa[a] = i
	}
	var x, y int64

	g := extGcd(n, m, &x, &y)

	M := int64(m / g)

	all := make([]int64, 0, m)

	for i := 0; i < m; i++ {
		if pa[B[i]] < 0 || (i-pa[B[i]])%g != 0 {
			continue
		}
		kk := int64(i-pa[B[i]]) / int64(g)
		xx := x * kk
		xx = (xx%M + M) % M
		xx = xx*int64(n) + int64(pa[B[i]]) + 1
		all = append(all, xx)
	}

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

	L := int64(n) * M
	aa := L - int64(len(all))
	day := K / aa * L
	K %= aa
	if K == 0 {
		day -= L
		K = aa
	}

	check := func(x int64) bool {
		i := sort.Search(len(all), func(i int) bool {
			return all[i] > x
		})
		return x-int64(i) >= K
	}

	var l, r int64 = 0, L

	for l < r {
		mid := (l + r) / 2

		if check(mid) {
			r = mid
		} else {
			l = mid + 1
		}
	}

	return r + day
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1500B(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}

	var n, m, loop int
	var k, cntDiff int64
	Fscan(in, &n, &m, &k)
	a := make([]int, n)
	pos := make([]int, max(n, m)*2+1)
	for i := range pos {
		pos[i] = -1
	}
	diff := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
		pos[a[i]] = i
		diff[i] = m
	}
	b := make([]int, m)
	for i := range b {
		Fscan(in, &b[i])
		if pos[b[i]] >= 0 {
			diff[((pos[b[i]]-i)%n+n)%n]--
		}
	}

	i := 0
	for {
		cntDiff += int64(diff[i])
		loop++
		i = (i + m) % n
		if i == 0 {
			break
		}
	}
	ans := k / cntDiff * int64(loop) * int64(m)
	k -= k / cntDiff * cntDiff
	for ; k > int64(diff[i]); i = (i + m) % n {
		k -= int64(diff[i])
		ans += int64(m)
	}
	for j := 0; k > 0; j++ {
		if a[i] != b[j] {
			k--
		}
		ans++
		i = (i + 1) % n
	}
	Fprint(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	p := [1e6]int{}
	for i := 0; i < 1e6; i++ {
		p[i] = -1
	}
	var n, m, k, i, cntD, loop int
	Fscan(in, &n, &m, &k)
	a := make([]int, n)
	diff := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
		p[a[i]] = i
		diff[i] = m
	}
	b := make([]int, m)
	for i := range b {
		Fscan(in, &b[i])
		if p[b[i]] >= 0 {
			diff[((p[b[i]]-i)%n+n)%n]--
		}
	}
	for {
		cntD += diff[i]
		loop++
		i = (i + m) % n
		if i == 0 {
			break
		}
	}
	ans := (k - 1) / cntD * loop * m
	k -= (k - 1) / cntD * cntD
	for ; k > diff[i]; i = (i + m) % n {
		k -= diff[i]
		ans += m
	}
	for j := 0; k > 0; j++ {
		if a[i] != b[j] {
			k--
		}
		ans++
		i = (i + 1) % n
	}
	Print(ans)
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	line, _ := reader.ReadBytes('\n')

	var n, m int
	pos := readInt(line, 0, &n) + 1
	pos = readInt(line, pos, &m) + 1
	var k uint64
	readUint64(line, pos, &k)

	A := readNNums(reader, n)
	B := readNNums(reader, m)
	res := solve(A, B, int64(k))

	fmt.Println(res)
}

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

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

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

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

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

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

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

	return i
}

func extGcd(a, b int, x *int64, y *int64) int {
	if b == 0 {
		*x = 1
		*y = 0
		return a
	}
	var x1, y1 int64
	g := extGcd(b, a%b, &x1, &y1)
	*x = y1 - int64(a/b)*x1
	*y = x1

	return g
}

const MAX = 1000010

func solve(A, B []int, K int64) int64 {
	n := len(A)
	m := len(B)

	pa := make([]int, MAX)
	pb := make([]int, MAX)

	for i := 0; i < MAX; i++ {
		pa[i] = -1
		pb[i] = -1
	}

	for i, a := range A {
		pa[a] = i
	}

	for i, b := range B {
		pb[b] = i
	}

	var y int64
	g := extGcd(n, m, new(int64), &y)
	L := int64(n) * int64(m) / int64(g)
	var l int64 = 1
	var r int64 = 1e18
	var ans int64
	for l <= r {
		mid := (l + r) / 2
		var same int64
		quo := mid / L
		rem := mid % L
		for cur := 1; cur < MAX && same < mid; cur++ {
			if pa[cur] >= 0 && pb[cur] >= 0 && (pb[cur]-pa[cur])%g == 0 {
				same += quo
				tmp := y*int64(n)*int64((pb[cur]-pa[cur])/g) + int64(pa[cur])
				tmp %= L
				if tmp < 0 {
					tmp += L
				}
				if tmp < rem {
					same++
				}
			}
		}

		if mid-same >= K {
			r = mid - 1
			ans = mid
		} else {
			l = mid + 1
		}
	}
	return ans
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	line, _ := reader.ReadBytes('\n')

	var n, m int
	pos := readInt(line, 0, &n) + 1
	pos = readInt(line, pos, &m) + 1
	var k uint64
	readUint64(line, pos, &k)

	A := readNNums(reader, n)
	B := readNNums(reader, m)
	res := solve(A, B, int64(k))

	fmt.Println(res)
}

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

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

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

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

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

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

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

	return i
}

func extGcd(a, b int, x *int64, y *int64) int {
	if b == 0 {
		*x = 1
		*y = 0
		return a
	}
	var x1, y1 int64
	g := extGcd(b, a%b, &x1, &y1)
	*x = y1 - int64(a/b)*x1
	*y = x1

	return g
}

const MAX = 1000010

func solve(A, B []int, K int64) int64 {
	n := len(A)
	m := len(B)

	pa := make([]int, MAX)
	pb := make([]int, MAX)

	for i := 0; i < MAX; i++ {
		pa[i] = -1
		pb[i] = -1
	}

	for i, a := range A {
		pa[a] = i
	}

	for i, b := range B {
		pb[b] = i
	}

	var y int64
	g := extGcd(n, m, new(int64), &y)
	L := int64(n) * int64(m) / int64(g)
	var l int64 = 1
	var r int64 = 1e18

	for l < r {
		mid := (l + r) / 2
		var same int64
		quo := mid / L
		rem := mid % L
		for cur := 1; cur < MAX && same < mid; cur++ {
			if pa[cur] >= 0 && pb[cur] >= 0 && (pb[cur]-pa[cur])%g == 0 {
				same += quo
				tmp := y*int64(n)*int64((pb[cur]-pa[cur])/g) + int64(pa[cur])
				tmp %= L
				if tmp < 0 {
					tmp += L
				}
				if tmp < rem {
					same++
				}
			}
		}

		if mid-same >= K {
			r = mid
		} else {
			l = mid + 1
		}
	}
	return r
}


Let's denote correct match equation (we will denote it as CME) an equation $$$a + b = c$$$ there all integers $$$a$$$, $$$b$$$ and $$$c$$$ are greater than zero.For example, equations $$$2 + 2 = 4$$$ (||+||=||||) and $$$1 + 2 = 3$$$ (|+||=|||) are CME but equations $$$1 + 2 = 4$$$ (|+||=||||), $$$2 + 2 = 3$$$ (||+||=|||), and $$$0 + 1 = 1$$$ (+|=|) are not.Now, you have $$$n$$$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!For example, if $$$n = 2$$$, you can buy two matches and assemble |+|=||, and if $$$n = 5$$$ you can buy one match and assemble ||+|=|||.   Calculate the minimum number of matches which you have to buy for assembling CME.Note, that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. The only line of each query contains one integer $$$n$$$ ($$$2 \le n \le 10^9$$$) — the number of matches.

NoteThe first and second queries are explained in the statement.In the third query, you can assemble $$$1 + 3 = 4$$$ (|+|||=||||) without buying matches.In the fourth query, buy one match and assemble $$$2 + 4 = 6$$$ (||+||||=||||||).

package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	res := 0

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

	return res
}

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

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

	return res
}

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

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

	return s
}

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

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

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

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

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var q int

func main() {
	q = ReadInt()
	for i := 0; i < q; i++ {
		n := ReadInt()

		if n%2 == 0 {
			if n/2 == 1 {
				fmt.Println(2)
			} else {
				fmt.Println(0)
			}
		} else {
			fmt.Println(1)
		}
	}
}

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

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

package main
import ("fmt"
        "os"
        "strconv")
func main(){
    var n int
    fmt.Fscan(os.Stdin, &n)
    i:=0
    for i < n{
      var a int
      fmt.Fscan(os.Stdin, &a)
      if a == 2{
        fmt.Printf("2")
      } else{
        var s = strconv.Itoa(a%2)
        fmt.Printf(s)
      }
      fmt.Printf("\n")
      i++
    }
 }

package main

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

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

	var q, n int
	fmt.Fscanf(in, "%d\n", &q)
	for i := 0; i < q; i++ {
		fmt.Fscanf(in, "%d\n", &n)
		if n == 2 {
			fmt.Println(2)
		} else {
			fmt.Println(n & 1)
		}
	}
}

package main

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

func main() {
	var t, n int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(in, &n)
		if n == 2 {
			fmt.Println(2)
		} else {
			fmt.Println(n % 2)
		}
	}
}

// A. CME
/*
Let's denote correct match equation (we will denote it as CME)
an equation 𝑎+𝑏=𝑐 there all integers 𝑎, 𝑏 and 𝑐 are greater than zero.

For example, equations 2+2=4
(||+||=||||) and 1+2=3 (|+||=|||) are CME but equations 1+2=4 (|+||=||||),
2+2=3 (||+||=|||), and 0+1=1 (+|=|) are not.

Now, you have 𝑛 matches. You want to assemble a CME using all your matches.
Unfortunately, it is possible that you can't assemble the CME using all matches.
But you can buy some extra matches and then assemble CME!

For example, if 𝑛=2, you can buy two matches and assemble |+|=||, and if 𝑛=5
you can buy one match and assemble ||+|=|||.

Calculate the minimum number of matches which you have to buy for assembling CME.

Note, that you have to answer 𝑞 independent queries.

Input
The first line contains one integer 𝑞 (1≤𝑞≤100) — the number of queries.

The only line of each query contains one integer 𝑛 (2≤𝑛≤109 ) —
the number of matches.

Output
For each test case print one integer in single line — the minimum number
of matches which you have to buy for assembling CME.

Example
Input
4
2
5
8
11

Output
2
1
0
1

Note
The first and second queries are explained in the statement.

In the third query, you can assemble 1+3=4 (|+|||=||||) without buying matches.

In the fourth query, buy one match and assemble 2+4=6 (||+||||=||||||).
*/
package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	input, _ := reader.ReadString('\n')
	n, _ := strconv.Atoi(strings.TrimSpace(input))

	for ; n > 0; n-- {
		s, _ := reader.ReadString('\n')
		v, _ := strconv.Atoi(strings.TrimSpace(s))

		if v == 2 {
			fmt.Println(2)
		} else {
			fmt.Println(v & 1)
		}
	}
}

// A. CME
/*
Let's denote correct match equation (we will denote it as CME)
an equation 𝑎+𝑏=𝑐 there all integers 𝑎, 𝑏 and 𝑐 are greater than zero.

For example, equations 2+2=4
(||+||=||||) and 1+2=3 (|+||=|||) are CME but equations 1+2=4 (|+||=||||),
2+2=3 (||+||=|||), and 0+1=1 (+|=|) are not.

Now, you have 𝑛 matches. You want to assemble a CME using all your matches.
Unfortunately, it is possible that you can't assemble the CME using all matches.
But you can buy some extra matches and then assemble CME!

For example, if 𝑛=2, you can buy two matches and assemble |+|=||, and if 𝑛=5
you can buy one match and assemble ||+|=|||.

Calculate the minimum number of matches which you have to buy for assembling CME.

Note, that you have to answer 𝑞 independent queries.

Input
The first line contains one integer 𝑞 (1≤𝑞≤100) — the number of queries.

The only line of each query contains one integer 𝑛 (2≤𝑛≤109 ) —
the number of matches.

Output
For each test case print one integer in single line — the minimum number
of matches which you have to buy for assembling CME.

Example
Input
4
2
5
8
11

Output
2
1
0
1

Note
The first and second queries are explained in the statement.

In the third query, you can assemble 1+3=4 (|+|||=||||) without buying matches.

In the fourth query, buy one match and assemble 2+4=6 (||+||||=||||||).
*/
package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	input, _ := reader.ReadString('\n')
	n, _ := strconv.Atoi(strings.TrimSpace(input))

	for n > 0 {
		s, _ := reader.ReadString('\n')
		v, _ := strconv.Atoi(strings.TrimSpace(s))

		if v == 2 {
			fmt.Println(2)
		} else {
			fmt.Println(v & 1)
		}
		n--
	}
}

package main

import "fmt"

func main() {
	var q, n int64
	fmt.Scan(&q)
	for ; q > 0; q-- {
		fmt.Scan(&n)
		if n == 2 {
			fmt.Println(2)
		} else {
			fmt.Println(n % 2)
		}
	}
}

package main

import "fmt"

func main() {
	var q, num int
	_, _ = fmt.Scan(&q)
	for q > 0 {
		_, _ = fmt.Scan(&num)
		if num == 2 {
			fmt.Println(2)
		} else {
			fmt.Println(num % 2)
		}
		q--
	}
}

package main

import "fmt"

func main() {
	var q int
	fmt.Scan(&q)
	vec := make([]int64, q)
	for i := range vec {
		fmt.Scan(&vec[i])
	}
	for _, e := range vec {
		if e <= 3 {
			fmt.Println(4-e)
		} else {
			if e % 2 == 0 {
				fmt.Println(0)
			} else {
				fmt.Println(1)
			}
		}
	}
}

//A. Карточки
package main

import (
	"fmt"
)

func main() {
	var q uint32
	var n uint32
	var sl []uint32

	fmt.Scan(&q)

	for i := 1; uint32(i) <= q; i++ {
		fmt.Scan(&n)
		if n == 2 {
			sl = append(sl, 2)
			//fmt.Println(2)
		} else {
			sl = append(sl, n&1)
			//fmt.Println(n & 1) //1 - если четно, иначе 0
		}
	}
	for _, val := range sl {
		fmt.Println(val)
	}

}

//HOWDY! IT'S ME! A HARD BLACKISH DICK MOVE!
package main

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

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

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

//str := PrintlnInts(X...)

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

func main() {
	for q := ReadInt(); q > 0; q-- {
		n := ReadInt()
		ans := 2
		if n > 2 {
			ans = n % 2
		}
		fmt.Println(ans)
	}
}

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

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

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

func _gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return _gcd(b, a%b)
}

func gcd(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	gcd := args[0]
	for i := 1; i < len(args); i++ {
		gcd = _gcd(gcd, args[i])
	}
	return gcd
}

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

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

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

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

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

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

func readInt_64() int64 {
	return readIntNbits(64)
}

func ReadInt2_64() (int64, int64) {
	return readInt_64(), readInt_64()
}

func ReadInt3_64() (int64, int64, int64) {
	return readInt_64(), readInt_64(), readInt_64()
}

func readInt() int {
	return int(readIntNbits(32))
}

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

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

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

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

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

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

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

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

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

	return string(res)
}

package main

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

func main() {
    in := bufio.NewReader(os.Stdin)
    out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	tot := 0
	fmt.Fscan(in, &tot)
	for ; tot > 0; tot-- {
		n := 0
		fmt.Fscan(in, &n)
		if n == 2 {fmt.Fprint(out, n); fmt.Fprint(out, "\n"); continue}
		fmt.Fprint(out, n%2)
		fmt.Fprint(out, "\n")
	}
}

package main

import "fmt"

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

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

func main(){
	var q int
	fmt.Scanln(&q)
	for i:= 0;i < q ; i++ {
		var n int
		fmt.Scanln(&n)
		if n <=4{
			fmt.Println(4 - n)
		} else{
			if n%2 > 0{
				fmt.Println("1")
			} else{
				fmt.Println("0")
			}
		}
	}
}

package main
import ("fmt"
        "os"
        "strconv")
func main(){
    var n int
    fmt.Fscan(os.Stdin, &n)
    i:=0
    for i < n{
      var a int
      fmt.Fscan(os.Stdin, &a)
      if a == 2{
        fmt.Printf("2")
      } else{
        var s = strconv.Itoa(a%2)
        fmt.Printf(s)
      }
      i++
    }
 }