Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari?You can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem

The first line contains two integers n and k (1 ≤ n ≤ 1000; 2 ≤ k ≤ 5). Each of the next k lines contains integers 1, 2, ..., n in some order — description of the current permutation.

Print the length of the longest common subsequence.

NoteThe answer for the first test sample is subsequence [1, 2, 3].

package main

import (
	"bufio"
	"bytes"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"runtime/pprof"
	"strconv"
	"time"
	"unicode/utf8"
	"math/rand"
)

// ******************************** CODE STARTS ********************************

const (
)

var (
	n int
	k int
	array [][]int
	pos [][]int

	dp []int
	was []bool
)

func f(p int) int {
	if was[p] {
		return dp[p]
	}
	was[p] = true
	res := 0
	for j := p + 1; j < n; j++ {
		flag := true
		for i := 0; i < k; i++ {
			if pos[i][array[0][p]] >= pos[i][array[0][j]] {
				flag = false
				break
			}
		}
		if flag {
			res = maxInt(res, f(j))
		}
	}

	dp[p] = 1 + res
	return dp[p]
}

func solve() {
	n = readInt()
	k = readInt()
	array = make([][]int, k)
	pos = make([][]int, k)
	for j := 0; j < k; j++ {
		array[j] = make([]int, n)
		pos[j] = make([]int, n)
		for i := 0; i < n; i++ {
			array[j][i] = readInt() - 1
			pos[j][array[j][i]] = i
		}
	}

	dp = make([]int, n)
	was = make([]bool, n)
	best := 0
	for i := 0; i < n; i++ {
		best = maxInt(best, f(i))
	}
	printInt(best)
	printLine()
}

// ********************************* CODE ENDS *********************************

// IO.

var (
	scanner *Scanner
	writer  *bufio.Writer
	logger  *log.Logger
)

func main() {
	dbg := flag.Bool("dbg", false, "Equals true, if run is in debug mode.")
	opt := flag.Bool("opt", false, "Equals true, if run is in optimized mode.")
	flag.Parse()

	var (
		input  *os.File
		output *os.File
	)

	if *opt || *dbg {
		startTime := time.Now()
		defer func() {
			println(fmt.Sprintf("Time: %.5fs", time.Since(startTime).Seconds()))
		}()
		input, _ = os.Open("/home/outside/coding/workspace/go/io/input.txt")
		output, _ = os.Create("/home/outside/coding/workspace/go/io/output.txt")
		logger = log.New(output, "log: ", 0)
		if *dbg {
			cpuprofile, _ := os.Create("/home/outside/coding/workspace/go/io/cpuprofile.txt")
			pprof.StartCPUProfile(cpuprofile)
			defer cpuprofile.Close()
			defer pprof.StopCPUProfile()
		}
	} else {
		input = os.Stdin
		output = os.Stdout
		// input, _ = os.Open("")
		// output, _ = os.Create("")
	}
	defer input.Close()
	defer output.Close()

	scanner = NewScanner(input)
	scanner.Split(bufio.ScanWords)

	writer = bufio.NewWriter(output)
	defer writer.Flush()

	rand.Seed(int64(time.Now().Nanosecond()))
	solve()
}

// Read.

func readString() string {
	scanner.Scan()
	ans := scanner.Text()
	return ans
}

func readLine() string {
	scanner.Split(bufio.ScanLines)
	defer scanner.Split(bufio.ScanWords)
	return readString()
}

func readInt() int {
	ans, _ := strconv.ParseInt(readString(), 10, 0)
	return int(ans)
}

func readInt64() int64 {
	ans, _ := strconv.ParseInt(readString(), 10, 64)
	return ans
}

func readFloat64() float64 {
	ans, _ := strconv.ParseFloat(readString(), 64)
	return ans
}

// Write.

func printString(value string) {
	writer.WriteString(value)
}

func printLine() {
	printString("\n")
}

func printSpace() {
	printString(" ")
}

func printInt(value int) {
	printString(strconv.FormatInt(int64(value), 10))
}

func printInt64(value int64) {
	printString(strconv.FormatInt(value, 10))
}

func printFloat64(value float64) {
	printString(strconv.FormatFloat(value, 'f', 20, 64))
}

// Log.

func logln(value ...interface{}) {
	writer.Flush()
	logger.Println(value...)
}
func logf(format string, value ...interface{}) {
	writer.Flush()
	logger.Printf(format, value...)
}

// Tuple

type Tuple struct {
	a, b int
}

func (p Tuple) Equals(key Key) bool {
	return p.a == key.(Tuple).a
}

func (p Tuple) Less(key Key) bool {
	return p.a < key.(Tuple).a
}

type TupleSlice []Tuple

func (p TupleSlice) Len() int {
	return len(p)
}

func (p TupleSlice) Less(j, i int) bool {
	return p[j].a < p[i].a
}

func (p TupleSlice) Swap(j, i int) {
	p[j], p[i] = p[i], p[j]
}

// Min, max, abs.

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

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

func absInt(a int) int {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

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

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

func absInt64(a int64) int64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a < b {
		return a
	} else {
		return b
	}
}

func absFloat64(a float64) float64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

// Set Key interface implementations.

type Int int

func (p Int) Equals(key Key) bool {
	return int(p) == int(key.(Int))
}

func (p Int) Less(key Key) bool {
	return int(p) < int(key.(Int))
}

// Set.

type Key interface {
	Equals(key Key) bool
	Less(key Key) bool
}

type node struct {
	key   Key
	left  *node
	right *node
}

func newNode(key Key) *node {
	return &node{key, nil, nil}
}

type SplayTree struct {
	root *node
	tmp  *node
	len  int
}

func NewSplayTree() *SplayTree {
	return &SplayTree{nil, newNode(nil), 0}
}

func rotateLeft(x, p *node) {
	p.right = x.left
	x.left = p
}

func rotateRight(x, p *node) {
	p.left = x.right
	x.right = p
}

func (p *SplayTree) splay(x *node, key Key) *node {
	if x == nil {
		return nil
	}

	left := p.tmp
	right := p.tmp

	for {
		if key.Less(x.key) {
			y := x.left
			if y == nil {
				break
			}
			if key.Less(y.key) { // zig-zig
				rotateRight(y, x)
				x = y
				if x.left == nil {
					break
				}
			}
			// link right
			right.left = x
			right = x
			// move left
			x = x.left
		} else if x.key.Less(key) {
			y := x.right
			if y == nil {
				break
			}
			if y.key.Less(key) { // zig-zig
				rotateLeft(y, x)
				x = y
				if x.right == nil {
					break
				}
			}
			// link left
			left.right = x
			left = x
			// move right
			x = x.right
		} else {
			break
		}
	}

	left.right = x.left
	right.left = x.right
	x.left = p.tmp.right
	x.right = p.tmp.left

	return x
}

// left <= key < right
func (p *SplayTree) split(key Key) (left, right *node) {
	p.root = p.splay(p.root, key)
	if p.root.key.Equals(key) || p.root.key.Less(key) {
		right := p.root.right
		p.root.right = nil
		return p.root, right
	} else {
		left := p.root.left
		p.root.left = nil
		return left, p.root
	}
}

// keys from left tree must be less then keys from right tree
func (p *SplayTree) join(left, right *node) *node {
	if left == nil {
		return right
	} else if right == nil {
		return left
	}
	left = p.splay(left, right.key)
	left.right = right
	return left
}

type Set interface {
	Len() int
	Insert(key Key) error
	Find(key Key) bool
	Remove(key Key) error
}

func NewSet() Set {
	return Set(NewSplayTree())
}

func (p *SplayTree) Len() int {
	return p.len
}

func (p *SplayTree) Insert(key Key) error {
	if p.root == nil {
		p.root = newNode(key)
		p.len++
	} else {
		p.root = p.splay(p.root, key)
		if p.root.key.Equals(key) {
			return errors.New("Such key already exists")
		} else {
			left, right := p.split(key)
			p.root = newNode(key)
			p.root.left = left
			p.root.right = right
			p.len++
		}
	}
	return nil
}

func (p *SplayTree) Find(key Key) bool {
	if p.root == nil {
		return false
	}
	p.root = p.splay(p.root, key)
	return p.root.key.Equals(key)
}

func (p *SplayTree) Remove(key Key) error {
	p.root = p.splay(p.root, key)
	if p.root == nil || !p.root.key.Equals(key) {
		return errors.New("Such key doesn't exist")
	}
	p.root = p.join(p.split(key))
	return nil
}

// Copied scan.go
// Scanner provides a convenient interface for reading data such as
// a file of newline-delimited lines of text. Successive calls to
// the Scan method will step through the 'tokens' of a file, skipping
// the bytes between the tokens. The specification of a token is
// defined by a split function of type SplitFunc; the default split
// function breaks the input into lines with line termination stripped. Split
// functions are defined in this package for scanning a file into
// lines, bytes, UTF-8-encoded runes, and space-delimited words. The
// client may instead provide a custom split function.
//
// Scanning stops unrecoverably at EOF, the first I/O error, or a token too
// large to fit in the buffer. When a scan stops, the reader may have
// advanced arbitrarily far past the last token. Programs that need more
// control over error handling or large tokens, or must run sequential scans
// on a reader, should use bufio.Reader instead.
//
type Scanner struct {
	r            io.Reader // The reader provided by the client.
	split        SplitFunc // The function to split the tokens.
	maxTokenSize int       // Maximum size of a token; modified by tests.
	token        []byte    // Last token returned by split.
	buf          []byte    // Buffer used as argument to split.
	start        int       // First non-processed byte in buf.
	end          int       // End of data in buf.
	err          error     // Sticky error.
}

// SplitFunc is the signature of the split function used to tokenize the
// input. The arguments are an initial substring of the remaining unprocessed
// data and a flag, atEOF, that reports whether the Reader has no more data
// to give. The return values are the number of bytes to advance the input
// and the next token to return to the user, plus an error, if any. If the
// data does not yet hold a complete token, for instance if it has no newline
// while scanning lines, SplitFunc can return (0, nil, nil) to signal the
// Scanner to read more data into the slice and try again with a longer slice
// starting at the same point in the input.
//
// If the returned error is non-nil, scanning stops and the error
// is returned to the client.
//
// The function is never called with an empty data slice unless atEOF
// is true. If atEOF is true, however, data may be non-empty and,
// as always, holds unprocessed text.
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

// Errors returned by Scanner.
var (
	ErrTooLong         = errors.New("bufio.Scanner: token too long")
	ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
	ErrAdvanceTooFar   = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
)

const (
	// Maximum size used to buffer a token. The actual maximum token size
	// may be smaller as the buffer may need to include, for instance, a newline.
	MaxScanTokenSize = 1 << 20
)

// NewScanner returns a new Scanner to read from r.
// The split function defaults to ScanLines.
func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        ScanLines,
		maxTokenSize: MaxScanTokenSize,
		buf:          make([]byte, 4096), // Plausible starting size; needn't be large.
	}
}

// Err returns the first non-EOF error that was encountered by the Scanner.
func (s *Scanner) Err() error {
	if s.err == io.EOF {
		return nil
	}
	return s.err
}

// Bytes returns the most recent token generated by a call to Scan.
// The underlying array may point to data that will be overwritten
// by a subsequent call to Scan. It does no allocation.
func (s *Scanner) Bytes() []byte {
	return s.token
}

// Text returns the most recent token generated by a call to Scan
// as a newly allocated string holding its bytes.
func (s *Scanner) Text() string {
	return string(s.token)
}

// Scan advances the Scanner to the next token, which will then be
// available through the Bytes or Text method. It returns false when the
// scan stops, either by reaching the end of the input or an error.
// After Scan returns false, the Err method will return any error that
// occurred during scanning, except that if it was io.EOF, Err
// will return nil.
func (s *Scanner) Scan() bool {
	// Loop until we have a token.
	for {
		// See if we can get a token with what we already have.
		if s.end > s.start {
			advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
			if err != nil {
				s.setErr(err)
				return false
			}
			if !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				return true
			}
		}
		// We cannot generate a token with what we are holding.
		// If we've already hit EOF or an I/O error, we are done.
		if s.err != nil {
			// Shut it down.
			s.start = 0
			s.end = 0
			return false
		}
		// Must read more data.
		// First, shift data to beginning of buffer if there's lots of empty space
		// or space is neded.
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		// Is the buffer full? If so, resize.
		if s.end == len(s.buf) {
			if len(s.buf) >= s.maxTokenSize {
				s.setErr(ErrTooLong)
				return false
			}
			newSize := len(s.buf) * 2
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		// Finally we can read some input. Make sure we don't get stuck with
		// a misbehaving Reader. Officially we don't need to do this, but let's
		// be extra careful: Scanner is for safe, simple jobs.
		for loop := 0; ; {
			n, err := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if err != nil {
				s.setErr(err)
				break
			}
			if n > 0 {
				break
			}
			loop++
			if loop > 100 {
				s.setErr(io.ErrNoProgress)
				break
			}
		}
	}
}

// advance consumes n bytes of the buffer. It reports whether the advance was legal.
func (s *Scanner) advance(n int) bool {
	if n < 0 {
		s.setErr(ErrNegativeAdvance)
		return false
	}
	if n > s.end-s.start {
		s.setErr(ErrAdvanceTooFar)
		return false
	}
	s.start += n
	return true
}

// setErr records the first error encountered.
func (s *Scanner) setErr(err error) {
	if s.err == nil || s.err == io.EOF {
		s.err = err
	}
}

// Split sets the split function for the Scanner. If called, it must be
// called before Scan. The default split function is ScanLines.
func (s *Scanner) Split(split SplitFunc) {
	s.split = split
}

// Split functions

// ScanBytes is a split function for a Scanner that returns each byte as a token.
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	return 1, data[0:1], nil
}

var errorRune = []byte(string(utf8.RuneError))

// ScanRunes is a split function for a Scanner that returns each
// UTF-8-encoded rune as a token. The sequence of runes returned is
// equivalent to that from a range loop over the input as a string, which
// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd".
// Because of the Scan interface, this makes it impossible for the client to
// distinguish correctly encoded replacement runes from encoding errors.
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}

	// Fast path 1: ASCII.
	if data[0] < utf8.RuneSelf {
		return 1, data[0:1], nil
	}

	// Fast path 2: Correct UTF-8 decode without error.
	_, width := utf8.DecodeRune(data)
	if width > 1 {
		// It's a valid encoding. Width cannot be one for a correctly encoded
		// non-ASCII rune.
		return width, data[0:width], nil
	}

	// We know it's an error: we have width==1 and implicitly r==utf8.RuneError.
	// Is the error because there wasn't a full rune to be decoded?
	// FullRune distinguishes correctly between erroneous and incomplete encodings.
	if !atEOF && !utf8.FullRune(data) {
		// Incomplete; get more bytes.
		return 0, nil, nil
	}

	// We have a real UTF-8 encoding error. Return a properly encoded error rune
	// but advance only one byte. This matches the behavior of a range loop over
	// an incorrectly encoded string.
	return 1, errorRune, nil
}

// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[0 : len(data)-1]
	}
	return data
}

// ScanLines is a split function for a Scanner that returns each line of
// text, stripped of any trailing end-of-line marker. The returned line may
// be empty. The end-of-line marker is one optional carriage return followed
// by one mandatory newline. In regular expression notation, it is `\r?\n`.
// The last non-empty line of input will be returned even if it has no
// newline.
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\n'); i >= 0 {
		// We have a full newline-terminated line.
		return i + 1, dropCR(data[0:i]), nil
	}
	// If we're at EOF, we have a final, non-terminated line. Return it.
	if atEOF {
		return len(data), dropCR(data), nil
	}
	// Request more data.
	return 0, nil, nil
}

// isSpace reports whether the character is a Unicode white space character.
// We avoid dependency on the unicode package, but check validity of the implementation
// in the tests.
func isSpace(r rune) bool {
	if r <= '\u00FF' {
		// Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
		switch r {
		case ' ', '\t', '\n', '\v', '\f', '\r':
			return true
		case '\u0085', '\u00A0':
			return true
		}
		return false
	}
	// High-valued ones.
	if '\u2000' <= r && r <= '\u200a' {
		return true
	}
	switch r {
	case '\u1680', '\u180e', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
		return true
	}
	return false
}

// ScanWords is a split function for a Scanner that returns each
// space-separated word of text, with surrounding spaces deleted. It will
// never return an empty string. The definition of space is set by
// unicode.IsSpace.
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	// Skip leading spaces.
	start := 0
	for width := 0; start < len(data); start += width {
		var r rune
		r, width = utf8.DecodeRune(data[start:])
		if !isSpace(r) {
			break
		}
	}
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	// Scan until space, marking end of word.
	for width, i := 0, start; i < len(data); i += width {
		var r rune
		r, width = utf8.DecodeRune(data[i:])
		if isSpace(r) {
			return i + width, data[start:i], nil
		}
	}
	// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	// Request more data.
	return 0, nil, nil
}

package main

import (
	"bufio"
	"bytes"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"runtime/pprof"
	"strconv"
	"time"
	"unicode/utf8"
	"math/rand"
)

// ******************************** CODE STARTS ********************************

const (
)

var (
	n int
	k int
	array [][]int
	pos [][]int

	dp []int
	was []bool
)

func f(p int) int {
	if was[p] {
		return dp[p]
	}
	was[p] = true
	res := 0
	for j := p + 1; j < n; j++ {
		flag := true
		for i := 0; i < k; i++ {
			if pos[i][array[0][p]] >= pos[i][array[i][j]] {
				flag = false
				break
			}
		}
		if flag {
			res = maxInt(res, f(j))
		}
	}

	dp[p] = 1 + res
	return dp[p]
}

func solve() {
	n = readInt()
	k = readInt()
	array = make([][]int, k)
	pos = make([][]int, k)
	for j := 0; j < k; j++ {
		array[j] = make([]int, n)
		pos[j] = make([]int, n)
		for i := 0; i < n; i++ {
			array[j][i] = readInt() - 1
			pos[j][array[j][i]] = i
		}
	}

	dp = make([]int, n)
	was = make([]bool, n)
	best := 0
	for i := 0; i < n; i++ {
		best = maxInt(best, f(i))
	}
	printInt(best)
	printLine()
}

// ********************************* CODE ENDS *********************************

// IO.

var (
	scanner *Scanner
	writer  *bufio.Writer
	logger  *log.Logger
)

func main() {
	dbg := flag.Bool("dbg", false, "Equals true, if run is in debug mode.")
	opt := flag.Bool("opt", false, "Equals true, if run is in optimized mode.")
	flag.Parse()

	var (
		input  *os.File
		output *os.File
	)

	if *opt || *dbg {
		startTime := time.Now()
		defer func() {
			println(fmt.Sprintf("Time: %.5fs", time.Since(startTime).Seconds()))
		}()
		input, _ = os.Open("/home/outside/coding/workspace/go/io/input.txt")
		output, _ = os.Create("/home/outside/coding/workspace/go/io/output.txt")
		logger = log.New(output, "log: ", 0)
		if *dbg {
			cpuprofile, _ := os.Create("/home/outside/coding/workspace/go/io/cpuprofile.txt")
			pprof.StartCPUProfile(cpuprofile)
			defer cpuprofile.Close()
			defer pprof.StopCPUProfile()
		}
	} else {
		input = os.Stdin
		output = os.Stdout
		// input, _ = os.Open("")
		// output, _ = os.Create("")
	}
	defer input.Close()
	defer output.Close()

	scanner = NewScanner(input)
	scanner.Split(bufio.ScanWords)

	writer = bufio.NewWriter(output)
	defer writer.Flush()

	rand.Seed(int64(time.Now().Nanosecond()))
	solve()
}

// Read.

func readString() string {
	scanner.Scan()
	ans := scanner.Text()
	return ans
}

func readLine() string {
	scanner.Split(bufio.ScanLines)
	defer scanner.Split(bufio.ScanWords)
	return readString()
}

func readInt() int {
	ans, _ := strconv.ParseInt(readString(), 10, 0)
	return int(ans)
}

func readInt64() int64 {
	ans, _ := strconv.ParseInt(readString(), 10, 64)
	return ans
}

func readFloat64() float64 {
	ans, _ := strconv.ParseFloat(readString(), 64)
	return ans
}

// Write.

func printString(value string) {
	writer.WriteString(value)
}

func printLine() {
	printString("\n")
}

func printSpace() {
	printString(" ")
}

func printInt(value int) {
	printString(strconv.FormatInt(int64(value), 10))
}

func printInt64(value int64) {
	printString(strconv.FormatInt(value, 10))
}

func printFloat64(value float64) {
	printString(strconv.FormatFloat(value, 'f', 20, 64))
}

// Log.

func logln(value ...interface{}) {
	writer.Flush()
	logger.Println(value...)
}
func logf(format string, value ...interface{}) {
	writer.Flush()
	logger.Printf(format, value...)
}

// Tuple

type Tuple struct {
	a, b int
}

func (p Tuple) Equals(key Key) bool {
	return p.a == key.(Tuple).a
}

func (p Tuple) Less(key Key) bool {
	return p.a < key.(Tuple).a
}

type TupleSlice []Tuple

func (p TupleSlice) Len() int {
	return len(p)
}

func (p TupleSlice) Less(j, i int) bool {
	return p[j].a < p[i].a
}

func (p TupleSlice) Swap(j, i int) {
	p[j], p[i] = p[i], p[j]
}

// Min, max, abs.

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

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

func absInt(a int) int {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

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

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

func absInt64(a int64) int64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a < b {
		return a
	} else {
		return b
	}
}

func absFloat64(a float64) float64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

// Set Key interface implementations.

type Int int

func (p Int) Equals(key Key) bool {
	return int(p) == int(key.(Int))
}

func (p Int) Less(key Key) bool {
	return int(p) < int(key.(Int))
}

// Set.

type Key interface {
	Equals(key Key) bool
	Less(key Key) bool
}

type node struct {
	key   Key
	left  *node
	right *node
}

func newNode(key Key) *node {
	return &node{key, nil, nil}
}

type SplayTree struct {
	root *node
	tmp  *node
	len  int
}

func NewSplayTree() *SplayTree {
	return &SplayTree{nil, newNode(nil), 0}
}

func rotateLeft(x, p *node) {
	p.right = x.left
	x.left = p
}

func rotateRight(x, p *node) {
	p.left = x.right
	x.right = p
}

func (p *SplayTree) splay(x *node, key Key) *node {
	if x == nil {
		return nil
	}

	left := p.tmp
	right := p.tmp

	for {
		if key.Less(x.key) {
			y := x.left
			if y == nil {
				break
			}
			if key.Less(y.key) { // zig-zig
				rotateRight(y, x)
				x = y
				if x.left == nil {
					break
				}
			}
			// link right
			right.left = x
			right = x
			// move left
			x = x.left
		} else if x.key.Less(key) {
			y := x.right
			if y == nil {
				break
			}
			if y.key.Less(key) { // zig-zig
				rotateLeft(y, x)
				x = y
				if x.right == nil {
					break
				}
			}
			// link left
			left.right = x
			left = x
			// move right
			x = x.right
		} else {
			break
		}
	}

	left.right = x.left
	right.left = x.right
	x.left = p.tmp.right
	x.right = p.tmp.left

	return x
}

// left <= key < right
func (p *SplayTree) split(key Key) (left, right *node) {
	p.root = p.splay(p.root, key)
	if p.root.key.Equals(key) || p.root.key.Less(key) {
		right := p.root.right
		p.root.right = nil
		return p.root, right
	} else {
		left := p.root.left
		p.root.left = nil
		return left, p.root
	}
}

// keys from left tree must be less then keys from right tree
func (p *SplayTree) join(left, right *node) *node {
	if left == nil {
		return right
	} else if right == nil {
		return left
	}
	left = p.splay(left, right.key)
	left.right = right
	return left
}

type Set interface {
	Len() int
	Insert(key Key) error
	Find(key Key) bool
	Remove(key Key) error
}

func NewSet() Set {
	return Set(NewSplayTree())
}

func (p *SplayTree) Len() int {
	return p.len
}

func (p *SplayTree) Insert(key Key) error {
	if p.root == nil {
		p.root = newNode(key)
		p.len++
	} else {
		p.root = p.splay(p.root, key)
		if p.root.key.Equals(key) {
			return errors.New("Such key already exists")
		} else {
			left, right := p.split(key)
			p.root = newNode(key)
			p.root.left = left
			p.root.right = right
			p.len++
		}
	}
	return nil
}

func (p *SplayTree) Find(key Key) bool {
	if p.root == nil {
		return false
	}
	p.root = p.splay(p.root, key)
	return p.root.key.Equals(key)
}

func (p *SplayTree) Remove(key Key) error {
	p.root = p.splay(p.root, key)
	if p.root == nil || !p.root.key.Equals(key) {
		return errors.New("Such key doesn't exist")
	}
	p.root = p.join(p.split(key))
	return nil
}

// Copied scan.go
// Scanner provides a convenient interface for reading data such as
// a file of newline-delimited lines of text. Successive calls to
// the Scan method will step through the 'tokens' of a file, skipping
// the bytes between the tokens. The specification of a token is
// defined by a split function of type SplitFunc; the default split
// function breaks the input into lines with line termination stripped. Split
// functions are defined in this package for scanning a file into
// lines, bytes, UTF-8-encoded runes, and space-delimited words. The
// client may instead provide a custom split function.
//
// Scanning stops unrecoverably at EOF, the first I/O error, or a token too
// large to fit in the buffer. When a scan stops, the reader may have
// advanced arbitrarily far past the last token. Programs that need more
// control over error handling or large tokens, or must run sequential scans
// on a reader, should use bufio.Reader instead.
//
type Scanner struct {
	r            io.Reader // The reader provided by the client.
	split        SplitFunc // The function to split the tokens.
	maxTokenSize int       // Maximum size of a token; modified by tests.
	token        []byte    // Last token returned by split.
	buf          []byte    // Buffer used as argument to split.
	start        int       // First non-processed byte in buf.
	end          int       // End of data in buf.
	err          error     // Sticky error.
}

// SplitFunc is the signature of the split function used to tokenize the
// input. The arguments are an initial substring of the remaining unprocessed
// data and a flag, atEOF, that reports whether the Reader has no more data
// to give. The return values are the number of bytes to advance the input
// and the next token to return to the user, plus an error, if any. If the
// data does not yet hold a complete token, for instance if it has no newline
// while scanning lines, SplitFunc can return (0, nil, nil) to signal the
// Scanner to read more data into the slice and try again with a longer slice
// starting at the same point in the input.
//
// If the returned error is non-nil, scanning stops and the error
// is returned to the client.
//
// The function is never called with an empty data slice unless atEOF
// is true. If atEOF is true, however, data may be non-empty and,
// as always, holds unprocessed text.
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

// Errors returned by Scanner.
var (
	ErrTooLong         = errors.New("bufio.Scanner: token too long")
	ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
	ErrAdvanceTooFar   = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
)

const (
	// Maximum size used to buffer a token. The actual maximum token size
	// may be smaller as the buffer may need to include, for instance, a newline.
	MaxScanTokenSize = 1 << 20
)

// NewScanner returns a new Scanner to read from r.
// The split function defaults to ScanLines.
func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        ScanLines,
		maxTokenSize: MaxScanTokenSize,
		buf:          make([]byte, 4096), // Plausible starting size; needn't be large.
	}
}

// Err returns the first non-EOF error that was encountered by the Scanner.
func (s *Scanner) Err() error {
	if s.err == io.EOF {
		return nil
	}
	return s.err
}

// Bytes returns the most recent token generated by a call to Scan.
// The underlying array may point to data that will be overwritten
// by a subsequent call to Scan. It does no allocation.
func (s *Scanner) Bytes() []byte {
	return s.token
}

// Text returns the most recent token generated by a call to Scan
// as a newly allocated string holding its bytes.
func (s *Scanner) Text() string {
	return string(s.token)
}

// Scan advances the Scanner to the next token, which will then be
// available through the Bytes or Text method. It returns false when the
// scan stops, either by reaching the end of the input or an error.
// After Scan returns false, the Err method will return any error that
// occurred during scanning, except that if it was io.EOF, Err
// will return nil.
func (s *Scanner) Scan() bool {
	// Loop until we have a token.
	for {
		// See if we can get a token with what we already have.
		if s.end > s.start {
			advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
			if err != nil {
				s.setErr(err)
				return false
			}
			if !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				return true
			}
		}
		// We cannot generate a token with what we are holding.
		// If we've already hit EOF or an I/O error, we are done.
		if s.err != nil {
			// Shut it down.
			s.start = 0
			s.end = 0
			return false
		}
		// Must read more data.
		// First, shift data to beginning of buffer if there's lots of empty space
		// or space is neded.
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		// Is the buffer full? If so, resize.
		if s.end == len(s.buf) {
			if len(s.buf) >= s.maxTokenSize {
				s.setErr(ErrTooLong)
				return false
			}
			newSize := len(s.buf) * 2
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		// Finally we can read some input. Make sure we don't get stuck with
		// a misbehaving Reader. Officially we don't need to do this, but let's
		// be extra careful: Scanner is for safe, simple jobs.
		for loop := 0; ; {
			n, err := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if err != nil {
				s.setErr(err)
				break
			}
			if n > 0 {
				break
			}
			loop++
			if loop > 100 {
				s.setErr(io.ErrNoProgress)
				break
			}
		}
	}
}

// advance consumes n bytes of the buffer. It reports whether the advance was legal.
func (s *Scanner) advance(n int) bool {
	if n < 0 {
		s.setErr(ErrNegativeAdvance)
		return false
	}
	if n > s.end-s.start {
		s.setErr(ErrAdvanceTooFar)
		return false
	}
	s.start += n
	return true
}

// setErr records the first error encountered.
func (s *Scanner) setErr(err error) {
	if s.err == nil || s.err == io.EOF {
		s.err = err
	}
}

// Split sets the split function for the Scanner. If called, it must be
// called before Scan. The default split function is ScanLines.
func (s *Scanner) Split(split SplitFunc) {
	s.split = split
}

// Split functions

// ScanBytes is a split function for a Scanner that returns each byte as a token.
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	return 1, data[0:1], nil
}

var errorRune = []byte(string(utf8.RuneError))

// ScanRunes is a split function for a Scanner that returns each
// UTF-8-encoded rune as a token. The sequence of runes returned is
// equivalent to that from a range loop over the input as a string, which
// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd".
// Because of the Scan interface, this makes it impossible for the client to
// distinguish correctly encoded replacement runes from encoding errors.
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}

	// Fast path 1: ASCII.
	if data[0] < utf8.RuneSelf {
		return 1, data[0:1], nil
	}

	// Fast path 2: Correct UTF-8 decode without error.
	_, width := utf8.DecodeRune(data)
	if width > 1 {
		// It's a valid encoding. Width cannot be one for a correctly encoded
		// non-ASCII rune.
		return width, data[0:width], nil
	}

	// We know it's an error: we have width==1 and implicitly r==utf8.RuneError.
	// Is the error because there wasn't a full rune to be decoded?
	// FullRune distinguishes correctly between erroneous and incomplete encodings.
	if !atEOF && !utf8.FullRune(data) {
		// Incomplete; get more bytes.
		return 0, nil, nil
	}

	// We have a real UTF-8 encoding error. Return a properly encoded error rune
	// but advance only one byte. This matches the behavior of a range loop over
	// an incorrectly encoded string.
	return 1, errorRune, nil
}

// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[0 : len(data)-1]
	}
	return data
}

// ScanLines is a split function for a Scanner that returns each line of
// text, stripped of any trailing end-of-line marker. The returned line may
// be empty. The end-of-line marker is one optional carriage return followed
// by one mandatory newline. In regular expression notation, it is `\r?\n`.
// The last non-empty line of input will be returned even if it has no
// newline.
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\n'); i >= 0 {
		// We have a full newline-terminated line.
		return i + 1, dropCR(data[0:i]), nil
	}
	// If we're at EOF, we have a final, non-terminated line. Return it.
	if atEOF {
		return len(data), dropCR(data), nil
	}
	// Request more data.
	return 0, nil, nil
}

// isSpace reports whether the character is a Unicode white space character.
// We avoid dependency on the unicode package, but check validity of the implementation
// in the tests.
func isSpace(r rune) bool {
	if r <= '\u00FF' {
		// Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
		switch r {
		case ' ', '\t', '\n', '\v', '\f', '\r':
			return true
		case '\u0085', '\u00A0':
			return true
		}
		return false
	}
	// High-valued ones.
	if '\u2000' <= r && r <= '\u200a' {
		return true
	}
	switch r {
	case '\u1680', '\u180e', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
		return true
	}
	return false
}

// ScanWords is a split function for a Scanner that returns each
// space-separated word of text, with surrounding spaces deleted. It will
// never return an empty string. The definition of space is set by
// unicode.IsSpace.
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	// Skip leading spaces.
	start := 0
	for width := 0; start < len(data); start += width {
		var r rune
		r, width = utf8.DecodeRune(data[start:])
		if !isSpace(r) {
			break
		}
	}
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	// Scan until space, marking end of word.
	for width, i := 0, start; i < len(data); i += width {
		var r rune
		r, width = utf8.DecodeRune(data[i:])
		if isSpace(r) {
			return i + width, data[start:i], nil
		}
	}
	// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	// Request more data.
	return 0, nil, nil
}


When little Petya grew up and entered the university, he started to take part in АСМ contests. Later he realized that he doesn't like how the АСМ contests are organised: the team could only have three members (and he couldn't take all his friends to the competitions and distribute the tasks between the team members efficiently), so he decided to organize his own contests PFAST Inc. — Petr and Friends Are Solving Tasks Corporation. PFAST Inc. rules allow a team to have unlimited number of members.To make this format of contests popular he organised his own tournament. To create the team he will prepare for the contest organised by the PFAST Inc. rules, he chose several volunteers (up to 16 people) and decided to compile a team from them. Petya understands perfectly that if a team has two people that don't get on well, then the team will perform poorly. Put together a team with as many players as possible given that all players should get on well with each other.

The first line contains two integer numbers n (1 ≤ n ≤ 16) — the number of volunteers, and m () — the number of pairs that do not get on. Next n lines contain the volunteers' names (each name is a non-empty string consisting of no more than 10 uppercase and/or lowercase Latin letters). Next m lines contain two names — the names of the volunteers who do not get on. The names in pair are separated with a single space. Each pair of volunteers who do not get on occurs exactly once. The strings are case-sensitive. All n names are distinct.

The first output line should contain the single number k — the number of people in the sought team. Next k lines should contain the names of the sought team's participants in the lexicographical order. If there are several variants to solve the problem, print any of them. Petya might not be a member of the sought team.

package main

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

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

var isEdge [][]bool
var n int

func feasible(x int) bool {
  us := []int{}
  pos := 0
  for x != 0 {
    if x & 1 == 1 {
      us = append(us, pos)
    }
    x >>= 1
    pos++
  }
  for i, u := range us {
    for j := i-1; j >= 0; j-- {
      if isEdge[u][us[j]] {
        return false
      }
    }
  }
  return true
}

func count(x int) int {
  result := 0
  for x != 0 {
    if x & 1 == 1 {
      result++
    }
    x >>= 1
  }
  return result
}

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

  n, m := getI(), getI()
  isEdge = make([][]bool, n)
  for u := 0; u < n; u++ {
    isEdge[u] = make([]bool, n)
  }
  nameToI := map[string]int{}
  names := make([]string, n)
  for u := 0; u < n; u++ {
    pos := n-u-1
    s := getS()
    nameToI[s] = pos
    names[pos] = s
  }
  for i := 0; i < m; i++ {
    u, v := nameToI[getS()], nameToI[getS()]
    isEdge[u][v] = true
    isEdge[v][u] = true
  }
  result := 0
  best := -1
  for x := (1 << uint(n)) - 1; x >= 0; x-- {
    if feasible(x) && count(x) > result {
      result = count(x)
      best = x
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
  pos := 0
  x := best
  sorted := []string{}
  for x != 0 {
    if x & 1 == 1 {
      sorted = append(sorted, names[pos])
    }
    x >>= 1
    pos++
  }
  sort.Strings(sorted)
  for _, s := range sorted {
    writer.WriteString(fmt.Sprintf("%s\n", s))
  }
}

package main

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

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

var isEdge [][]bool
var n int

func feasible(x int) bool {
  us := []int{}
  pos := 0
  for x != 0 {
    if x & 1 == 1 {
      us = append(us, pos)
    }
    x >>= 1
    pos++
  }
  for i, u := range us {
    for j := i-1; j >= 0; j-- {
      if isEdge[u][us[j]] {
        return false
      }
    }
  }
  return true
}

func count(x int) int {
  result := 0
  for x != 0 {
    if x & 1 == 1 {
      result++
    }
    x >>= 1
  }
  return result
}

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

  n, m := getI(), getI()
  isEdge = make([][]bool, n)
  for u := 0; u < n; u++ {
    isEdge[u] = make([]bool, n)
  }
  nameToI := map[string]int{}
  names := make([]string, n)
  for u := 0; u < n; u++ {
    pos := n-u-1
    s := getS()
    nameToI[s] = pos
    names[pos] = s
  }
  for i := 0; i < m; i++ {
    u, v := nameToI[getS()], nameToI[getS()]
    isEdge[u][v] = true
  }
  result := 0
  best := -1
  for x := (1 << uint(n)) - 1; x >= 0; x-- {
    if feasible(x) && count(x) > result {
      result = count(x)
      best = x
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
  pos := 0
  x := best
  sorted := []string{}
  for x != 0 {
    if x & 1 == 1 {
      sorted = append(sorted, names[pos])
    }
    x >>= 1
    pos++
  }
  sort.Strings(sorted)
  for _, s := range sorted {
    writer.WriteString(fmt.Sprintf("%s\n", s))
  }
}


Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first.Consider the 2D plane. There is a token which is initially at $$$(0,0)$$$. In one move a player must increase either the $$$x$$$ coordinate or the $$$y$$$ coordinate of the token by exactly $$$k$$$. In doing so, the player must ensure that the token stays within a (Euclidean) distance $$$d$$$ from $$$(0,0)$$$.In other words, if after a move the coordinates of the token are $$$(p,q)$$$, then $$$p^2 + q^2 \leq d^2$$$ must hold.The game ends when a player is unable to make a move. It can be shown that the game will end in a finite number of moves. If both players play optimally, determine who will win.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The only line of each test case contains two space separated integers $$$d$$$ ($$$1 \leq d \leq 10^5$$$) and $$$k$$$ ($$$1 \leq k \leq d$$$).

For each test case, if Ashish wins the game, print "Ashish", otherwise print "Utkarsh" (without the quotes).

NoteIn the first test case, one possible sequence of moves can be$$$(0, 0) \xrightarrow{\text{Ashish }} (0, 1) \xrightarrow{\text{Utkarsh }} (0, 2)$$$.Ashish has no moves left, so Utkarsh wins.

package main

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

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

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

func solveA() {
	var n int
	scanf("%d\n", &n)
	ans := 0
	if n % 2 == 0 {
		if n >= 4 {
			ans = 2
		} else if n == 2 {
			ans = 1
		}
	} else {
		if n >= 5 {
			ans = 3
		} else if n == 3 {
			ans = 2
		}
	}
	printf("%d\n", ans)
}

type point struct {
	left int
	right int
}

func solveB() {
	var n, q int
	scanf("%d %d\n", &n, &q)
	var s string
	scanf("%s\n", &s)
	var P0, P1 point = point{n, -1}, point{n, -1}
	for i := 0; i < n; i++ {
		if s[i] == '0' {
			P0.right = i
		} else {
			P1.right = i
		}
	}

	for i := n - 1; i >= 0; i-- {
		if s[i] == '0' {
			P0.left = i
		} else {
			P1.left = i
		}
	}

	for ; q > 0; q-- {
		var l, r int
		scanf("%d %d\n", &l, &r)
		l--
		r--
		ans := "NO"
		if (s[l] == '0' && P0.left < l || s[l] == '1' && P1.left < l) ||
			(s[r] == '0' && P0.right > r || s[r] == '1' && P1.right > r) {
			ans = "YES"
		}

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

func sqr(x int64) float64 {
	return float64(x) * float64(x)
}

func solveD() {
	var d, k int64
	scanf("%d %d\n", &d, &k)
	ans := "Ashish"
	z := int64(math.Sqrt(0.5 * sqr(d) / sqr(k)))
	if k * k * (z * z + (z + 1) * (z + 1)) > d * d {
		ans = "Utkarsh"
	}
	printf("%s\n", ans)
}

func main() {
	defer writer.Flush()
	var t int
	scanf("%d\n", &t)
	for ; t > 0; t-- {
		solveD()
	}
}

package main
import (
	"os"
	"fmt"
	"bufio"
)
var rd = bufio.NewReader(os.Stdin)
func sqr(x int64) int64 {
	return x * x
}
func ok(x, y, d, k int64) bool {
	return sqr(k * x) + sqr(k * y) <= sqr(d)
}
func main() {
	q := 0
	fmt.Fscan(rd, &q)
	for t := 0; t < q; t++ {
		var d, k, cur int64
		fmt.Fscan(rd, &d, &k)
		for ok(cur + 1, cur + 1, d, k) {
			cur++
		}
		if ok(cur + 1, cur, d, k) {
			fmt.Println("Ashish")
		} else {
			fmt.Println("Utkarsh")
		}
	}
}

package main

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

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

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

func solveA() {
	var n int
	scanf("%d\n", &n)
	ans := 0
	if n % 2 == 0 {
		if n >= 4 {
			ans = 2
		} else if n == 2 {
			ans = 1
		}
	} else {
		if n >= 5 {
			ans = 3
		} else if n == 3 {
			ans = 2
		}
	}
	printf("%d\n", ans)
}

type point struct {
	left int
	right int
}

func solveB() {
	var n, q int
	scanf("%d %d\n", &n, &q)
	var s string
	scanf("%s\n", &s)
	var P0, P1 point = point{n, -1}, point{n, -1}
	for i := 0; i < n; i++ {
		if s[i] == '0' {
			P0.right = i
		} else {
			P1.right = i
		}
	}

	for i := n - 1; i >= 0; i-- {
		if s[i] == '0' {
			P0.left = i
		} else {
			P1.left = i
		}
	}

	for ; q > 0; q-- {
		var l, r int
		scanf("%d %d\n", &l, &r)
		l--
		r--
		ans := "NO"
		if (s[l] == '0' && P0.left < l || s[l] == '1' && P1.left < l) ||
			(s[r] == '0' && P0.right > r || s[r] == '1' && P1.right > r) {
			ans = "YES"
		}

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

func sqr(x int) float64 {
	return float64(x * x)
}

func solveD() {
	var d, k int
	scanf("%d %d\n", &d, &k)
	ans := "Ashish"
	z := int(math.Sqrt(0.5 * sqr(d) / sqr(k)))
	if k * k * (z * z + (z + 1) * (z + 1)) > d * d {
		ans = "Utkarsh"
	}
	printf("%s\n", ans)
}

func main() {
	defer writer.Flush()
	var t int
	scanf("%d\n", &t)
	for ; t > 0; t-- {
		solveD()
	}
}

package main
import (
	"os"
	"fmt"
	"bufio"
)
var rd = bufio.NewReader(os.Stdin)
func sqr(x int) int {
	return x * x
}
func ok(x, y, d, k int) bool {
	return sqr(k * x) + sqr(k * y) <= sqr(d)
}
func main() {
	q := 0
	fmt.Fscan(rd, &q)
	for t := 0; t < q; t++ {
		d, k, cur := 0, 0, 0
		fmt.Fscan(rd, &d, &k)
		for ok(cur + 1, cur + 1, d, k) {
			cur++
		}
		if ok(cur + 1, cur, d, k) {
			fmt.Println("Ashish")
		} else {
			fmt.Println("Utkarsh")
		}
	}
}


You work in the quality control department of technical support for a large company. Your job is to make sure all client issues have been resolved.Today you need to check a copy of a dialog between a client and a technical support manager. According to the rules of work, each message of the client must be followed by one or several messages, which are the answer of a support manager. However, sometimes clients ask questions so quickly that some of the manager's answers to old questions appear after the client has asked some new questions.Due to the privacy policy, the full text of messages is not available to you, only the order of messages is visible, as well as the type of each message: a customer question or a response from the technical support manager. It is guaranteed that the dialog begins with the question of the client.You have to determine, if this dialog may correspond to the rules of work described above, or the rules are certainly breached.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 500$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the total number of messages in the dialog. The second line of each test case consists of $$$n$$$ characters "Q" and "A", describing types of messages in the dialog in chronological order. Character "Q" denotes the message with client question, and character "A" — the message with technical support manager answer. It is guaranteed that the first character in the line equals to "Q".

For each test case print "Yes" (without quotes) if dialog may correspond to the rules of work, or "No" (without quotes) otherwise.

5

4

QQAA

4

QQAQ

3

QAA

1

Q

14

QAQQAQAAQQQAAA

NoteIn the first test case the two questions from the client are followed with two specialist's answers. So this dialog may correspond to the rules of work.In the second test case one of the first two questions was not answered.In the third test case the technical support manager sent two messaged as the answer to the only message of the client.

package main

import "fmt"

func main() {
	var t, n int
	var log []byte

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

		for j := 0; j < n; j++ {
			if log[j] == 'Q' {
				count++
			} else {
				if count > 0 {
					count--
				}
			}
		}
		if count == 0 {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
	}

}

package main
import "fmt"

func main () {
    var t int
    fmt.Scan(&t)
    for j := 0; j < t; j++ {
        var n int64
        var s string
        fmt.Scan(&n)
        fmt.Scan(&s)
        c := 0
        f := true
        for i:= len(s)-1;i >= 0; i-- {
            if s[i:i+1]=="A" {
                c++
            } else {
                if c <= 0 {
                    f = false
                    break
                } else {
                    c--
                }
            }
        }
        if f {
            fmt.Println("Yes")
        } else {
            fmt.Println("No")
        }
    }
}

package main

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

var (
	t, n int
	str  string
	q, a int
)

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n, &str)
		q, a = 0, 0
		for i := 0; i < n; i++ {
			if str[i] == 'Q' {
				q++
			} else {
				if q != 0 {
					q--
				}
			}
		}

		if q != 0 {
			println("No")
		} else {
			println("Yes")
		}
	}
}

var (
	ioR *bufio.Reader
	ioW *bufio.Writer
)

func init() {
	ioR = bufio.NewReader(os.Stdin)
	ioW = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(ioR, a...)
}

func println(a ...any) {
	fmt.Fprintln(ioW, a...)
}

func flush() {
	ioW.Flush()
}

package main

import (
	"fmt"
)

func work() {
	var n int
	fmt.Scanln(&n)
	cnt := 0
	var s string
	fmt.Scanln(&s)
	for _, c := range s {
		if c == 'Q' {
			cnt++
		} else if c == 'A' {
			cnt--
			if cnt < 0 {
				cnt = 0
			}
		}
	}
	if cnt != 0 {
		fmt.Println("No")
	} else {
		fmt.Println("Yes")
	}

}

func main() {
	var T int
	fmt.Scanln(&T)
	for i := 0; i < T; i++ {
		work()
	}
}

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n,sum int
		fmt.Fscan(in,&n)
		var s string
		fmt.Fscan(in,&s)
		for j:=n-1;j>=0;j--{
			if s[j] == 65 {
				sum++
			} else {
				sum--
			}
			if sum < 0 {
				fmt.Fprintln(out,"No")
				goto out
			}
		}
		fmt.Fprintln(out,"Yes")
		out:
	}
}

package main

import "fmt"

func main() {
    var cases, num = 0, 0
    fmt.Scanf("%d\n", &cases)
    for i := 0; i < cases; i++ {
        str := ""
        fmt.Scanf("%d\n", &num)
        fmt.Scanf("%s\n", &str)
        res := 0
        j := 0
        for j = 0; j < num; j++ {
            if str[j] == 'Q' {
                res++
            } else if str[j] == 'A' {
                res--
            }
            if res < 0 {
                res = 0
            }
        }
        if res > 0 || j < num {
            fmt.Println("No")
        } else {
            fmt.Println("Yes")
        }
    }
}

package main

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

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

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

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

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

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

/**
Run solve the problem CF1754A
Date: 10/24/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1754/A
Problem: CF1754A
**/
func (in *CF1754A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		str := in.NextString()
		q := 0

		for i := 0; i < n; i++ {
			if str[i] == 'Q' {
				q++
			} else {
				q--
				if q < 0 {
					q = 0
				}
			}
		}
		if q > 0 {
			fmt.Println("NO")
		} else {
			fmt.Println("YES")
		}
	}
}

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

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

package main

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

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()
	var t, n int
	var s string
	Fscan(r, &t)

	for t > 0 {
		t--
		Fscan(r, &n, &s)
		k := 0
		for i := range s {
			if s[i] == 'Q' {
				if k < 0 {
					k = 0
				}
				k++
			} else {
				k--
			}
		}
		if k > 0 {
			Fprintln(w, "NO")
		} else {
			Fprintln(w, "YES")

		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var epochs int
	fmt.Scanf("%d\n", &epochs)
	for ; epochs > 0; epochs-- {
		var q int
		fmt.Scanf("%d\n", &q)
		q = 0
		var input string
		fmt.Scanf("%s\n", &input)
		for _, token := range input {
			if token == 'Q' {
				if q >= 0 {
					q++
				} else {
					q = 1
				}
			} else {
				q--
			}
		}
		if q > 0 {
			fmt.Println("No")
		} else {
			fmt.Println("Yes")
		}
	}
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	testcasesStr := scanner.Text()

	testcases, _ := strconv.ParseInt(testcasesStr, 0, 64)

	var i int64

	for i = 0; i < testcases; i++ {

		scanner.Scan()
		messageLengthStr  := scanner.Text()

		scanner.Scan()
		messageOrder  := scanner.Text()

		messageLength, _ := strconv.ParseInt(messageLengthStr, 0, 64)

		validOrder := IsValidOrder(messageLength, messageOrder)

		fmt.Println(validOrder)
	}
}

func IsValidOrder(messageLength int64, messageOrder string) string {
	messageQueues := []string{}

	var i int64

	for i = 0; i < messageLength; i++ {
		character := string(messageOrder[i])

		if character == "Q" {
			messageQueues = append(messageQueues, character)
		} else if character == "A" {
			if len(messageQueues) > 0 {
				messageQueues = append(messageQueues[:0], messageQueues[1:]...)
			}
		}
	}

	if len(messageQueues) == 0 {
		return "YES"
	}
	return "NO"
}

package main

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

var in = bufio.NewReader(os.Stdin)
var tc = 1
var DEBUG = os.Getenv("DEBUG") != ""

func solve() {
	var n int
	var s string
	scan(&n, &s)
	var a, q = 0, 0
	for _, e := range []rune(s) {
		if e == 'Q' {
			q++
		} else {
			a++
			q -= min(a, q)
			a = 0
		}
	}
	printf("%s\n", yn(q <= 0))
}

func main() {
	var T int
	scan(&T)
	for ; T > 0; T-- {
		solve()
		tc++
	}
}

func yn(b bool) string      { return map[bool]string{true: "Yes", false: "No"}[b] }
func scan(a ...interface{}) { fmt.Fscan(in, a...) }
func printf(format string, a ...interface{}) {
	if DEBUG {
		format = fmt.Sprintf("Test #%d: %s", tc, format)
	}
	fmt.Printf(format, a...)
}

func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

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

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

package main

import (
	"fmt"
)

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

	for testCases > 0 {
		testCases--
		var message string
		var length string
		fmt.Scan(&length)
		fmt.Scan(&message)
		count := 0
		possible := true
		message = reverse(message)
		for _, value := range message {
			if value == 81 {
				count--
			} else {
				count++
			}
			// fmt.Println(value)
			if count < 0 {
				possible = false
			}
		}
		if possible {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}
func reverse(message string) string {
	var result string
	for _, v := range message {
		result = string(v) + result
	}
	return result
}

package main

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

var reader = bufio.NewReader(os.Stdin)

const N = 52

var n, m int
var (
	a, g, q [N]int
)

func main() {
	var t int

	fmt.Fscan(reader, &t)
testcase:
	for t > 0 {
		t--
		fmt.Fscan(reader, &n)
		var s string
		fmt.Fscan(reader, &s)
		qcnt := 0
		for i := 0; i < len(s); {
			if s[i] == 'Q' {
				qcnt++
				i++
			} else {
				j := i
				if qcnt > 0 {
					for ; j < len(s) && s[j] == 'A'; j++ {
						if qcnt > 0 {
							qcnt--
						}
					}
				} else {
					fmt.Println("No")
					continue testcase
				}
				i = j
			}
		}
		if qcnt == 0 {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
	}
}

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

package main

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

func solve(){
	var n int
	var s string
	Fscan(Stdin, &n, &s)
	tot := 0
	for i := 0; i < n; i++ {
		if s[i] == 'Q' {
			tot++
		} else {
			if tot > 0 {
				tot--
			}
		}
	}
	if tot > 0 {
		Fprintln(Stdout, "NO")
	} else {
		Fprintln(Stdout, "YES")
	}
}

func main(){
	var t int
	Fscan(Stdin, &t)
	for ; t > 0; t-- {
		solve()
	}
}

package main

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

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

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

func solve(n int, l string) string {
	var temp = 0
	for _, x := range l {
		if x == 'Q' {
			temp++
		}
		if x == 'A' {
			temp = max(temp-1, 0)
		}
	}
	if temp > 0 {
		return "No"
	}
	return "Yes"
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		fmt.Fscan(reader, &l)
		fmt.Println(solve(n, l))
	}
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanln(&n)
	for i := 0; i < n; i++ {
		var qn int
		var st string
		fmt.Scanln(&qn)
		fmt.Scanln(&st)
		s := 0
		for j := 0; j < qn; j++ {
			if st[j] == 'Q' {
				s = s + 1
			} else if s > 0 {
				s = s - 1
			}
		}
		if s > 0 {
			fmt.Println("No")
		} else {
			fmt.Println("Yes")
		}

	}
}

package main

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

const MaxMessages = 101

func main() {
	defer writer.Flush()
	var line string
	var n, t int

	scanws(&t)
	for t > 0 {
		scanws(&n)
		scanws(&line)
		printf("%s\n", solve(line, n))
		t--
	}
}

func solve(msgs string, sz int) string {
	if sz <= 1 {
		return "No"
	}
	var index int
	var s []rune
	runes := []rune(msgs)
	s = make([]rune, 0, MaxMessages)
	index = 0
	for _, event := range runes {
		switch {
		case event == 'Q':
			s = append(s, event)
			index++
		case len(s) > 0:
			s = s[:index-1]
			index--
		}
	}

	if len(s) > 0 {
		return "No"
	} else {
		return "Yes"
	}
}

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanws(a ...interface{}) { fmt.Fscan(reader, a...) }

package main

import (
	"fmt"
)

func solve() {
	var idx = 0
	var str string
	fmt.Scan(&idx, &str)
	ans := 0
	for _, item := range str {
		if item == 'Q' {
			ans++
		} else {
			ans--
		}
		if ans < 0 {
			ans = 0
		}
	}
	if ans > 0 {
		fmt.Println("No")
	} else {
		fmt.Println("Yes")
	}
}

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

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)
		b := make([]byte, n)
		fmt.Fscan(r, &b)

		cnt := 0
		for _, v := range b {
			if v == 'Q' {
				cnt++
			} else if cnt > 0 {
				cnt--
			}
		}
		if cnt == 0 {
			fmt.Fprintln(w, "YES")
		} else {
			fmt.Fprintln(w, "NO")
		}
	}

}

package main

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

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()
	var t, n int
	var s string
	Fscan(r, &t)

	for t > 0{
		t--
		Fscan(r, &n, &s)
		k := 0
		for i := range s{
			if s[i] == 'Q'{
				if k < 0{
					k = 0
				}
				k++
			}else{
				k--
			}
		}
		if k > 0{
			Fprintln(w, "NO")
		}else{
			Fprintln(w, "YES")

		}
	}
}

package main

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

const cf = true

func solve() {
	var n int
	var str string
	fmt.Fscan(in, &n, &str)
	a := 0
	for i := n - 1; i >= 0; i-- {
		if str[i] == 'Q' {
			a--
		} else {
			a++
		}
		if a < 0 {
			fmt.Fprintln(out, "No")
			return
		}
	}
	fmt.Fprintln(out, "Yes")
}

func main() {
	defer out.Flush()
	t := 1
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		solve()
	}
}

func LCM(a, b int) int {
	return a * b / GCD(a, b)
}

func GCD(a, b int) int {
	for a != b {
		if a > b {
			a -= b
		} else {
			b -= a
		}
	}

	return a
}

type SqrtInt interface {
	SignedSqrt | UnsignedSqrt
}

type SignedSqrt interface {
	~int | ~int32 | ~int64
}

type UnsignedSqrt interface {
	~uint | ~uint32 | ~uint64 | ~uintptr
}

func sqrt[T SqrtInt](x T) T {
	l, r := T(0), T(2000000123)
	for l < r {
		mid := (l + r) / 2
		if mid*mid > x {
			r = mid
		} else {
			l = mid + 1
		}
	}
	return l - 1
}

func ConvertInt(val string, base, toBase int) (string, error) {
	i, err := strconv.ParseInt(val, base, 64)
	if err != nil {
		return "", err
	}
	return strconv.FormatInt(i, toBase), nil
}

type set[T Ordered] struct {
	itms map[T]struct{}
}

func (s *set[T]) init() {
	if s.itms == nil {
		s.itms = make(map[T]struct{})
	}
}

func (s *set[T]) add(item T) *set[T] {
	s.init()
	s.itms[item] = exists
	return s
}

func (s *set[T]) remove(item T) *set[T] {
	s.init()
	delete(s.itms, item)
	return s
}

func (s *set[T]) has(item T) bool {
	s.init()
	_, c := s.itms[item]
	return c
}

func (s *set[T]) sortedItems() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	sort.Slice(items, func(i, j int) bool {
		return items[i] < items[j]
	})
	return items
}

func (s *set[T]) items() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	return items
}

func (s *set[T]) size() int {
	s.init()
	return len(s.itms)
}

var exists = struct{}{}

const MaxUint = ^uint(0)
const MinUint = 0
const MaxInt = int(MaxUint >> 1)
const MinInt = -MaxInt - 1

func reverseStr(s string) string {
	r := []byte(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type Ordered interface {
	Integer | Float | ~string
}

func abs[T Signed](x T) T {
	if x < 0 {
		return -x
	}
	return x
}

func min[T Ordered](x, y T) T {
	if x < y {
		return x
	}
	return y
}

func max[T Ordered](x, y T) T {
	if x > y {
		return x
	}
	return y
}

var (
	in  = getReader()
	out = getWriter()
)

func getReader() *bufio.Reader {
	if cf {
		return bufio.NewReader(os.Stdin)
	} else {
		in, _ := os.Open("input.txt")
		return bufio.NewReader(in)
	}
}

func getWriter() *bufio.Writer {
	if cf {
		return bufio.NewWriter(os.Stdout)
	} else {
		out, _ := os.Create("output.txt")
		return bufio.NewWriter(out)
	}
}

package main

import "fmt"

func main() {
	var t, n int
	var log []byte

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

		for j := 0; j < n-1; j++ {
			if log[j] == 'Q' {
				count++
			} else {
				if count > 0 {
					count--
				}
			}
		}
		if count == 0 {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
	}

}

package main

import "fmt"

func main() {
	var t, n int
	var log []byte

	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&n)
		fmt.Scan(&log)
		var countQ, countA int = 0, 0
		var cond bool

		for j := 0; j < n-1; j++ {

			if log[j] == 'Q' {
				countQ++
				if log[j] == 'Q' && log[j+1] == 'A' {
					for i := 0; i < n-j; i++ {
						if log[i] == 'Q' {
							continue
						}
						if log[i] == 'A' {
							countA++
						}
					}
					if countA >= countQ {
						countQ = 0
						countA = 0
						continue
					} else {
						countQ = 0
						countA = 0
						cond = true
						break
					}
				}
			}
		}

		if !cond {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
		//QAAAAAQQ
	}

}

package main

import "fmt"

func main() {
	var t, n int
	var log []byte

	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&n)
		fmt.Scan(&log)
		var countQ, countA int = 0, 0
		var cond bool
		for j := 0; j < n; j++ {
			if log[j] == 'A' {
				countA++
			}
			if log[j] == 'Q' {
				countQ++
			}
			if log[j] == 'Q' && j == n-1 {
				cond = true
				break
			}
			//QQQAQAAAAAAAAQQQA
			//QQAQQQQQQQQQQQQQQQQQQQQQQQQQQA
			//3 1
			//1

		}
		var locQ, locA int = 0, 0
		if !cond {
			for i := n - 1; i > 0; i-- {
				if log[i] == 'A' {
					locA++
				}
				if log[i] == 'Q' && log[i-1] == 'Q' {
					locQ++
				}
				if log[i] == 'Q' && log[i-1] == 'A' {
					locQ++
					if locA < locQ {
						cond = true
					}
					break
				}

			}
		}

		if countA >= countQ && !cond {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
		//QAAAAAQQ
	}

}

package main

import "fmt"

func main() {
	var t, n int
	var log []byte

	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&n)
		fmt.Scan(&log)
		var countQ, countA int = 0, 0
		var cond bool
		for j := 0; j < n; j++ {
			if log[j] == 'A' {
				countA++
			}
			if log[j] == 'Q' {
				countQ++
			}
			if log[j] == 'Q' && j == n-1 {
				cond = true
				break
			}
			//QQQAQAAAAAAAAQQQA
			//QQAQQQQQQQQQQQQQQQQQQQQQQQQQQA
			//3 1
			//1

		}
		var locQ, locA int = 0, 0
		if !cond {
			for i := n - 1; i > 0; i-- {
				if log[i] == 'A' {
					locA++
				}
				if log[i] == 'Q' && log[i-1] == 'Q' {
					locQ++
				}
				if log[i] == 'Q' && log[i-1] == 'A' {
					locQ++
					if locA < locQ {
						cond = true
					}
					break
				}

			}
		}

		if countA > countQ && !cond {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
		//QAAAAAQQ
	}

}

package main

import "fmt"

func main() {
	var t, n int
	var log []byte

	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&n)
		fmt.Scan(&log)
		var countQ, countA int = 0, 0
		var cond bool
		for j := 0; j < n; j++ {
			if log[j] == 'A' {
				countA++
			}
			if log[j] == 'Q' {
				countQ++
			}
			if log[j] == 'Q' && j == n-1 {
				cond = true
				break
			}
			//QQQAQAAAAAAAAQQQA
			//3 1
			//1

		}
		var locQ, locA int
		for i := n - 1; i > 0; i-- {
			if log[i] == 'A' {
				locA++
			}
			if log[i] == 'Q' && log[i-1] == 'Q' {
				locQ++
			}
			if log[i] == 'Q' && log[i-1] == 'A' {
				locQ++
				if locA < locQ {
					cond = true
				}
				break
			}

		}

		if countA < countQ || cond {
			fmt.Println("No")
		} else if countA > countQ && !cond {
			fmt.Println("Yes")
		}
		//QAAAAAQQ
	}

}

package main

import "fmt"

func main() {
	var t, n int
	var log []byte

	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&n)
		fmt.Scan(&log)
		var countQ, countA int = 0, 0
		var cond bool
		for j := 0; j < n; j++ {
			if log[j] == 'A' {
				countA++
			}
			if log[j] == 'Q' {
				countQ++
			}
			if log[j] == 'Q' && j == n-1 {
				cond = true
				break
			}
			//QQQAQAAAAAAAAQQQA
			//3 1
			//1

		}
		var locQ, locA int
		for i := n - 1; i > 0; i-- {
			if log[i] == 'A' {
				locA++
			}
			if log[i] == 'Q' && log[i-1] == 'Q' {
				locQ++
			}
			if log[i] == 'Q' && log[i-1] == 'A' {
				locQ++
				if locA < locQ {
					cond = true
				}
				break
			}

		}

		if countA < countQ || cond {
			fmt.Println("No")
		} else {
			fmt.Println("Yes")
		}
		//QAAAAAQQ
	}

}

package main

import "fmt"

func main() {
	var t, n int
	var log []byte

	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&n)
		fmt.Scan(&log)
		var countQ, countA int = 0, 0
		var cond bool
		for j := 0; j < n; j++ {
			if log[j] == 'A' {
				countA++
			} else if log[j] == 'Q' {
				countQ++
			}
			if log[j] == 'Q' && j == n-1 {
				cond = true
				break
			}
			//QQQAQQQA

		}
		if countA < countQ || cond {
			fmt.Println("No")
		} else {
			fmt.Println("Yes")
		}
		//QAAAAAQQ
	}

}

package main

import "fmt"

func main() {
	var t, n int
	var log []byte

	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&n)
		fmt.Scan(&log)
		var countQ, countA int = 0, 0
		for j := 0; j < n; j++ {
			if log[j] == 'A' {
				countA++
			} else {
				countQ++
			}
		}
		if countA < countQ {
			fmt.Println("No")
		} else {
			fmt.Println("Yes")
		}
	}

}

package main

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

var (
	t, n int
	str  string
	q, a int
)

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n, &str)
		flag := false
		q, a = 0, 0
		for i := 0; i < n; i++ {
			if str[i] == 'Q' {
				flag = true
				q++
			} else {
				flag = false
				a++
			}
		}
		if str[0] == 'A' {
			flag = false
		}
		if flag || q > a {
			println("No")
		} else {
			println("Yes")
		}
	}
}

var (
	ioR *bufio.Reader
	ioW *bufio.Writer
)

func init() {
	ioR = bufio.NewReader(os.Stdin)
	ioW = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(ioR, a...)
}

func println(a ...any) {
	fmt.Fprintln(ioW, a...)
}

func flush() {
	ioW.Flush()
}

package main

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

var (
	t, n int
	str  string
	q, a int
)

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n, &str)
		flag := false
		for i := 0; i < n; i++ {
			if str[i] == 'Q' {
				flag = true
				q++
			} else {
				flag = false
				a++
			}
		}
		if str[0] == 'A' {
			flag = false
		}
		if flag || q > a {
			println("No")
		} else {
			println("Yes")
		}
	}
}

var (
	ioR *bufio.Reader
	ioW *bufio.Writer
)

func init() {
	ioR = bufio.NewReader(os.Stdin)
	ioW = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(ioR, a...)
}

func println(a ...any) {
	fmt.Fprintln(ioW, a...)
}

func flush() {
	ioW.Flush()
}

package main

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

var (
	t, n int
	str  string
	q, a int
)

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n, &str)
		flag := false
		for i := 0; i < n; i++ {
			if str[i] == 'Q' {
				flag = true
			} else {
				flag = false
			}
		}
		if str[0] == 'A' {
			flag = false
		}
		if flag {
			println("No")
		} else {
			println("Yes")
		}
	}
}

var (
	ioR *bufio.Reader
	ioW *bufio.Writer
)

func init() {
	ioR = bufio.NewReader(os.Stdin)
	ioW = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(ioR, a...)
}

func println(a ...any) {
	fmt.Fprintln(ioW, a...)
}

func flush() {
	ioW.Flush()
}

package main

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

var (
	t, n int
	str  string
	q, a int
)

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n, &str)
		flag := false
		for i := 0; i < n; i++ {
			if str[i] == 'Q' {
				flag = true
			} else {
				flag = false
			}
		}
		if str[0] == 'A' {
			flag = false
		}
		if flag {
			println("NO")
		} else {
			println("YES")
		}
	}
}

var (
	ioR *bufio.Reader
	ioW *bufio.Writer
)

func init() {
	ioR = bufio.NewReader(os.Stdin)
	ioW = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(ioR, a...)
}

func println(a ...any) {
	fmt.Fprintln(ioW, a...)
}

func flush() {
	ioW.Flush()
}

package main

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

var (
	t, n int
	str  string
	q, a int
)

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n, &str)
		q, a = 0, 0
		flag := false
		for i := 0; i < n; i++ {
			if str[i] == 'Q' {
				q++
				flag = true
			} else {
				flag = false
				a++
			}
		}
		if flag {
			println("NO")
		} else {
			println("YES")
		}
	}
}

var (
	ioR *bufio.Reader
	ioW *bufio.Writer
)

func init() {
	ioR = bufio.NewReader(os.Stdin)
	ioW = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(ioR, a...)
}

func println(a ...any) {
	fmt.Fprintln(ioW, a...)
}

func flush() {
	ioW.Flush()
}

package main

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

var (
	t, n int
	str  string
	q, a int
)

func main() {
	defer flush()
	scan(&t)
	for ; t != 0; t-- {
		scan(&n, &str)
		q, a = 0, 0
		for i := 0; i < n; i++ {
			if str[i] == 'Q' {
				q++
			} else {
				a++
			}
		}
		if q > a {
			println("NO")
		} else {
			println("YES")
		}
	}
}

var (
	ioR *bufio.Reader
	ioW *bufio.Writer
)

func init() {
	ioR = bufio.NewReader(os.Stdin)
	ioW = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(ioR, a...)
}

func println(a ...any) {
	fmt.Fprintln(ioW, a...)
}

func flush() {
	ioW.Flush()
}

package main

import (
	"fmt"
)

func work() {
	var n int
	fmt.Scanln(&n)
	cntQ := 0
	cntA := 0
	var s string
	fmt.Scanln(&s)
	for _, c := range s {
		if c == 'Q' {
			cntQ++
		} else if c == 'A' {
			cntA++
		}
		if cntQ > cntA {
			fmt.Println("No")
			return
		}
	}
	// fmt.Println(s)
	// fmt.Println(cntQ, cntA)
	fmt.Println("Yes")
}

func main() {
	var T int
	fmt.Scanln(&T)
	for i := 0; i < T; i++ {
		work()
	}
}

package main

import (
	"fmt"
)

func work() {
	var n int
	fmt.Scanln(&n)
	cntQ := 0
	cntA := 0
	var s string
	fmt.Scanln(&s)
	for _, c := range s {
		if c == 'Q' {
			cntQ++
		} else if c == 'A' {
			cntA++
		}
	}
	// fmt.Println(s)
	// fmt.Println(cntQ, cntA)
	if cntQ > cntA {
		fmt.Println("No")
	} else {
		fmt.Println("Yes")
	}
}

func main() {
	var T int
	fmt.Scanln(&T)
	for i := 0; i < T; i++ {
		work()
	}
}

package main

import (
	"fmt"
)

func work() {
	var n int
	fmt.Scanf("%d", &n)
	cntQ := 0
	cntA := 0
	var s string
	fmt.Scanln(&s)
	for _, c := range s {
		if c == 'Q' {
			cntQ++
		} else if c == 'A' {
			cntA++
		}
	}
	fmt.Println(s)
	fmt.Println(cntQ, cntA)
	if cntQ > cntA {
		fmt.Println("No")
	} else {
		fmt.Println("Yes")
	}
}

func main() {
	var T int
	fmt.Scanf("%d", &T)
	for i := 0; i < T; i++ {
		work()
	}
}

package main

import (
	"fmt"
)

func work() {
	var n int
	fmt.Scanf("%d", &n)
	cntQ := 0
	cntA := 0
	var s string
	fmt.Scanln(&s)
	for _, c := range s {
		if c == 'Q' {
			cntQ++
		} else if c == 'A' {
			cntA++
		}
	}
	if cntQ > cntA {
		fmt.Println("No")
	} else {
		fmt.Println("Yes")
	}
}

func main() {
	var T int
	fmt.Scanf("%d", &T)
	for i := 0; i < T; i++ {
		work()
	}
}

package main

import (
	"fmt"
)

func work() {
	var n int
	fmt.Scanf("%d", &n)
	cntQ := 0
	cntA := 0
	var s string
	fmt.Scanf("%s", &s)
	for _, c := range s {
		if c == 'Q' {
			cntQ++
		} else if c == 'A' {
			cntA++
		}
	}
	if cntQ > cntA {
		fmt.Println("No")
	} else {
		fmt.Println("Yes")
	}
}

func main() {
	var T int
	fmt.Scanf("%d", &T)
	for i := 0; i < T; i++ {
		work()
	}
}

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		var s string
		fmt.Fscan(in,&s)
		a:= make([]int,n)
		for j:=0;j<n;j++{
			if s[j] == 81 {
				a[j] = 1
			} else {
				a[j] = 0
			}
		}
		for j:=0;j<n-1;j++{
			for k:=j+1;k<n;k++{
				if a[k] == 0 {
					a[k] = 2
				}
			}
		}
		var q,solved int
		for j:=0;j<n;j++{
			if a[j] == 1 {
				q++
			} else if a[j] == 2 {
				solved++
			}
		}
		if q > solved || a[n-1] == 1 {
			fmt.Fprintln(out,"No")
		} else {
			fmt.Fprintln(out,"Yes")
		}
	}
}

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n,tally int
		fmt.Fscan(in,&n)
		var s string
		fmt.Fscan(in,&s)
		for j:=0;j<n;j++{
			if s[j] == 65 {
				tally++
			}
		}
		var r bool = false
		if n & 1 == 1 {
			if tally > n/2 {
				r = true
			}
		} else {
			if tally >= n/2 {
				r = true
			}
		}
		if r == true && s[n-1] != 81 {
			fmt.Fprintln(out,"Yes")
		} else {
			fmt.Fprintln(out,"No")
		}
	}
}

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n,tally int
		fmt.Fscan(in,&n)
		var s string
		fmt.Fscan(in,&s)
		for j:=0;j<n;j++{
			if s[j] == 65 {
				tally++
			}
		}
		var r bool = false
		if n & 1 == 1 {
			if tally > n/2 {
				r = true
			}
		} else {
			if tally >= n/2 {
				r = true
			}
		}
		if r == true {
			fmt.Fprintln(out,"Yes")
		} else {
			fmt.Fprintln(out,"No")
		}
	}
}

package main

import "fmt"

func main() {
    var cases, num = 0, 0
    fmt.Scanf("%d\n", &cases)
    for i := 0; i < cases; i++ {
        str := ""
        fmt.Scanf("%d\n", &num)
        fmt.Scanf("%s\n", &str)
        res := 0
        j := 0
        for j = 0; j < num; j++ {
            if str[j] == 'Q' {
                res++
            } else if str[j] == 'A' {
                res--
            }
            if res < 0 {
                break
            }
        }
        if res > 0 || j < num {
            fmt.Println("No")
        } else {
            fmt.Println("Yes")
        }
    }
}

package main

import "fmt"

func main() {
    var cases, num = 0, 0
    fmt.Scanf("%d\n", &cases)
    for i := 0; i < cases; i++ {
        str := ""
        fmt.Scanf("%d\n", &num)
        fmt.Scanf("%s\n", &str)
        res := 0
        for j := 0; j < num; j++ {
            if str[j] == 'Q' {
                res++
            } else if str[j] == 'A' {
                res--
            }
            if res < 0 {
                break
            }
        }
        if res > 0 {
            fmt.Println("No")
        } else {
            fmt.Println("Yes")
        }
    }
}

package main

import "fmt"

func main() {
    var cases, num = 0, 0
    fmt.Scanf("%d", &cases)
    for i := 0; i < cases; i++ {
        str := ""
        fmt.Scanf("%d", &num)
        fmt.Scanf("%s", &str)
        res := 0
        for j := 0; j < num; j++ {
            if str[j] == 'Q' {
                res++
            } else if str[j] == 'A' {
                res--
            }
            if res < 0 {
                break
            }
        }
        if res > 0 {
            fmt.Println("No")
        } else {
            fmt.Println("Yes")
        }
    }
}

package main

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

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

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

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

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

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

/**
Run solve the problem CF1754A
Date: 10/24/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1754/A
Problem: CF1754A
**/
func (in *CF1754A) Run() {
  for t := in.NextInt(); t > 0; t-- {
    n := in.NextInt()
    str := in.NextString()
    q := 0

    for i := 0; i < n; i++ {
      if str[i] == 'Q' {
        q++
      } else {
        q = 0
      }
    }
    if q > 0 {
      fmt.Println("NO")
    } else {
      fmt.Println("YES")
    }
  }
}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1754A
Date: 10/24/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1754/A
Problem: CF1754A
**/
func (in *CF1754A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		str := in.NextString()
		q := 0
		for i := 0; i < n; i++ {
			if str[i] == 'Q' {
				q++
			}
		}
		if q > n-q || str[n-1] == 'Q' {
			fmt.Println("NO")
		} else {
			fmt.Println("YES")
		}
	}
}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1754A
Date: 10/24/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1754/A
Problem: CF1754A
**/
func (in *CF1754A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		str := in.NextString()
		q := 0
		for i := 0; i < n; i++ {
			if str[i] == 'Q' {
				q++
			}
		}
		if q > n-q {
			fmt.Println("NO")
		} else {
			fmt.Println("YES")
		}
	}
}

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

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

package main

import "fmt"

func main() {
	var testCase int
	var inputChar int

	fmt.Scan(&testCase)
	for i := 0; i < testCase; i++ {
		fmt.Scan(&inputChar)
		counter := 0
		board := make([]string, inputChar)

		for j := 0; j < inputChar; j++ {
			fmt.Scan(&board[j])
			if board[0] == "A" {
				counter = -1
				break
			}

			if board[j] == "Q" {
				counter--

			} else if board[j] == "A" {
				counter++
				if counter > 0 {
					counter = 0
				}
			}

		}

		if counter >= 0 {
			fmt.Print("Yes\n")

		} else {
			fmt.Print("No\n")
		}
	}

}

package main

import "fmt"

func main() {
	var testCase int
	var inputChar int

	fmt.Scan(&testCase)
	for i := 0; i < testCase; i++ {
		fmt.Scan(&inputChar)
		counter := 0
		board := make([]string, inputChar)

		for j := 0; j < inputChar; j++ {
			fmt.Scan(&board[j])
			if board[0] == "A" {
				counter = -1
				break
			}

			if board[j] == "Q" {
				counter++

			} else if board[j] == "A" {
				counter--

			}

		}

		if counter < 0 {
			fmt.Print("No\n")

		} else {
			fmt.Print("Yes\n")
		}
	}

}

package main

import (
	"fmt"
)

func main() {
	var epochs int
	fmt.Scanf("%d\n", &epochs)
	for ; epochs > 0; epochs-- {
		var num, q, a int
		fmt.Scanf("%d\n", &num)
		var qastring string
		fmt.Scanf("%s\n", &qastring)
		for _, qa := range qastring {
			if qa == 'Q' {
				q++
			} else {
				a++
			}
		}
		if a >= q {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
	}
}

package main

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

var in = bufio.NewReader(os.Stdin)
var tc = 1
var DEBUG = os.Getenv("DEBUG") != ""

func solve() {
	var n int
	var s string
	scan(&n, &s)
	c := 0
	for _, e := range []rune(s) {
		if e == 'Q' {
			c++
		} else {
			c--
		}
	}
	printf("%s\n", yn(c <= 0))
}

func main() {
	var T int
	scan(&T)
	for ; T > 0; T-- {
		solve()
		tc++
	}
}

func yn(b bool) string      { return map[bool]string{true: "Yes", false: "No"}[b] }
func scan(a ...interface{}) { fmt.Fscan(in, a...) }
func printf(format string, a ...interface{}) {
	if DEBUG {
		format = fmt.Sprintf("Test #%d: %s", tc, format)
	}
	fmt.Printf(format, a...)
}

func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

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

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

package main

import (
	"fmt"
)

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

	for testCases > 0 {
		testCases--
		var message string
		fmt.Scan(&message)
		count := 0
		possible := true
		message = reverse(message)
		for _, value := range message {
			if value == 81 {
				count--
			} else {
				count++
			}
			// fmt.Println(value)
			if count < 0 {
				possible = false
			}
		}
		if possible {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}
func reverse(message string) string {
	var result string
	for _, v := range message {
		result = string(v) + result
	}
	return result
}

package main

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

var reader = bufio.NewReader(os.Stdin)

const N = 52

var n, m int
var (
	a, g, q [N]int
)

func main() {
	var t int

	fmt.Fscan(reader, &t)
testcase:
	for t > 0 {
		t--
		fmt.Fscan(reader, &n)
		var s string
		fmt.Fscan(reader, &s)
		qcnt := 0
		scnt := 0
		for i := 0; i < len(s);  {
			if qcnt > scnt {
				if s[i] == 'Q' {
					qcnt ++
					i ++
				} else {
					j := i
					for ; j < len(s) && s[j] == 'A'; j ++ {

					}
					i = j
					scnt ++
				}
			} else {
				fmt.Println("No")
				continue testcase
			}
		}
		if qcnt == scnt {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
	}
}

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


We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".Given a string, you have to find two values:  the number of good substrings of even length;  the number of good substrings of odd length.

The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.

Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.

NoteIn example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.DefinitionsA substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.

package main

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

func main() {
	buf, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		panic(err)
	}
	var a, b [2]int64
	var ans [2]int64
	for i := range buf {
		switch buf[i] {
		case 'a':
			a[i%2]++
			ans[0] += a[(i+1)%2]
			ans[1] += a[i%2]
		case 'b':
			b[i%2]++
			ans[0] += b[(i+1)%2]
			ans[1] += b[i%2]
		}
	}
	fmt.Println(ans[0], ans[1])
}

package main

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

const MAX_N = 100010

var dp [2][2]int64

func main() {
	fsc := NewFastScanner()
	S := fsc.Next()
	N := len(S)
	var res1, res2 int64

	for i := 0; i < N; i++ {
		if S[i] == 'a' {
			dp[i%2][0]++
			//even
			res1 += dp[(i+1)%2][0]
			//odd
			res2 += dp[i%2][0]
		} else {
			dp[i%2][1]++
			//even
			res1 += dp[(i+1)%2][1]
			//odd
			res2 += dp[i%2][1]
		}
	}
	fmt.Println(res1, res2)

}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

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

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

//Max,Min
func IntMax(a, b int) int {
	if a < b {
		return b
	}
	return a
}

func Int64Max(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func Float64Max(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

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

func Int64Min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func Float64Min(a, b float64) float64 {
	if a > b {
		return b
	}
	return a
}

//Gcd
func IntGcd(a, b int) int {
	if a < b {
		b, a = a, b
	}
	if b == 0 {
		return a
	}
	return IntGcd(b, a%b)
}
func Int64Gcd(a, b int64) int64 {
	if a < b {
		b, a = a, b
	}
	if b == 0 {
		return a
	}
	return Int64Gcd(b, a%b)
}

func IntAbs(a int) int {
	if a < 0 {
		a *= -1
	}
	return a
}

func Int64Abs(a int64) int64 {
	if a < 0 {
		a *= -1
	}
	return a
}