Let's call a string good if its length is at least $$$2$$$ and all of its characters are $$$\texttt{A}$$$ except for the last character which is $$$\texttt{B}$$$. The good strings are $$$\texttt{AB},\texttt{AAB},\texttt{AAAB},\ldots$$$. Note that $$$\texttt{B}$$$ is not a good string.You are given an initially empty string $$$s_1$$$.You can perform the following operation any number of times:   Choose any position of $$$s_1$$$ and insert some good string in that position. Given a string $$$s_2$$$, can we turn $$$s_1$$$ into $$$s_2$$$ after some number of operations?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single string $$$s_2$$$ ($$$1 \leq |s_2| \leq 2 \cdot 10^5$$$). It is guaranteed that $$$s_2$$$ consists of only the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$. It is guaranteed that the sum of $$$|s_2|$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print "YES" (without quotes) if we can turn $$$s_1$$$ into $$$s_2$$$ after some number of operations, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAB}} \to \texttt{A}\color{red}{\texttt{AB}}\texttt{AB}$$$.In the third test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAAAAAAAB}}$$$.In the second and fourth test case, it can be shown that it is impossible to turn $$$s_1$$$ into $$$s_2$$$.

package main

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

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

	defer writer.Flush()

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

	for ; t > 0; t-- {
		var text string
		fmt.Fscanf(in, "%s\n", &text)

		if text[len(text) - 1] != 'B' {
			fmt.Fprintln(writer, "NO")
			continue
		}

		good := true
		cnt := 0
		for _, ch := range text {
			if ch == 'A' {
				cnt++
			} else {
				cnt--
				if cnt < 0 {
					good = false
					break
				}
			}
		}

		if good {
			fmt.Fprintln(writer, "YES")
		} else {
			fmt.Fprintln(writer, "NO")
		}
	}
}

package main

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

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

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

	for ; t > 0; t-- {
		var text string
		fmt.Fscanf(in, "%s\n", &text)

		//text, _ := reader.ReadString('\n')
		//text = strings.TrimSpace(text)

		if text[len(text) - 1] != 'B' {
			fmt.Println("NO")
			continue
		}

		good := true
		cnt := 0
		for _, ch := range text {
			if ch == 'A' {
				cnt++
			} else {
				cnt--
				if cnt < 0 {
					good = false
					break
				}
			}
		}

		if good {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

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

	for ; t > 0; t-- {
		var text string
		fmt.Fscan(in, &text)

		//text, _ := reader.ReadString('\n')
		//text = strings.TrimSpace(text)

		if text[len(text) - 1] != 'B' {
			fmt.Println("NO")
			continue
		}

		good := true
		cnt := 0
		for _, ch := range text {
			if ch == 'A' {
				cnt++
			} else {
				cnt--
				if cnt < 0 {
					good = false
					break
				}
			}
		}

		if good {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

	text, _ := reader.ReadString('\n')
	text = strings.TrimSpace(text)
	t, _ := strconv.Atoi(text)

	for j := 0; j < t; j++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimSpace(text)

		if text[len(text) - 1] != 'B' {
			fmt.Println("NO")
			continue
		}

		good := true
		cnt := 0
		for _, ch := range text {
			if ch == 'A' {
				cnt++
			} else {
				cnt--
				if cnt < 0 {
					good = false
					break
				}
			}
		}

		if good {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

	text, _ := reader.ReadString('\n')
	text = strings.TrimSpace(text)
	t, _ := strconv.Atoi(text)

	for j := 0; j < t; j++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimRight(text, "\r\n")

		if text[len(text) - 1] != 'B' {
			fmt.Println("NO")
			continue
		}

		good := true
		cnt := 0
		for _, ch := range text {
			if ch == 'A' {
				cnt++
			} else {
				cnt--
				if cnt < 0 {
					good = false
					break
				}
			}
		}

		if good {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

	reader := bufio.NewReader(os.Stdin)
	reader.ReadString('\n')
	for j := 0; j < t; j++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimRight(text, "\r\n")

		if text[len(text) - 1] != 'B' {
			fmt.Println("NO")
			continue
		}

		good := true
		cnt := 0
		for _, ch := range text {
			if ch == 'A' {
				cnt++
			} else {
				cnt--
				if cnt < 0 {
					good = false
					break
				}
			}
		}

		if good {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var b int
	var text string
	fmt.Scanf("%d\n", &b)
	for j := 0; j < b; j++ {
		fmt.Scanf("%s\n", &text)

		if text[len(text) - 1] != 'B' {
			fmt.Println("NO")
			continue
		}

		good := true
		cnt := 0
		for _, ch := range text {
			if ch == 'A' {
				cnt++
			} else {
				cnt--
				if cnt < 0 {
					good = false
					break
				}
			}
		}

		if good {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

	reader := bufio.NewReader(os.Stdin)
	reader.ReadString('\n')
	for j := 0; j < b; j++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimRight(text, "\r\n")

		if text[len(text) - 1] != 'B' {
			fmt.Println("NO")
			continue
		}

		good := true
		cnt := 0
		for _, ch := range text {
			if ch == 'A' {
				cnt++
			} else {
				cnt--
				if cnt < 0 {
					good = false
					break
				}
			}
		}

		if good {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

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

		f := true
		var a, b int64
		for _, ch := range s {
			if ch == 'A' {
				a++
			} else {
				b++
			}

			if b > a {
				f = false
				break
			}
		}

		if f && b > 0 && s[len(s)-1] == 'B' {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

package main

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

const MOD int64 = 1000000007

var s string

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

func (a ByV) Len() int           { return len(a) }
func (a ByV) Less(i, j int) bool { return a[i].v < a[j].v }
func (a ByV) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {

	read := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(read, &t)

	for i := 0; i < t; i++ {

		fmt.Fscan(read, &s)

		a := solve()

		if a {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

type pair struct {
	v int
	idx []int
}

//a b c d

//20 12 -- 4
//4  2  -- 4

func solve() bool  {
	var cntA int
	var cntB int

	for i := 0; i < len(s); i++ {
		if s[i] == 'A' {
			cntA++
		}
		if s[i] == 'B' {
			cntB++
			if cntB > cntA {
				return false
			}
		}
	}

	if s[len(s) - 1] == 'A' {
		return false
	}

	if cntB == 0 {
		return false
	}

	return true

}

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

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

func solve(reader *bufio.Reader) {
    var str string
    fmt.Fscan(reader, &str)
    s := []rune(str)
    n := len(s)
    a := 0
    for i := 0; i < n; i++ {
        if(s[i] == 'A') {
            a++
        } else {
            a--
        }
        if(a < 0) {
            fmt.Println("NO")
            return
        }
    }
    if(s[n - 1] != 'B') {
        fmt.Println("NO")
    } else {
        fmt.Println("YES")
    }
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    tc := 1
    fmt.Fscan(reader, &tc)
    for i := 0; i < tc; i++ {
        solve(reader)
    }
}

package main

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

var in = bufio.NewReader(os.Stdin)

func main() {
	var n int
	fmt.Fscan(in, &n)

	for i := 0; i < n; i += 1 {
		var line string
		fmt.Fscan(in, &line)

		if good(line) {
			fmt.Printf("YES\n")
		} else {
			fmt.Printf("NO\n")
		}
	}
}

func good(s string) bool {
	if !strings.HasSuffix(s, "B") {
		return false
	}
	as := 0
	for i := 0; i < len(s); i += 1 {
		u := s[i]
		if u == 'A' {
			as += 1
		} else if u == 'B' {
			as -= 1
			if as < 0 {
				return false
			}
		}
	}

	return true
}

package main

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

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

func (in *CF1672B) 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 *CF1672B) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

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

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

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

/**
Run solve the problem CF1672B
Date: 27/07/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1672/B
Problem: CF1672B
**/
func (in *CF1672B) Run() {
	for t := in.NextInt(); t > 0; t-- {
		str := in.NextString()
		ans := true

		if len(str) < 2 {
			ans = false
		}

		b := 0
		a := 0
		for i := 0; i < len(str) && ans; i++ {
			if str[i] == 'B' {
				b++
			} else {
				a++
			}
			if b > a {
				ans = false
			}
		}

		if b > a {
			ans = false
		}

		if ans && str[0] == 'B' {
			ans = false
		}

		if ans && str[len(str)-1] == 'A' {
			ans = false
		}

		if ans {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}

}

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

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

package main

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

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

func solve() string {
	var s string
	fmt.Fscan(in, &s)

	var cntA int = 0
	var lastChar rune

	for _, c := range s {
		if c == 'B' {
			if cntA == 0 {
				return "NO"
			}
			cntA -= 1
		} else {
			cntA += 1
		}
		lastChar = c
	}

	if lastChar != 'B' {
		return "NO"
	} else {
		return "YES"
	}
}

func main() {
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		fmt.Fprintln(out, solve())
	}
}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func main() {
	defer w.Flush()

	var t int
	fmt.Fscan(r, &t)

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

func solve() {
	var s string
	fmt.Fscan(r, &s)

	if len(s) < 2 || s[len(s)-1] != 'B' {
		fmt.Fprintln(w, "NO")
		return
	}

	a := 0
	b := 0

	for _, c := range s {
		if c == 'A' {
			a++
		} else {
			b++
		}

		if b > a {
			fmt.Fprintln(w, "NO")
			return
		}
	}

	fmt.Fprintln(w, "YES")
}

package main

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

func solve(input string) string {
	if (input[len(input)-1]) != 'B' {
		return "NO"
	}
	sum := 0
	for _, val := range input {
		if val == 'B' {
			sum -= 1
		} else {
			sum += 1
		}
		if sum < 0 {
			return "NO"
		}
	}
	return "YES"
}
func main() {
	in := bufio.NewReader(os.Stdin)
	t := readInt(in)
	for i := 0; i < t; i++ {
		input, _ := in.ReadString('\n')
		input = strings.TrimSpace(input)
		fmt.Println(solve(input))
	}
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.TrimSpace(nStr)
	n, _ := strconv.Atoi(nStr)
	return n
}

package main

import (
	"fmt"
)

func main() {

	var testcase int
	fmt.Scan(&testcase)

	for i := 0; i < testcase; i++ {

		var inputString string
		fmt.Scan(&inputString)

		numberOfA := 0
		numberOfB := 0

		if len(inputString) < 2 {
			fmt.Println("NO")
			continue
		}

		raisedFlag := false
		for _, char := range inputString {

			if string(char) == "A" {
				numberOfA += 1
			}
			if string(char) == "B" {
				numberOfB += 1
			}

			if numberOfB > numberOfA {
				fmt.Println("NO")
				raisedFlag = true
				break
			}

		}
		if raisedFlag == true {
			continue
		}

		if string(inputString[len(inputString)-1:]) == "B" {
			fmt.Println("YES")
		} else {
			fmt.Println("No")
		}
	}

}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t      int
	s      string
)

func solve(s string) string {
	l := len(s)
	if s[0] == 'B' || s[l-1] == 'A' {
		return "NO"
	}
	c := 0
	for i := range s {
		if s[i] == 'A' {
			c++
		} else {
			c--
		}
		if c < 0 {
			return "NO"
		}
	}
	return "YES"
}

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

package main

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

/*
7
ABABABAB
BABABABAAB
ABABA
AB
AABBABAABBB
AABAAAAABABABABAB
AABAAABAAABBABABAAAB
---
YES
NO
NO
YES
NO
YES
YES
======
5
AABABAAABAAABB
AAABB
AAAABBBB
ABABB
ABB
---
YES
YES
YES
NO
NO
======
1
AABABB
---
YES

*/

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

	if len(s) == 1 {
		fmt.Fprintln(writer, "NO")
		return
	}

	if s[0] == 'B' {
		fmt.Fprintln(writer, "NO")
		return
	}

	if s[len(s)-1] != 'B' {
		fmt.Fprintln(writer, "NO")
		return
	}

	aCnt := make([]int, len(s))
	bCnt := make([]int, len(s))

	for i, r := range s {
		if r == 'A' {
			aCnt[i]++
		} else {
			bCnt[i]++
		}

		if i == 0 {
			continue
		}

		aCnt[i] += aCnt[i-1]
		bCnt[i] += bCnt[i-1]

		if aCnt[i] < bCnt[i] {
			fmt.Fprintln(writer, "NO")
			return
		}
	}

	fmt.Fprintln(writer, "YES")
}

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

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

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

const maxUint = ^uint(0)

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

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

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

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

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

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

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

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

	return minNumIdx
}

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

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

	return maxNumIdx
}

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

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

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

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

	return true
}

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

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

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

	num = abs(num)

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

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

//goland:noinspection GoUnusedFunction
func factorize(num int) []int {
	factors := []int{1}

	sqrtA := int(math.Sqrt(float64(num)))

	for ftr := 2; ftr <= sqrtA; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > sqrtA {
		factors = append(factors, num)
	}

	return factors
}

package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

	for ii := 0; ii < t; ii++ {
		var s string
		fmt.Fscan(in, &s)
		a := 0
		can := true
		b := 0
		for i := 0; i < len(s); i++ {
			if s[i] == 'A' {
				a++
				b = 0
			} else {
				if a == 0 {
					can = false
					break
				}
				a--
				b++
			}
		}
		if can && (a == 0 || b > 0) {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

package main

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

type Int int64

const (
	INF = 3e5 + 10
	L0  = Int(0)
	L1  = Int(1)
)

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

	var t int
	Fscan(in, &t)

	for tt := 0; tt < t; tt++ {
		var s string
		Fscan(in, &s)

		sum := 0
		lastB := false
		for _, ch := range s {
			if ch == 'A' {
				sum += 1
				lastB = false
			}
			if ch == 'B' {
				sum -= 1
				lastB = true
			}

			if sum < 0 {
				break
			}
		}
		if sum >= 0 && lastB {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}

}

func Abs(x Int) Int {
	if x > 0 {
		return x
	}
	return -x
}

func Min(nums ...Int) Int {
	return nums[MinIdx(nums...)]
}

func MinIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num < nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

func Max(nums ...Int) Int {
	return nums[MaxIdx(nums...)]
}

func MaxIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

package main

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

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

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

	for ; t > 0; t-- {
		var text string
		fmt.Fscanf(in, "%s\n", &text)

		//text, _ := reader.ReadString('\n')
		//text = strings.TrimSpace(text)

		if text[len(text) - 1] != 'B' {
			fmt.Fprintln(writer, "NO")
			continue
		}

		good := true
		cnt := 0
		for _, ch := range text {
			if ch == 'A' {
				cnt++
			} else {
				cnt--
				if cnt < 0 {
					good = false
					break
				}
			}
		}

		if good {
			fmt.Fprintln(writer, "YES")
		} else {
			fmt.Fprintln(writer, "NO")
		}
	}
}

package main

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

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

	reader := bufio.NewReader(os.Stdin)
	reader.ReadString('\n')
	for j := 0; j < b; j++ {
		text, _ := reader.ReadString('\n')
		//text = strings.TrimRight(text, "\r\n")

		if text[len(text) - 1] != 'B' {
			fmt.Println("NO")
			continue
		}

		good := true
		cnt := 0
		for _, ch := range text {
			if ch == 'A' {
				cnt++
			} else {
				cnt--
				if cnt < 0 {
					good = false
					break
				}
			}
		}

		if good {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

	reader := bufio.NewReader(os.Stdin)
	reader.ReadString('\n')
	for j := 0; j < b; j++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimRight(text, "\r\n")

		good := true
		cnt := 0
		for _, ch := range text {
			if ch == 'A' {
				cnt++
			} else {
				cnt--
				if cnt < 0 {
					good = false
					break
				}
			}
		}

		if good {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

	reader := bufio.NewReader(os.Stdin)
	reader.ReadString('\n')
	for j := 0; j < b; j++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimRight(text, "\r\n")

		if text[len(text) - 1] != 'B' {
			fmt.Println("NO")
			continue
		}

		good := true
		cnt := 0
		for _, ch := range text {
			if ch != 'A' {
				if cnt == 0 {
					good = false
					break
				}
				cnt = 0
			} else {
				cnt++
			}
		}

		if good {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

	reader := bufio.NewReader(os.Stdin)
	reader.ReadString('\n')
	for j := 0; j < b; j++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimRight(text, "\r\n")

		good := true
		cnt := 0
		for _, ch := range text {
			if ch != 'A' {
				if cnt == 0 {
					good = false
					break
				}
				cnt = 0
			} else {
				cnt++
			}
		}

		if good {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

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

		f := true
		var a, b int
		for _, ch := range s {
			if ch == 'A' {
				a++
			} else {
				b++
			}

			if b > a {
				f = false
				break
			}
		}

		if f && b > 0 {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

package main

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

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

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

		var f bool
		var b int
		for i := 0; i < len(s); i++ {
			if i < len(s)-1 && s[i:i+2] == "BB" {
				f = false
				break
			}

			if s[i] == 'B' {
				b++
			}
			f = true
		}

		if f && b > 0 && s[0] == 'A' {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

package main

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

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

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

		var f bool
		for i := 0; i < len(s)-1; i++ {
			if s[i:i+2] == "BB" {
				f = false
				break
			}
			f = true
		}

		if f {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

package main

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

const MOD int64 = 1000000007

var s string

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

func (a ByV) Len() int           { return len(a) }
func (a ByV) Less(i, j int) bool { return a[i].v < a[j].v }
func (a ByV) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {

	read := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(read, &t)

	for i := 0; i < t; i++ {

		fmt.Fscan(read, &s)

		a := solve()

		if a {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

type pair struct {
	v int
	idx []int
}

//a b c d

//20 12 -- 4
//4  2  -- 4

func solve() bool  {
	var cntA int
	var cntB int

	for i := 0; i < len(s); i++ {
		if s[i] == 'A' {
			cntA++
		}
		if s[i] == 'B' {
			cntB++
			if cntB > cntA {
				return false
			}
		}
	}

	if cntB == 0 {
		return false
	}

	return true

}

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

package main

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

const MOD int64 = 1000000007

var s string

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

func (a ByV) Len() int           { return len(a) }
func (a ByV) Less(i, j int) bool { return a[i].v < a[j].v }
func (a ByV) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {

	read := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(read, &t)

	for i := 0; i < t; i++ {

		fmt.Fscan(read, &s)

		a := solve()

		if a {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

type pair struct {
	v int
	idx []int
}

//a b c d

//20 12 -- 4
//4  2  -- 4

func solve() bool  {
	var cntA int
	var cntB int
	for i := 0; i < len(s); i ++ {
		if s[i] == 'A' {
			cntA++
		} else {
			cntB++
		}
	}

	if cntB == 0 {
		return false
	}

	if cntA >= cntB {
		return true
	}

	return false
}

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

package main

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

const MOD int64 = 1000000007

var s string

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

func (a ByV) Len() int           { return len(a) }
func (a ByV) Less(i, j int) bool { return a[i].v < a[j].v }
func (a ByV) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {

	read := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(read, &t)

	for i := 0; i < t; i++ {

		fmt.Fscan(read, &s)

		a := solve()

		if a {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

type pair struct {
	v int
	idx []int
}

//a b c d

//20 12 -- 4
//4  2  -- 4

func solve() bool  {
	var cntA int
	var cntB int
	for i := 0; i < len(s); i ++ {
		if s[i] == 'B' {
			cntB++

			var j int
			for j = i + 1; j < len(s); j++ {
				if s[j] != 'B' {
					break
				}
				cntB++
			}
			i = j - 1

			if cntA < cntB {
				return false
			}
			cntA = 0
			cntB = 0

		} else {
			cntA++
		}
	}

	if cntA > 0 {
		return false
	}

	return true
}

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

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

func solve(reader *bufio.Reader) {
    var str string
    fmt.Fscan(reader, &str)
    s := []rune(str)
    n := len(s)
    a := 0
    for i := 0; i < n; i++ {
        if(s[i] == 'A') {
            a++
        } else {
            a--
        }
        if(a < 0) {
            fmt.Println("NO")
            return
        }
    }
    if(a == n) {
        fmt.Println("NO")
    } else {
        fmt.Println("YES")
    }
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    tc := 1
    fmt.Fscan(reader, &tc)
    for i := 0; i < tc; i++ {
        solve(reader)
    }
}

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

func solve(reader *bufio.Reader) {
    var str string
    fmt.Fscan(reader, &str)
    s := []rune(str)
    n := len(s)
    a, b := 0, 0
    for i := 0; i < n; i++ {
        if(s[i] == 'A') {
            a++
        } else {
            b++
        }
        if(b > a) {
            fmt.Println("NO")
            return
        }
    }
    if(b == 0) {
        fmt.Println("NO")
    } else {
        fmt.Println("YES")
    }
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    tc := 1
    fmt.Fscan(reader, &tc)
    for i := 0; i < tc; i++ {
        solve(reader)
    }
}

package main

import (
	"fmt"
)

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

	for i := 0; i < n; i += 1 {
		var line string
		_, _ = fmt.Scanln(&line)

		if good(line) {
			fmt.Printf("YES\n")
		} else {
			fmt.Printf("NO\n")
		}
	}
}

func good(s string) bool {
	as := 0
	b := false
	for i := 0; i < len(s); i += 1 {
		u := s[i]
		if u == 'A' {
			as += 1
		} else if u == 'B' {
			b = true
			as -= 1
			if as < 0 {
				return false
			}
		}
	}

	return b
}

package main

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

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

func (in *CF1672B) 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 *CF1672B) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

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

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

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

/**
Run solve the problem CF1672B
Date: 27/07/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1672/B
Problem: CF1672B
**/
func (in *CF1672B) Run() {
	for t := in.NextInt(); t > 0; t-- {
		str := in.NextString()
		ans := true

		if len(str) < 2 {
			ans = false
		}

		for i := 1; i < len(str) && ans; i++ {
			if str[i-1] == 'B' && str[i] == 'B' {
				ans = false
			}
		}

		if ans && str[0] == 'B' {
			ans = false
		}

		if ans && str[len(str)-1] == 'A' {
			ans = false
		}

		if ans {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}

}

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

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

package main

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

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

func solve() string {
	var s string
	fmt.Fscan(in, &s)

	if len(s) == 0 {
		return "YES"
	}

	if len(s) < 2 {
		return "NO"
	}

	var haveB bool = false
	for ind, c := range s {
		if c == 'B' {
			if ind < 1 {
				return "NO"
			}
			if s[ind-1] != 'A' {
				return "NO"
			}
			haveB = true
		}
	}
	if haveB {
		return "YES"
	} else {
		return "NO"
	}
}

func main() {
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		fmt.Fprintln(out, solve())
	}
}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func main() {
	defer w.Flush()

	var t int
	fmt.Fscan(r, &t)

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

func solve() {
	var s string
	fmt.Fscan(r, &s)

	if len(s) < 2 || s[len(s)-1] != 'B' {
		fmt.Fprintln(w, "NO")
		return
	}

	hasA := false

	for _, c := range s {
		if c == 'A' {
			hasA = true
		} else {
			if !hasA {
				fmt.Fprintln(w, "NO")
				return
			}

			hasA = false
		}
	}

	fmt.Fprintln(w, "YES")
}

package main

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

func solve(input string) string {
	if input[len(input)-1] != 'B' {
		return "NO"
	}
	for index, val := range input {
		if val == 'B' {
			if index == 0 {
				return "NO"
			}
			if input[index-1] == 'B' {
				return "NO"
			}
		}
	}
	return "YES"
}
func main() {
	in := bufio.NewReader(os.Stdin)
	t := readInt(in)
	for i := 0; i < t; i++ {
		input, _ := in.ReadString('\n')
		input = strings.TrimSpace(input)
		fmt.Println(solve(input))
	}
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.TrimSpace(nStr)
	n, _ := strconv.Atoi(nStr)
	return n
}

package main

import (
	"fmt"
)

func main() {

	var testcase int
	fmt.Scan(&testcase)

	for i := 0; i < testcase; i++ {

		var inputString string
		fmt.Scan(&inputString)

		fmt.Println(inputString)

		numberOfA := 0
		numberOfB := 0

		if len(inputString) < 2 {
			fmt.Println("NO")
			continue
		}

		raisedFlag := false
		for _, char := range inputString {

			if string(char) == "A" {
				numberOfA += 1
			}
			if string(char) == "B" {
				numberOfB += 1
			}

			if numberOfB > numberOfA {
				fmt.Println("NO")
				raisedFlag = true
				break
			}

		}
		if raisedFlag == true {
			continue
		}

		if string(inputString[len(inputString)-1:]) == "B" {
			fmt.Println("YES")
		} else {
			fmt.Println("No")
		}
	}

}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t      int
	s      string
)

func solve(s string) string {
	l := len(s)
	if s[0] == 'B' || s[l-1] == 'A' {
		return "NO"
	}
	for i := 1; i < len(s); i++ {
		if s[i] == 'B' && s[i-1] == 'B' {
			return "NO"
		}
	}
	return "YES"
}

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

package main

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

/*
7
ABABABAB
BABABABAAB
ABABA
AB
AABBABAABBB
AABAAAAABABABABAB
AABAAABAAABBABABAAAB
---
YES
NO
NO
YES
NO
YES
YES
======
5
AABABAAABAAABB
AAABB
AAAABBBB
ABABB
ABB
---
YES
YES
YES
NO
NO
*/

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

	if len(s) == 1 {
		fmt.Fprintln(writer, "NO")
		return
	}

	if s[0] == 'B' {
		fmt.Fprintln(writer, "NO")
		return
	}

	if s[len(s)-1] != 'B' {
		fmt.Fprintln(writer, "NO")
		return
	}

	rev := reversed(s)

	bCnt := 0

	for i := 0; i < len(rev); i++ {
		r := rev[i]
		if r == 'B' {
			bCnt++
		} else {
			if i+bCnt-1 >= len(rev) {
				fmt.Fprintln(writer, "NO")
				return
			}

			for j := i; j < len(rev) && bCnt > 0; j++ {
				if rev[j] == 'A' {
					bCnt--
				} else {
					break
				}
			}

			if bCnt > 0 {
				fmt.Fprintln(writer, "NO")
				return
			}
		}
	}

	fmt.Fprintln(writer, "YES")
}

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

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

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

const maxUint = ^uint(0)

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

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

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

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

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

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

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

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

	return minNumIdx
}

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

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

	return maxNumIdx
}

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

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

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

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

	return true
}

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

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

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

	num = abs(num)

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

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

//goland:noinspection GoUnusedFunction
func factorize(num int) []int {
	factors := []int{1}

	sqrtA := int(math.Sqrt(float64(num)))

	for ftr := 2; ftr <= sqrtA; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > sqrtA {
		factors = append(factors, num)
	}

	return factors
}

package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

	for ii := 0; ii < t; ii++ {
		var s string
		fmt.Fscan(in, &s)
		a := 0
		can := true
		b := 0
		for i := 0; i < len(s); i++ {
			if s[i] == 'A' {
				a++
			} else {
				if a == 0 {
					can = false
					break
				}
				a--
				b++
			}
		}
		if can && b > 0 {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}
}

package main

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

type Int int64

const (
	INF = 3e5 + 10
	L0  = Int(0)
	L1  = Int(1)
)

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

	var t int
	Fscan(in, &t)

	for tt := 0; tt < t; tt++ {
		var s string
		Fscan(in, &s)

		sum := 0
		hasB := false
		for _, ch := range s {
			if ch == 'A' {
				sum += 1
			}
			if ch == 'B' {
				sum -= 1
				hasB = true
			}

			if sum < 0 {
				break
			}
		}
		if sum >= 0 && hasB {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}

}

func Abs(x Int) Int {
	if x > 0 {
		return x
	}
	return -x
}

func Min(nums ...Int) Int {
	return nums[MinIdx(nums...)]
}

func MinIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num < nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

func Max(nums ...Int) Int {
	return nums[MaxIdx(nums...)]
}

func MaxIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}


Vova has won $$$n$$$ trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible — that means, to maximize the length of the longest such subsegment.Help Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of trophies. The second line contains $$$n$$$ characters, each of them is either G or S. If the $$$i$$$-th character is G, then the $$$i$$$-th trophy is a golden one, otherwise it's a silver trophy.

Print the maximum possible length of a subsegment of golden trophies, if Vova is allowed to do at most one swap.

NoteIn the first example Vova has to swap trophies with indices $$$4$$$ and $$$10$$$. Thus he will obtain the sequence "GGGGGGGSGS", the length of the longest subsegment of golden trophies is $$$7$$$. In the second example Vova can make no swaps at all. The length of the longest subsegment of golden trophies in the sequence is $$$4$$$. In the third example Vova cannot do anything to make the length of the longest subsegment of golden trophies in the sequence greater than $$$0$$$.

package main

import (
	"fmt"
	"bufio"
	"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 max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func main(){
	defer writer.Flush()
	var n,l,r,ans,cnt,m,i int
	var a, b []int
	var s string
	scanf("%d\n", &n)
	scanf("%s\n", &s)
	// printf("read : %s\n", s)
	cnt = 0
	for i=0;i<n;i++ {
		if s[i] == 'G' {
			cnt++
		}
	}
	m=0
	l=0
	r=0
	for l < n {
		if l == r {
			r++
		} else if r < n && s[r] == 'G' {
			r++
		} else if s[l] != 'G' {
			l++
		} else {
			m++
			a = append(a, l)
			b = append(b, r)
			// printf("add %d %d\n", l, r)
			l = r
		}
	}
	ans = 0
	for i=0;i<m;i++ {
		ans = max(ans, b[i]-a[i])
		if m > 1 {
			ans = max(ans, b[i]-a[i]+1)
		}
	}
	for i=1;i<m;i++ {
		if a[i] - b[i-1] == 1 {
			ans = max(ans, b[i]-a[i] + b[i-1] - a[i-1])
			if m > 2 {
				ans = max(ans, b[i]-a[i] + b[i-1] - a[i-1] + 1)
			}
		}
	}
	printf("%d\n", ans)
}

package main

import (
	"fmt"
)

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

type cut struct {
	start, end int
}

func (p* cut) len() int {
	return p.end - p.start  + 1
}

func check(s []byte) int {
	if len(s) == 0 {
		return 0
	}
	var pcur *cut
	var cuts []*cut
	for i := 0; i < len(s); i++ {
		if s[i] == 71 {
			if pcur == nil {
				pcur = &cut{start:i}
			}
		} else {
			if pcur != nil {
				pcur.end = i - 1
				cuts = append(cuts, pcur)
				pcur = nil
			}
		}
	}
	if pcur != nil {
		pcur.end = len(s) - 1
		cuts = append(cuts, pcur)
	}

	return check_cuts(cuts)
}

func adj(a, b *cut) bool {
	return b.start - a.end == 2
}

func check_cuts(cuts []*cut) int {
	if len(cuts) == 0 {
		return 0
	}
	if len(cuts) == 1 {
		return cuts[0].len()
	}
	if len(cuts) == 2 {
		a, b := cuts[0], cuts[1]
		if adj(a, b) {
			return b.len() + a.len()
		} else {
			return max(b.len(), a.len()) + 1
		}
	}
	var prev *cut
	var selSize int
	for _, pc := range cuts {
		if prev == nil {
			selSize = pc.len() + 1
			prev = pc
			continue
		}

		curSize := pc.len() + 1
		if adj(prev, pc) {
			curSize += prev.len()
		}

		if curSize > selSize {
			selSize = curSize
		}

		prev = pc
	}
	return selSize
}

func main() {
	var n int
	fmt.Scanln(&n)
	s := make([]byte, n)
	fmt.Scanln(&s)
	fmt.Println(check(s))
}

package main

import (
  "fmt"
)

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

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

  lhs := make([]int, n)
  rhs := make([]int, n)

  var c, tot, sol int = 0, 0, 0

  for i, ch := range(s) {
    lhs[i] = c
    if ch == 'G' {
      c += 1
      tot += 1
    } else {
      c = 0
    }
    sol = max(sol, c)
  }

  c = 0
  for i := len(s)-1; i >= 0; i -=1 {
    rhs[i] = c
    if s[i] == 'G' {
      c += 1
    } else {
      c = 0
    }
    sol = max(sol, c)
  }

  for i, ch := range(s) {
    if ch == 'S' {
      tmp := lhs[i] + rhs[i]
      if (tmp < tot) {
        sol = max(sol, tmp + 1)
      } else {
        sol = max(sol, tmp)
      }
    }
  }

  fmt.Println(sol)
}

package main

import (
	"fmt"
)

func main() {
	var n int
	var str string
	fmt.Scan(&n, &str)
	cnt := 0
	cntG := 0
	arrf := make([]int, 0)
	for i := 0; i < n; i++ {
		if str[i] == 'G' {
			cnt++
			cntG++
			arrf = append(arrf, cnt)
		} else {
			arrf = append(arrf, cnt)
			cnt = 0
		}
	}
	cnt = 0
	arrb := make([]int, 0)
	for i := n - 1; i >= 0; i-- {
		if str[i] == 'G' {
			cnt++
			arrb = append(arrb, cnt)
		} else {
			arrb = append(arrb, cnt)
			cnt = 0
		}
	}
	//fmt.Println(arrf)
	//fmt.Println(arrb)
	ans := 0
	for i := 0; i < n; i++ {
		if ans < arrb[n - i - 1] {
			ans = arrb[n - i - 1]
		}
		if ans < arrf[i] {
			ans = arrf[i]
		}
		if str[i] == 'S' {
			curSum := arrb[n - i - 1] + arrf[i] + 1
			if curSum <= cntG && ans < curSum {
				ans = curSum
			}
			if curSum == cntG + 1 && ans < curSum {
				ans = curSum - 1
			}
		}
	}
	fmt.Println(ans)
}

package main

import "fmt"

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

func calc(x, y, total int) int {
	if x+y == total {
		return total
	}
	return x + y + 1
}

func gao(segments []int, totalGolds int) int {
	if len(segments) <= 1 {
		return totalGolds
	}
	ans := 0
	for i := 1; i < len(segments); i++ {
		ans = maxInt(ans, calc(segments[i-1], segments[i], totalGolds))
	}
	return ans
}

func main() {
	var (
		n        int
		trophies []byte
	)
	_, _ = fmt.Scanln(&n)
	_, _ = fmt.Scanln(&trophies)
	nGolds, totalGolds := 0, 0
	var segments []int
	for _, ch := range trophies {
		if ch == 'G' {
			nGolds++
			totalGolds++
			continue
		}
		segments = append(segments, nGolds)
		nGolds = 0
	}
	if nGolds > 0 {
		segments = append(segments, nGolds)
	}
	fmt.Printf("%v\n", gao(segments, totalGolds))
}

package main

import (
	"bufio"
	"fmt"
	"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 max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func main() {
	defer writer.Flush()
	var n, mx, tot int
	scanf("%d\n", &n)
	lft := make([]int, n)
	rt := make([]int, n)
	var s string
	scanf("%s\n", &s)
	for i := 0; i < n; i++ {
		if i == 0 {
			if s[i] == 'G' {
				lft[i] = 1
				tot++
				mx = max(mx, lft[i])
			} else {
				lft[i] = 0
			}
		} else {
			if s[i] == 'G' {
				lft[i] = 1 + lft[i-1]
				mx = max(mx, lft[i])
				tot++
			} else {
				lft[i] = 0
			}
		}
	}
	for i := n - 1; i >= 0; i-- {
		if i == n-1 {
			if s[i] == 'G' {
				rt[i] = 1
				mx = max(mx, rt[i])
			} else {
				rt[i] = 0
			}
		} else {
			if s[i] == 'G' {
				rt[i] = 1 + rt[i+1]
				mx = max(mx, rt[i])
			} else {
				rt[i] = 0
			}
		}
	}
	//fmt.Println(tot)
	for i := 1; i < n-1; i++ {
		if s[i] == 'S' {
			cur := lft[i-1] + rt[i+1]
			if tot != cur {
				mx = max(cur+1, mx)
			} else {
				mx = max(mx, tot)
			}
		}
	}
	printf("%d\n", mx)
}

// Seperate the string to groups, for each group,
// there will be a chance to replace a S to G right after that group
package main

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

var scanner = bufio.NewScanner(os.Stdin)

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1000000)
	n, line, groups := 0, "", [][2]int{}
	fmt.Fscanf(reader, "%d\n%s\n", &n, &line)
	l, r := -1, -1
	// Break the input into G groups, each group stands by [lIndex, RIndex]
	for i := 0; i < len(line); i++ {
		if line[i:i+1] == "G" {
			if l != -1 {
				r++
			} else {
				l, r = i, i
			}
			if i == (len(line) - 1) {
				groups = append(groups, [2]int{l, r})
			}
			continue
		}
		if l != -1 {
			groups = append(groups, [2]int{l, r})
		}
		l, r = -1, -1
	}

	max := 0
	for i := 0; i < len(groups); i++ {
		res := groups[i][1] - groups[i][0] + 1
		if i == (len(groups) - 1) {
			if i > 0 {
				res++
			}
		} else {
			res++
			if (groups[i+1][0] - groups[i][1]) == 2 {
				res += groups[i+1][1] - groups[i+1][0] + 1
				if (i == (len(groups) - 2)) && (i == 0) {
					res--
				}
			}
		}

		if max < res {
			max = res
		}
	}

	fmt.Println(max)
}

package main

import (
	"fmt"
	"bufio"
	"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 max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func main(){
	defer writer.Flush()
	var n,l,r,ans,cnt,m,i int
	var a, b []int
	var s string
	scanf("%d\n", &n)
	scanf("%s\n", &s)
	// printf("read : %s\n", s)
	cnt = 0
	for i=0;i<n;i++ {
		if s[i] == 'G' {
			cnt++
		}
	}
	m=0
	l=0
	r=0
	for l < n {
		if l == r {
			r++
		} else if r < n && s[r] == 'G' {
			r++
		} else if s[l] != 'G' {
			l++
		} else {
			m++
			a = append(a, l)
			b = append(b, r)
			// printf("add %d %d\n", l, r)
			l = r
		}
	}
	ans = 0
	for i=0;i<m;i++ {
		ans = max(ans, b[i]-a[i])
	}
	for i=1;i<m;i++ {
		if a[i] - b[i-1] == 1 {
			ans = max(ans, b[i]-a[i] + b[i-1] - a[i-1])
			if m > 2 {
				ans = max(ans, b[i]-a[i] + b[i-1] - a[i-1] + 1)
			}
		}
	}
	printf("%d\n", ans)
}

package main

import (
	"fmt"
)

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

type cut struct {
	start, end int
}

func (p* cut) len() int {
	return p.end - p.start  + 1
}

func check(s []byte) int {
	if len(s) == 0 {
		return 0
	}
	var pcur *cut
	var cuts []*cut
	for i := 0; i < len(s); i++ {
		if s[i] == 71 {
			if pcur == nil {
				pcur = &cut{start:i}
			}
		} else {
			if pcur != nil {
				pcur.end = i - 1
				cuts = append(cuts, pcur)
				pcur = nil
			}
		}
	}
	if pcur != nil {
		pcur.end = len(s) - 1
		cuts = append(cuts, pcur)
	}

	return check_cuts(cuts)
}

func adj(a, b *cut) bool {
	return b.start - a.end == 2
}

func check_cuts(cuts []*cut) int {
	if len(cuts) == 10 {
		return 0
	}
	if len(cuts) == 1 {
		return cuts[0].len()
	}
	if len(cuts) == 2 {
		a, b := cuts[0], cuts[1]
		if adj(a, b) {
			return b.len() + a.len()
		} else {
			return max(b.len(), a.len())
		}
	}
	var prev, selected *cut
	var sel_size int
	for _, pc := range cuts {
		if selected == nil {
			selected = pc
			sel_size = pc.len() + 1
			prev = pc
			continue
		}

		cur_size := pc.len()
		if adj(prev, pc) {
			cur_size += prev.len() + 1
		} else {
			cur_size += 1
		}

		if cur_size > sel_size {
			selected = pc
			sel_size = cur_size
		}

		prev = pc
	}
	return sel_size
}

func main() {
	var n int
	fmt.Scanln(&n)
	s := make([]byte, n)
	fmt.Scanln(&s)
	fmt.Println(check(s))
}

package main

import (
	"fmt"
)

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

type cut struct {
	start, end int
}

func (p* cut) len() int {
	return p.end - p.start  + 1
}

func check(s []byte) int {
	if len(s) == 0 {
		return 0
	}
	var pcur *cut
	var cuts []*cut
	for i := 0; i < len(s); i++ {
		if s[i] == 71 {
			if pcur == nil {
				pcur = &cut{start:i}
			}
		} else {
			if pcur != nil {
				pcur.end = i - 1
				cuts = append(cuts, pcur)
				pcur = nil
			}
		}
	}
	if pcur != nil {
		pcur.end = len(s) - 1
		cuts = append(cuts, pcur)
	}

	return check_cuts(cuts)
}

func adj(a, b *cut) bool {
	return b.start - a.end == 2
}

func check_cuts(cuts []*cut) int {
	if len(cuts) == 10 {
		return 0
	}
	if len(cuts) == 1 {
		return cuts[0].len()
	}
	if len(cuts) == 2 {
		a, b := cuts[0], cuts[1]
		if adj(a, b) {
			return b.len() + a.len()
		} else {
			return max(b.len(), a.len()) + 1
		}
	}
	var prev *cut
	var selSize int
	for _, pc := range cuts {
		if prev == nil {
			selSize = pc.len() + 1
			prev = pc
			continue
		}

		curSize := pc.len() + 1
		if adj(prev, pc) {
			curSize += prev.len()
		}

		if curSize > selSize {
			selSize = curSize
		}

		prev = pc
	}
	return selSize
}

func main() {
	var n int
	fmt.Scanln(&n)
	s := make([]byte, n)
	fmt.Scanln(&s)
	fmt.Println(check(s))
}

package main

import (
	"fmt"
)

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

type cut struct {
	start, end int
}

func (p* cut) len() int {
	return p.end - p.start  + 1
}

func check(s []byte) int {
	if len(s) == 0 {
		return 0
	}
	var pcur *cut
	var cuts []*cut
	for i := 0; i < len(s); i++ {
		if s[i] == 71 {
			if pcur == nil {
				pcur = &cut{start:i}
			}
		} else {
			if pcur != nil {
				pcur.end = i - 1
				cuts = append(cuts, pcur)
				pcur = nil
			}
		}
	}
	if pcur != nil {
		pcur.end = len(s) - 1
		cuts = append(cuts, pcur)
	}

	return check_cuts(cuts)
}

func adj(a, b *cut) bool {
	return b.start - a.end == 2
}

func check_cuts(cuts []*cut) int {
	if len(cuts) == 10 {
		return 0
	}
	if len(cuts) == 1 {
		return cuts[0].len()
	}
	if len(cuts) == 2 {
		a, b := cuts[0], cuts[1]
		if adj(a, b) {
			return b.len() + a.len()
		} else {
			return max(b.len(), a.len())
		}
	}
	var prev, selected *cut
	var sel_size int
	for _, pc := range cuts {
		if selected == nil {
			selected = pc
			sel_size = pc.len()
			prev = pc
			continue
		}

		cur_size := pc.len()
		if adj(prev, pc) {
			cur_size += prev.len() + 1
		}

		if cur_size > sel_size {
			selected = pc
			sel_size = cur_size
		}

		prev = pc
	}
	return sel_size
}

func main() {
	var n int
	fmt.Scanln(&n)
	s := make([]byte, n)
	fmt.Scanln(&s)
	fmt.Println(check(s))
}

package main

import (
  "fmt"
)

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

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

  lhs := make([]int, n)
  rhs := make([]int, n)

  var c, tot, sol int = 0, 0, 0

  for i, ch := range(s) {
    lhs[i] = c
    if ch == 'G' {
      c += 1
      tot += 1
    } else {
      c = 0
    }
    sol = max(sol, c)
  }

  c = 0
  for i := len(s)-1; i >= 0; i -=1 {
    rhs[i] = c
    if s[i] == 'G' {
      c += 1
    } else {
      c = 0
    }
    sol = max(sol, c)
  }

  for i, ch := range(s) {
    if ch == 'S' {
      tmp := lhs[i] + rhs[i]
      if (tmp < tot) {
        sol = max(sol, tmp + 1)
      }
    }
  }

  fmt.Println(sol)
}

package main

import (
	"fmt"
)

func main() {
	var n int
	var str string
	fmt.Scan(&n, &str)
	cnt := 0
	cntG := 0
	arrf := make([]int, 0)
	for i := 0; i < n; i++ {
		if str[i] == 'G' {
			cnt++
			cntG++
			arrf = append(arrf, cnt)
		} else {
			arrf = append(arrf, cnt)
			cnt = 0
		}
	}
	cnt = 0
	arrb := make([]int, 0)
	for i := n - 1; i >= 0; i-- {
		if str[i] == 'G' {
			cnt++
			arrb = append(arrb, cnt)
		} else {
			arrb = append(arrb, cnt)
			cnt = 0
		}
	}
	ans := 0
	for i := 0; i < n; i++ {
		if ans < arrb[n - i - 1] {
			ans = arrb[n - i - 1]
		}
		if ans < arrf[i] {
			ans = arrf[i]
		}
		if str[i] == 'S' {
			curSum := arrb[n - i - 1] + arrf[i] + 1
			if curSum <= cntG && ans < curSum {
				ans = curSum
			}
		}
	}
	fmt.Println(ans)
}

package main

import (
	"bufio"
	"fmt"
	"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 max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func main() {
	defer writer.Flush()
	var n, mx, tot int
	scanf("%d\n", &n)
	lft := make([]int, n)
	rt := make([]int, n)
	var s string
	scanf("%s\n", &s)
	for i := 0; i < n; i++ {
		if i == 0 {
			if s[i] == 'G' {
				lft[i] = 1
				tot++
				mx = max(mx, lft[i])
			} else {
				lft[i] = 0
			}
		} else {
			if s[i] == 'G' {
				lft[i] = 1 + lft[i-1]
				mx = max(mx, lft[i])
				tot++
			} else {
				lft[i] = 0
			}
		}
	}
	for i := n - 1; i >= 0; i-- {
		if i == n-1 {
			if s[i] == 'G' {
				rt[i] = 1
				mx = max(mx, rt[i])
			} else {
				rt[i] = 0
			}
		} else {
			if s[i] == 'G' {
				rt[i] = 1 + rt[i+1]
				mx = max(mx, rt[i])
			} else {
				rt[i] = 0
			}
		}
	}
	for i := 1; i < n-1; i++ {
		if s[i] == 'S' {
			cur := lft[i-1] + rt[i+1]
			if tot != cur && cur > 1 {
				mx = max(cur+1, mx)
			} else {
				mx = max(mx,tot)
			}
		}
	}
	printf("%d\n", mx)
}

package main

import (
	"bufio"
	"fmt"
	"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 max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func main() {
	defer writer.Flush()
	var n, mx, tot int
	scanf("%d\n", &n)
	lft := make([]int, n)
	rt := make([]int, n)
	var s string
	scanf("%s\n", &s)
	for i := 0; i < n; i++ {
		if i == 0 {
			if s[i] == 'G' {
				lft[i] = 1
				tot++
				mx = max(mx, lft[i])
			} else {
				lft[i] = 0
			}
		} else {
			if s[i] == 'G' {
				lft[i] = 1 + lft[i-1]
				mx = max(mx, lft[i])
				tot++
			} else {
				lft[i] = 0
			}
		}
	}
	for i := n - 1; i >= 0; i-- {
		if i == n-1 {
			if s[i] == 'G' {
				rt[i] = 1
				mx = max(mx, rt[i])
			} else {
				rt[i] = 0
			}
		} else {
			if s[i] == 'G' {
				rt[i] = 1 + rt[i+1]
				mx = max(mx, rt[i])
			} else {
				rt[i] = 0
			}
		}
	}
	for i := 1; i < n-1; i++ {
		if s[i] == 'S' {
			cur := lft[i-1] + rt[i+1]
			if tot != cur && cur > 1 {
				mx = max(cur+1, mx)
			} else {
				mx = tot
			}
		}
	}
	printf("%d\n", mx)
}

// Seperate the string to groups, for each group,
// there will be a chance to replace a S to G right after that group
package main

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

var scanner = bufio.NewScanner(os.Stdin)

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1000000)
	n, line, groups := 0, "", [][2]int{}
	fmt.Fscanf(reader, "%d\n%s\n", &n, &line)
	l, r := -1, -1
	// Break the input into G groups, each group stands by [lIndex, RIndex]
	for i := 0; i < len(line); i++ {
		if line[i:i+1] == "G" {
			if l != -1 {
				r++
			} else {
				l, r = i, i
			}
			if i == (len(line) - 1) {
				groups = append(groups, [2]int{l, r})
			}
			continue
		}
		if l != -1 {
			groups = append(groups, [2]int{l, r})
		}
		l, r = -1, -1
	}

	max := 0
	for i := 0; i < len(groups); i++ {
		res := groups[i][1] - groups[i][0] + 1
		if i == (len(groups) - 1) {
			if i > 0 {
				res++
			}
		} else {
			res++
			if (groups[i][1] - groups[i+1][0]) == 2 {
				res += groups[i+1][1] - groups[i+1][0] + 1
				if (i == (len(groups) - 2)) && (i == 0) {
					res--
				}
			}
		}

		if max < res {
			max = res
		}
	}

	fmt.Println(max)
}

// Seperate the string to groups, for each group,
// there will be a chance to replace a S to G right after that group
package main

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

var scanner = bufio.NewScanner(os.Stdin)

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1000000)
	n, line, groups := 0, "", [][2]int{}
	fmt.Fscanf(reader, "%d\n%s\n", &n, &line)
	l, r := -1, -1
	// Break the input into G groups, each group stands by [lIndex, RIndex]
	for i := 0; i < len(line); i++ {
		if line[i:i+1] == "G" {
			if l != -1 {
				r++
			} else {
				l, r = i, i
			}
			if i == (len(line) - 1) {
				groups = append(groups, [2]int{l, r})
			}
			continue
		}
		if l != -1 {
			groups = append(groups, [2]int{l, r})
		}
		l, r = -1, -1
	}

	max := 0
	for i := 0; i < len(groups); i++ {
		res := groups[i][1] - groups[i][0] + 1
		if i == (len(groups) - 1) {
			if i > 0 {
				res++
			}
		} else {
			res++
			if groups[i+1][0] == (groups[i][1] + 2) {
				extra := groups[i+1][1] - groups[i+1][0] + 1
				res += extra
				if i == (len(groups)-2) && (extra > 1) {
					res--
				}
			}
		}
		if max < res {
			max = res
		}
	}
	fmt.Println(max)
}

// Seperate the string to groups, for each group,
// there will be a chance to replace a S to G right after that group
package main

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

var scanner = bufio.NewScanner(os.Stdin)

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1000000)
	n, line, groups := 0, "", [][2]int{}
	fmt.Fscanf(reader, "%d\n%s\n", &n, &line)
	l, r := -1, -1
	// Break the input into G groups, each group stands by [lIndex, RIndex]
	for i := 0; i < len(line); i++ {
		if line[i:i+1] == "G" {
			if l != -1 {
				r++
			} else {
				l, r = i, i
			}
			if i == (len(line) - 1) {
				groups = append(groups, [2]int{l, r})
			}
			continue
		}
		if l != -1 {
			groups = append(groups, [2]int{l, r})
		}
		l, r = -1, -1
	}

	max := 0
	for i := 0; i < len(groups); i++ {
		res := groups[i][1] - groups[i][0] + 1
		if i == (len(groups) - 1) {
			if i > 1 {
				res++
			}
		} else {
			res++
			if groups[i+1][0] == (groups[i][1] + 2) {
				res += groups[i+1][1] - groups[i+1][0] + 1
			}
			if i == (len(groups) - 2) {
				res--
			}
		}
		if max < res {
			max = res
		}
	}
	fmt.Println(max)
}

// Seperate the string to groups, for each group,
// there will be a chance to replace a S to G right after that group
package main

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

var scanner = bufio.NewScanner(os.Stdin)

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1000000)
	n, line, groups := 0, "", [][2]int{}
	fmt.Fscanf(reader, "%d\n%s\n", &n, &line)
	l, r := -1, -1
	// Break the input into G groups, each group stands by [lIndex, RIndex]
	for i := 0; i < len(line); i++ {
		if line[i:i+1] == "G" {
			if l != -1 {
				r++
			} else {
				l, r = i, i
			}
			if i == (len(line) - 1) {
				groups = append(groups, [2]int{l, r})
			}
			continue
		}
		if l != -1 {
			groups = append(groups, [2]int{l, r})
		}
		l, r = -1, -1
	}

	max := 0
	for i := 0; i < len(groups); i++ {
		res := groups[i][1] - groups[i][0] + 1
		if i == (len(groups) - 1) {
			if i > 0 {
				res++
			}
		} else {
			res++
			if groups[i+1][0] == (groups[i][1] + 2) {
				res += groups[i+1][1] - groups[i+1][0] + 1
				if i == (len(groups) - 2) {
					res--
				}
			}
		}
		if max < res {
			max = res
		}
	}
	fmt.Println(max)
}

// Seperate the string to groups, for each group,
// there will be a chance to replace a S to G right after that group
package main

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

var scanner = bufio.NewScanner(os.Stdin)

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1000000)
	n, line, groups := 0, "", [][2]int{}
	fmt.Fscanf(reader, "%d\n%s\n", &n, &line)
	l, r := -1, -1
	// Break the input into G groups, each group stands by [lIndex, RIndex]
	for i := 0; i < len(line); i++ {
		if line[i:i+1] == "G" {
			if l != -1 {
				r++
			} else {
				l, r = i, i
			}
			if i == (len(line) - 1) {
				groups = append(groups, [2]int{l, r})
			}
			continue
		}
		if l != -1 {
			groups = append(groups, [2]int{l, r})
		}
		l, r = -1, -1
	}

	max := 0
	for i := 0; i < len(groups); i++ {
		res := groups[i][1] - groups[i][0] + 1
		if i == (len(groups) - 1) {
			if i > 1 {
				res++
			}
		} else {
			res++
			if groups[i+1][0] == (groups[i][1] + 2) {
				res += groups[i+1][1] - groups[i+1][0] + 1
				if i == (len(groups) - 2) {
					res--
				}
			}
		}
		if max < res {
			max = res
		}
	}
	fmt.Println(max)
}

// Seperate the string to groups, for each group,
// there will be a chance to replace a S to G right after that group
package main

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

var scanner = bufio.NewScanner(os.Stdin)

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1000000)
	n, line, groups := 0, "", [][2]int{}
	fmt.Fscanf(reader, "%d\n%s\n", &n, &line)
	l, r := -1, -1
	// Break the input into G groups, each group stands by [lIndex, RIndex]
	for i := 0; i < len(line); i++ {
		if line[i:i+1] == "G" {
			if l != -1 {
				r++
			} else {
				l, r = i, i
			}
			if i == (len(line) - 1) {
				groups = append(groups, [2]int{l, r})
			}
			continue
		}
		if l != -1 {
			groups = append(groups, [2]int{l, r})
		}
		l, r = -1, -1
	}

	max := 0
	for i := 0; i < len(groups); i++ {
		res := groups[i][1] - groups[i][0] + 1
		if i == (len(groups) - 1) {
			if i > 0 {
				res++
			}
		} else {
			res++
			if groups[i+1][0] == (groups[i][1] + 2) {
				extra := groups[i+1][1] - groups[i+1][0] + 1
				res += extra
				if i == (len(groups)-2) && (extra > 1) && (i == 0) {
					res--
				}
			}
		}
		if max < res {
			max = res
		}
	}
	fmt.Println(max)
}


Vlad and Nastya live in a city consisting of $$$n$$$ houses and $$$n-1$$$ road. From each house, you can get to the other by moving only along the roads. That is, the city is a tree.Vlad lives in a house with index $$$x$$$, and Nastya lives in a house with index $$$y$$$. Vlad decided to visit Nastya. However, he remembered that he had postponed for later $$$k$$$ things that he has to do before coming to Nastya. To do the $$$i$$$-th thing, he needs to come to the $$$a_i$$$-th house, things can be done in any order. In $$$1$$$ minute, he can walk from one house to another if they are connected by a road.Vlad does not really like walking, so he is interested what is the minimum number of minutes he has to spend on the road to do all things and then come to Nastya. Houses $$$a_1, a_2, \dots, a_k$$$ he can visit in any order. He can visit any house multiple times (if he wants).

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. There is an empty line before each test case. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) — the number of houses and things, respectively. The second line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$) — indices of the houses where Vlad and Nastya live, respectively. The third line of each test case contains $$$k$$$ integers $$$a_1, a_2, \dots, a_k$$$ ($$$1 \le a_i \le n$$$) — indices of houses Vlad need to come to do things. The following $$$n-1$$$ lines contain description of city, each line contains two integers $$$v_j$$$ and $$$u_j$$$ ($$$1 \le u_j, v_j \le n$$$) — indices of houses connected by road $$$j$$$. It is guaranteed that the sum of $$$n$$$ for all cases does not exceed $$$2\cdot10^5$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer output single integer — the minimum number of minutes Vlad needs on the road to do all the things and come to Nastya.

NoteTree and best path for the first test case:  $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$ Tree and best path for the second test case:  $$$3 \rightarrow 1 \rightarrow 3 \rightarrow 5 \rightarrow 2 \rightarrow 5 \rightarrow 6 \rightarrow 5$$$ Tree and best path for the third test case:  $$$3 \rightarrow 5 \rightarrow 2$$$

package main
import("bufio";."fmt";"os")

// github.com/EndlessCheng/codeforces-go
func main() {
	in:=bufio.NewReader(os.Stdin)
	var T,n,k,x,y,v,w int
	for Fscan(in,&T);T>0;T--{
		Fscan(in,&n,&k,&x,&y)
		a:=make([]bool,n+1)
		a[y]=true
		for;k>0;k--{Fscan(in,&v);a[v]=true}
		g:=make([][]int,n+1)
		for i:=1;i<n;i++{
			Fscan(in,&v,&w)
			g[v]=append(g[v],w)
			g[w]=append(g[w],v)
		}
		ans:=n*2-2
		var f func(v,p,d int)bool
		f=func(v,p,d int)bool{
			if v==y{ans-=d}
			c:=a[v]
			for _,w:=range g[v]{
				if w!=p&&f(w,v,d+1){c=true}
			}
			if!c{ans-=2}
			return c
		}
		f(x,0,0)
		Println(ans)
	}
}

package main

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

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

	var T, n, k, x, y, v, w int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k, &x, &y)
		need := make([]bool, n+1)
		for ; k > 0; k-- {
			Fscan(in, &v)
			need[v] = true
		}
		need[x] = true
		need[y] = true
		g := make([][]int, n+1)
		for i := 1; i < n; i++ {
			Fscan(in, &v, &w)
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}

		ans := n*2 - 2
		var f func(v, fa, d int) bool
		f = func(v, fa, d int) bool {
			if v == y {
				ans -= d
			}
			found := need[v]
			for _, w := range g[v] {
				if w != fa && f(w, v, d+1) {
					found = true
				}
			}
			if !found {
				ans -= 2
			}
			return found
		}
		f(x, 0, 0)
		Fprintln(out, ans)
	}
}

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

package main

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

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

	var T, n, k, x, y, v, w int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k, &x, &y)
		need := make([]bool, n+1)
		for ; k > 0; k-- {
			Fscan(in, &v)
			need[v] = true
		}
		need[x] = true
		need[y] = true
		deg := make([]int, n+1)
		g := make([][]int, n+1)
		for i := 1; i < n; i++ {
			Fscan(in, &v, &w)
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
			deg[v]++
			deg[w]++
		}

		ans := n*2 - 2
		del := make([]bool, n+1)
		q := []int{}
		for i, d := range deg {
			if d == 1 && !need[i] {
				q = append(q, i)
			}
		}
		for len(q) > 0 {
			v := q[0]
			q = q[1:]
			del[v] = true
			ans -= 2
			for _, w := range g[v] {
				if deg[w]--; deg[w] == 1 && !need[w] {
					q = append(q, w)
				}
			}
		}

		var f func(v, fa, d int) bool
		f = func(v, fa, d int) bool {
			if v == y {
				ans -= d
				return true
			}
			for _, w := range g[v] {
				if w != fa && !del[w] {
					if f(w, v, d+1) {
						return true
					}
				}
			}
			return false
		}
		f(x, 0, 0)
		Fprintln(out, ans)
	}
}

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

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)
func slove() {
	defer w.Flush()
	var n, k int
	fmt.Fscan(r, &n, &k)
	var x, y int
	fmt.Fscan(r, &x, &y)
	x, y = x-1, y-1
	pass := make(map[int]bool)
	for i:=0;i<k;i++ {
		var a int
		fmt.Fscan(r, &a)
		pass[a-1] = true
	}
	edge := make([][]int, n)
	for i:=0;i<n-1;i++ {
		var a, b int
		fmt.Fscan(r, &a, &b)
		edge[a-1] = append(edge[a-1], b-1)
		edge[b-1] = append(edge[b-1], a-1)
	}
	l := 0
	var dfs func(i, from, level int) int
	dfs = func(i, from, level int) int {
		if i == y {
			l = level
		}
		ans := 0
		for _, j := range edge[i] {
			if j == from {
				continue
			}
			a := dfs(j, i, level+1)
			if a != -1 {
				ans += 2 + a
			}
		}
		if _, ok := pass[i]; ok || i == y {
			return ans
		}
		if ans == 0 {
			return -1
		} else {
			return ans
		}
	}
	fmt.Fprintln(w, dfs(x, -1, 0)-l)
}

func main() {
	var n int
	fmt.Fscan(r, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func gis(n int) []int  { res := make([]int,n); for i:=0;i<n;i++ { res[i] = gi() }; return res }
func ia(m int) []int { return make([]int,m) }
func fill2(m int) ([]int,[]int) { a,b := ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i] = gi(),gi()}; return a,b }
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N,K := gi(),gi(); X,Y := gi(),gi(); X--; Y--; A := gis(K); for i:=0;i<K;i++ { A[i]-- }; U,V := fill2(N-1); for i:=0;i<N-1;i++ { U[i]--; V[i]-- }
		//Build the graph
		gr := make([][]int,N)
		for i:=0;i<N-1;i++ { u,v := U[i],V[i]; gr[u] = append(gr[u],v); gr[v] = append(gr[v],u) }
		//Mark the path down to the target
		needToVisit := make([]bool,N); for _,a := range A { needToVisit[a] = true }
		pathToY := make([]bool,N)
		var dfs1 func(n,p int) bool
		dfs1 = func(n,p int) bool {
			ans := false
			if n == Y { ans = true }
			for _,c := range gr[n] { if c != p && dfs1(c,n) { ans = true } }
			pathToY[n] = ans
			return ans
		}
		dfs1(X,-1)
		var dfs2 func(n,p int) bool
		dfs2 = func(n,p int) bool {
			ans := false
			if needToVisit[n] || pathToY[n] { ans = true }
			for _,c := range gr[n] { if c != p && dfs2(c,n) { ans = true } }
			needToVisit[n] = ans
			return ans
		}
		dfs2(X,-1)
		var dfs3 func(n,p int) int
		dfs3 = func(n,p int) int {
			ans := 0
			for _,c := range gr[n] {
				if c == p || !needToVisit[c] { continue }
				cans := dfs3(c,n)
				if pathToY[c] { ans += 1 + cans } else { ans += 2 + cans }
			}
			return ans
		}
		ans := dfs3(X,-1)
		fmt.Fprintln(wrtr,ans)
	}
}

package main

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

var wr = bufio.NewWriter(os.Stdout)
var rd = bufio.NewScanner(os.Stdin)

func nextInt() int {
	rd.Scan()
	if n, err := strconv.Atoi(rd.Text()); err == nil {
		return n
	}
	return 0
}
func Max(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}
func Min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func main() {
	defer wr.Flush()
	rd.Buffer(make([]byte, 0), 1000000009)
	rd.Split(bufio.ScanWords)
	T := nextInt()
	for Case := 0; Case < T; Case++ {
		solve()
	}
}

var N = 200010
var n, k, x, y int
var d1 = make([]int, N)
var d2 = make([]int, N)
var head = make([]int, N)
var nxt = make([]int, N*2)
var to = make([]int, N*2)
var vis = make([]bool, N)
var st = make([]bool, N)
var fa = make([]int, N)
var tot = -1

func add(a, b int) {
	tot++
	nxt[tot] = head[a]
	to[tot] = b
	head[a] = tot
}
func dfs(u, pre, dep int, dis []int, ok bool) {
	dis[u] = dep
	if ok {
		fa[u] = pre
	}
	for i := head[u]; i != -1; i = nxt[i] {
		if to[i] != pre {
			dfs(to[i], u, dep+1, dis, ok)
		}
	}
}
func solve() {
	n, k, x, y = nextInt(), nextInt(), nextInt(), nextInt()
	tot = -1
	for i := 1; i <= n; i++ {
		head[i] = -1
		vis[i] = false
		st[i] = false
	}
	for i := 1; i <= k; i++ {
		t := nextInt()
		vis[t] = true
	}
	for i := 1; i < n; i++ {
		a, b := nextInt(), nextInt()
		add(a, b)
		add(b, a)
	}
	dfs(x, -1, 0, d1, true)
	dfs(y, -1, 0, d2, false)
	res := 0
	st[x]=true
	for i := 1; i <= n; i++ {
		if !vis[i] || st[i]{
			continue
		}
		t := i
		st[t] = true
		res += 2
		for fa[t] != -1 && !st[fa[t]] {
			t = fa[t]
			st[t] = true
			res += 2
			// fmt.Fprint(wr, " ", t)
		}
		// fmt.Fprint(wr, " ", res, "X\n")
	}
	ans := 0x3f3f3f3f
	for i := 1; i <= n; i++ {
		if vis[i] {
			ans = Min(ans, d2[i]-d1[i])
		}
	}
	fmt.Fprint(wr, ans+res, "\n")
}

package main

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

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

	var T, n, k, x, y, v, w int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k, &x, &y)
		need := make([]bool, n+1)
		for ; k > 0; k-- {
			Fscan(in, &v)
			need[v] = true
		}
		need[x] = true
		need[y] = true
		g := make([][]int, n+1)
		for i := 1; i < n; i++ {
			Fscan(in, &v, &w)
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}

		ans := n*2 - 2
		var f func(v, fa, d int) bool
		f = func(v, fa, d int) bool {
			if v == y {
				ans -= d
				return true
			}
			found := need[v]
			for _, w := range g[v] {
				if w != fa && f(w, v, d+1) {
					found = true
				}
			}
			if !found {
				ans -= 2
			}
			return found
		}
		f(x, 0, 0)
		Fprintln(out, ans)
	}
}

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

package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

	for ii := 0; ii < t; ii++ {
		var n, k, x, y int
		fmt.Fscan(in, &n, &k, &x, &y)
		task := make(map[int]bool)
		for i := 0; i < k; i++ {
			ta := 0
			fmt.Fscan(in, &ta)
			if ta == x || ta == y {
				continue
			}
			task[ta] = true
		}
		path := make([][]int, n+1)
		for i := 0; i < n-1; i++ {
			a, b := 0, 0
			fmt.Fscan(in, &a, &b)
			path[a] = append(path[a], b)
			path[b] = append(path[b], a)
		}
		alone := make(map[int]bool)
		var findy func(i, last int) bool
		findy = func(i, last int) bool {
			if i == y {
				return true
			}
			for _, j := range path[i] {
				if j == last {
					continue
				}
				ok := findy(j, i)
				if i != x {
					alone[i] = true
				}
				if ok {
					delete(task, i)
					return true
				}
			}
			return false
		}
		findy(x, x)
		visited := make(map[int]bool)
		ans := 0
		//fmt.Println(alone, task)
		var dfs func(i int, length int)
		dfs = func(i int, length int) {
			visited[i] = true
			if i == y {
				ans += length
				length = 0
			}
			if task[i] {
				ans += length * 2
				length = 0
			}
			//fmt.Println(i, ans)
			for _, j := range path[i] {
				if visited[j] {
					continue
				}
				if !alone[j] && alone[i] && j != y {
					dfs(j, 1)
				} else {
					dfs(j, length+1)
				}
			}

		}
		dfs(x, 0)
		fmt.Fprintln(out, ans)
	}
}

package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

	for ii := 0; ii < t; ii++ {
		var n, k, x, y int
		fmt.Fscan(in, &n, &k, &x, &y)
		task := make(map[int]bool)
		for i := 0; i < k; i++ {
			ta := 0
			fmt.Fscan(in, &ta)
			if ta == x || ta == y {
				continue
			}
			task[ta] = true
		}
		path := make([][]int, n+1)
		for i := 0; i < n-1; i++ {
			a, b := 0, 0
			fmt.Fscan(in, &a, &b)
			path[a] = append(path[a], b)
			path[b] = append(path[b], a)
		}
		var findy func(i, last int) bool
		findy = func(i, last int) bool {
			if i == y {
				return true
			}
			for _, j := range path[i] {
				if j == last {
					continue
				}
				ok := findy(j, i)
				if ok {
					delete(task, i)
					return true
				}
			}
			return false
		}
		findy(x, x)
		visited := make(map[int]bool)
		ans := 0
		var dfs func(i int, length int)
		dfs = func(i int, length int) {
			visited[i] = true
			if i == y {
				ans += length
				length = 0
			}
			if task[i] {
				ans += length * 2
				length = 0
			}
			for _, j := range path[i] {
				if visited[j] {
					continue
				}
				dfs(j, length+1)
			}
		}
		dfs(x, 0)
		fmt.Fprintln(out, ans)
	}
}


There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood.  King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.

The first line contains number n, which is the number of knights at the round table (3 ≤ n ≤ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.

Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".

package main

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

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	mood := make([]int, n)
	for i := 0;i < n - 1;i ++ {
		fmt.Fscanf(reader, "%d ", &mood[i])
	}
	fmt.Fscanf(reader, "%d\n", &mood[n - 1])
	for i := 1;2 * i < n;i ++ {
		if n % i != 0 {
			continue
		}
		for j := 0;j < i;j ++ {
			ok := 1
			for k := j;k < n; k += i {
				ok *= mood[k]
			}
			if ok == 1 {
				fmt.Printf("YES")
				return
			}
		}
	}
	fmt.Printf("NO")
	return
}

package main

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

var scanner *bufio.Scanner

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

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

  n := getI()
  knights := make([]int, n)
  for i := 0; i < n; i++ {
    knights[i] = getI()
  }
  for a := 3; a <= n; a++ {
    if n%a == 0 {
      fmt.Fprintf(os.Stderr, "a = %d\n", a)
      b := n/a
      for i := 0; i < b; i++ {
        okay := true
        for j := i; j < n; j += b {
          if knights[j] == 0 {
            okay = false
            break
          }
        }
        if okay {
          fmt.Fprintf(os.Stderr, "a = %d, b = %d, i = %d\n", a, b, i)
          writer.WriteString("YES\n")
          return
        }
      }
    }
  }
  writer.WriteString("NO\n")
}


A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are  roads in total. It takes exactly y seconds to traverse any single road.A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads.Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y.You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once.

The first line of the input contains three integers n, x and y (2 ≤ n ≤ 200 000, 1 ≤ x, y ≤ 109). Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree.

Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once.

NoteIn the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is .In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is .

package main

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

var in = bufio.NewScanner(os.Stdin)

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

type byDiff [][2]int

func (s byDiff) Len() int           { return len(s) }
func (s byDiff) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byDiff) Less(i, j int) bool { return s[i][0]-s[i][1] < s[j][0]-s[j][1] }

func main() {
	in.Split(bufio.ScanWords)
	n := int(readInt())
	x := readInt()
	y := readInt()
	edges := make([][]int, n)
	for i := 1; i < n; i++ {
		u := int(readInt() - 1)
		v := int(readInt() - 1)
		edges[u] = append(edges[u], v)
		edges[v] = append(edges[v], u)
	}
	if x >= y {
		for i := range edges {
			if len(edges[i]) == n-1 {
				fmt.Println(x + int64(n-2)*y)
				return
			}
		}
		fmt.Println(int64(n-1) * y)
		return
	}

	var drop func(v, p int) [2]int
	drop = func(v, p int) [2]int {
		var r [][2]int
		for _, u := range edges[v] {
			if u == p {
				continue
			}
			r = append(r, drop(u, v))
		}
		switch len(r) {
		case 0:
			return [2]int{0, 0}
		case 1:
			a := 1 + r[0][1]
			if a > r[0][0] {
				a = r[0][0]
			}
			return [2]int{a, a}
		}
		sort.Sort(byDiff(r))
		take := func(k int) int {
			t := len(r) - k
			for i := 0; i < k; i++ {
				t += r[i][0]
			}
			for i := k; i < len(r); i++ {
				t += r[i][1]
			}
			return t
		}
		a := take(0)
		b := take(1)
		c := take(2)
		if b > a {
			b = a
		}
		if c > b {
			c = b
		}
		return [2]int{b, c}
	}
	d := int64(drop(0, -1)[1])
	fmt.Println(d*y + (int64(n)-1-d)*x)
}

package main

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

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

var edges [][]int

func main() {
	defer out.Flush()
	var n int
	var x, y int64
	fmt.Fscan(in, &n, &x, &y)
	edges = make([][]int, n)
	for i := 0; i < n-1; i++ {
		var a, b int
		fmt.Fscan(in, &a, &b)
		a--
		b--
		edges[a] = append(edges[a], b)
		edges[b] = append(edges[b], a)
	}
	var xCount int
	if x >= y {
		if isStar() {
			xCount = 1
		} else {
			xCount = 0
		}
	} else {
		xCount, _ = solve(0, 0)
	}
	fmt.Fprintln(out, x*int64(xCount)+y*int64(n-1-xCount))
}

func isStar() bool {
	for _, vEdges := range edges {
		if len(vEdges) == len(edges)-1 {
			return true
		}
	}
	return false
}

func solve(v, parent int) (ans int, isAvail bool) {
	availChildren := 0
	for _, u := range edges[v] {
		if u == parent {
			continue
		}
		childAns, childIsAvail := solve(u, v)
		ans += childAns
		if childIsAvail {
			availChildren++
		}
	}
	switch availChildren {
	case 0:
		isAvail = true
	case 1:
		isAvail = true
		ans += 1
	default:
		isAvail = false
		ans += 2
	}
	return
}

package main

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

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

var edges [][]int

func main() {
	defer out.Flush()
	var n int
	var x, y int64
	fmt.Fscan(in, &n, &x, &y)
	edges = make([][]int, n)
	for i := 0; i < n-1; i++ {
		var a, b int
		fmt.Fscan(in, &a, &b)
		a--
		b--
		edges[a] = append(edges[a], b)
		edges[b] = append(edges[b], a)
	}
	var xCount int
	if x >= y {
		if isStar() {
			xCount = 1
		} else {
			xCount = 0
		}
	} else {
		xCount, _ = solve(0, 0)
	}
	fmt.Fprintln(out, x*int64(xCount)+y*int64(n-1-xCount))
}

func isStar() bool {
	for _, vEdges := range edges {
		if len(vEdges) == len(edges)-1 {
			return true
		}
	}
	return false
}

func solve(v, parent int) (ans int, isAvail bool) {
	availChildren := 0
	for _, u := range edges[v] {
		if u == parent {
			continue
		}
		dAns, childIsAvail := solve(u, v)
		ans += dAns
		if childIsAvail {
			availChildren++
		}
	}
	isAvail = availChildren < 2
	switch availChildren {
	case 0:
		isAvail = true
	case 1:
		isAvail = true
		ans += 1
	default:
		isAvail = false
		ans += 2
	}
	return
}

package main

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

var in = bufio.NewScanner(os.Stdin)

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

type byDiff [][2]int

func (s byDiff) Len() int           { return len(s) }
func (s byDiff) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byDiff) Less(i, j int) bool { return s[i][0]-s[i][1] < s[j][0]-s[j][1] }

func main() {
	in.Split(bufio.ScanWords)
	n := int(readInt())
	x := readInt()
	y := readInt()
	edges := make([][]int, n)
	for i := 1; i < n; i++ {
		u := int(readInt() - 1)
		v := int(readInt() - 1)
		edges[u] = append(edges[u], v)
		edges[v] = append(edges[v], u)
	}
	if x >= y {
		for i := range edges {
			if len(edges[i]) == n-1 {
				fmt.Println(x + int64(n-2)*y)
				return
			}
		}
		fmt.Println(int64(n-1) * y)
		return
	}

	var drop func(v, p int) [2]int
	drop = func(v, p int) [2]int {
		var r [][2]int
		for _, u := range edges[v] {
			if u == p {
				continue
			}
			r = append(r, drop(u, v))
		}
		switch len(r) {
		case 0:
			return [2]int{0, 0}
		case 1:
			a := 1 + r[0][1]
			if a > r[0][0] {
				a = r[0][0]
			}
			return [2]int{a, a}
		}
		sort.Sort(byDiff(r))
		take := func(k int) int {
			t := len(r) - k
			for i := 0; i < k; i++ {
				t += r[i][0]
			}
			for i := k; i < len(r); i++ {
				t += r[i][1]
			}
			return t
		}
		a := take(0)
		b := take(1)
		c := take(2)
		if b > a {
			b = a
		}
		if c > b {
			c = b
		}
		return [2]int{b, c}
	}
	d := int64(drop(0, -1)[1])
	fmt.Println(d)
	fmt.Println(d*y + (int64(n)-1-d)*x)
}

package main

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

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

var n int
var x, y int64
var edges [][]int
var xCount int
var yCount int
var childrenByHeight []ChildrenByHeight

func main() {
	defer out.Flush()
	fmt.Fscan(in, &n, &x, &y)
	edges = make([][]int, n)
	for i := 0; i < n-1; i++ {
		var a, b int
		fmt.Fscan(in, &a, &b)
		a--
		b--
		edges[a] = append(edges[a], b)
		edges[b] = append(edges[b], a)
	}
	if x >= y {
		if isStar() {
			fmt.Fprintln(out, y*int64(n-2)+x)
		} else {
			fmt.Fprintln(out, y*int64(n-1))
		}
		return
	}
	childrenByHeight = make([]ChildrenByHeight, n)
	computeHeight(0, 0)
	solve2(0)
	fmt.Fprintln(out, x*int64(xCount)+y*int64(yCount))
}

func isStar() bool {
	for _, es := range edges {
		if len(es) == n-1 {
			return true
		}
	}
	return false
}

func computeHeight(v, parent int) int {
	for _, u := range edges[v] {
		if u == parent {
			continue
		}
		h := computeHeight(u, v)
		childrenByHeight[v] = append(childrenByHeight[v], ChildWithHeight{u, h})
	}
	sort.Sort(childrenByHeight[v])
	if len(childrenByHeight[v]) == 0 {
		return 1
	}
	return childrenByHeight[v][0].height + 1
}

func solve2(v int) {
	cbh := childrenByHeight[v]
	if len(cbh) < 2 {
		solve1(v)
		return
	}
	xCount += 2
	solve1(cbh[0].vertex)
	solve1(cbh[1].vertex)
	for _, child := range cbh[2:] {
		yCount++
		solve2(child.vertex)
	}
}

func solve1(v int) {
	cbh := childrenByHeight[v]
	if len(cbh) == 0 {
		return
	}
	xCount++
	solve1(cbh[0].vertex)
	for _, child := range cbh[1:] {
		yCount++
		solve2(child.vertex)
	}
}

type ChildrenByHeight []ChildWithHeight

type ChildWithHeight struct {
	vertex int
	height int
}

func (a ChildrenByHeight) Less(i, j int) bool {
	return a[i].height > a[j].height
}

func (a ChildrenByHeight) Len() int {
	return len(a)
}

func (a ChildrenByHeight) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

package main

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

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

var n int
var x, y int64
var edges [][]int
var xCount int
var yCount int
var childrenByHeight []ChildrenByHeight

func main() {
	defer out.Flush()
	fmt.Fscan(in, &n, &x, &y)
	if x >= y {
		if n == 2 {
			fmt.Fprintln(out, x)
		} else {
			fmt.Fprintln(out, y*int64(n-1))
		}
		return
	}
	edges = make([][]int, n)
	for i := 0; i < n-1; i++ {
		var a, b int
		fmt.Fscan(in, &a, &b)
		a--
		b--
		edges[a] = append(edges[a], b)
		edges[b] = append(edges[b], a)
	}
	childrenByHeight = make([]ChildrenByHeight, n)
	computeHeight(0, 0)
	solve2(0)
	fmt.Fprintln(out, x*int64(xCount)+y*int64(yCount))
}

func computeHeight(v, parent int) int {
	for _, u := range edges[v] {
		if u == parent {
			continue
		}
		h := computeHeight(u, v)
		childrenByHeight[v] = append(childrenByHeight[v], ChildWithHeight{u, h})
	}
	sort.Sort(childrenByHeight[v])
	if len(childrenByHeight[v]) == 0 {
		return 1
	}
	return childrenByHeight[v][0].height + 1
}

func solve2(v int) {
	cbh := childrenByHeight[v]
	if len(cbh) < 2 {
		solve1(v)
		return
	}
	xCount += 2
	solve1(cbh[0].vertex)
	solve1(cbh[1].vertex)
	for _, child := range cbh[2:] {
		yCount++
		solve2(child.vertex)
	}
}

func solve1(v int) {
	cbh := childrenByHeight[v]
	if len(cbh) == 0 {
		return
	}
	xCount++
	solve1(cbh[0].vertex)
	for _, child := range cbh[1:] {
		yCount++
		solve2(child.vertex)
	}
}

type ChildrenByHeight []ChildWithHeight

type ChildWithHeight struct {
	vertex int
	height int
}

func (a ChildrenByHeight) Less(i, j int) bool {
	return a[i].height > a[j].height
}

func (a ChildrenByHeight) Len() int {
	return len(a)
}

func (a ChildrenByHeight) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

package main

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

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

var n int
var x, y int64
var edges [][]int
var xCount int
var yCount int
var childrenByHeight []ChildrenByHeight

func main() {
	defer out.Flush()
	fmt.Fscan(in, &n, &x, &y)
	edges = make([][]int, n)
	for i := 0; i < n-1; i++ {
		var a, b int
		fmt.Fscan(in, &a, &b)
		a--
		b--
		edges[a] = append(edges[a], b)
		edges[b] = append(edges[b], a)
	}
	if x >= y {
		if isStar() {
			fmt.Fprintln(out, y*int64(n-2)+x)
		} else {
			fmt.Fprintln(out, y*int64(n-1))
		}
		return
	}
	solve1cache = make([]int, n)
	solve2cache = make([]int, n)
	for i := 0; i < n; i++ {
		solve1cache[i] = -1
		solve2cache[i] = -1
	}
	childrenByHeight = make([]ChildrenByHeight, n)
	computeHeight(0, 0)
	yCount = solve2(0)
	xCount = n - 1 - yCount
	fmt.Fprintln(out, x*int64(xCount)+y*int64(yCount))
}

func isStar() bool {
	for _, es := range edges {
		if len(es) == n-1 {
			return true
		}
	}
	return false
}

func computeHeight(v, parent int) int {
	for _, u := range edges[v] {
		if u == parent {
			continue
		}
		h := computeHeight(u, v)
		childrenByHeight[v] = append(childrenByHeight[v], ChildWithHeight{u, h})
	}
	sort.Sort(childrenByHeight[v])
	if len(childrenByHeight[v]) == 0 {
		return 1
	}
	return childrenByHeight[v][0].height + 1
}

var solve2cache []int
var solve1cache []int

func solve2(v int) int {
	if solve2cache[v] != -1 {
		return solve2cache[v]
	}
	cbh := childrenByHeight[v]
	if len(cbh) < 2 {
		return solve1(v)
	}
	children := make(ChildrenByHeight, 0)
	for _, child := range cbh {
		children = append(children, ChildWithHeight{child.vertex, solve2(child.vertex)})
	}
	sort.Sort(children)
	result := 0
	result += solve1(children[0].vertex)
	result += solve1(children[1].vertex)
	for _, child := range children[2:] {
		result += child.height
	}
	solve2cache[v] = result
	return result
}

func solve1(v int) int {
	if solve1cache[v] != -1 {
		return solve1cache[v]
	}
	cbh := childrenByHeight[v]
	if len(cbh) == 0 {
		return 0
	}
	children := make(ChildrenByHeight, 0)
	for _, child := range cbh {
		children = append(children, ChildWithHeight{child.vertex, solve2(child.vertex)})
	}
	sort.Sort(children)
	result := 0
	result += solve1(children[0].vertex)
	for _, child := range children[1:] {
		result += child.height
	}
	solve1cache[v] = result
	return result
}

type ChildrenByHeight []ChildWithHeight

type ChildWithHeight struct {
	vertex int
	height int
}

func (a ChildrenByHeight) Less(i, j int) bool {
	return a[i].height > a[j].height
}

func (a ChildrenByHeight) Len() int {
	return len(a)
}

func (a ChildrenByHeight) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

package main

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

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

var n int
var x, y int64
var edges [][]int
var xCount int
var yCount int
var childrenByHeight []ChildrenByHeight

func main() {
	defer out.Flush()
	fmt.Fscan(in, &n, &x, &y)
	edges = make([][]int, n)
	for i := 0; i < n-1; i++ {
		var a, b int
		fmt.Fscan(in, &a, &b)
		a--
		b--
		edges[a] = append(edges[a], b)
		edges[b] = append(edges[b], a)
	}
	if x >= y {
		if isStar() {
			fmt.Fprintln(out, y*int64(n-2)+x)
		} else {
			fmt.Fprintln(out, y*int64(n-1))
		}
		return
	}
	solve1cache = make([]int, n)
	solve2cache = make([]int, n)
	for i := 0; i < n; i++ {
		solve1cache[i] = -1
		solve2cache[i] = -1
	}
	childrenByHeight = make([]ChildrenByHeight, n)
	computeHeight(0, 0)
	yCount = solve2(0)
	xCount = n - 1 - yCount
	fmt.Fprintln(out, x*int64(xCount)+y*int64(yCount))
}

func isStar() bool {
	for _, es := range edges {
		if len(es) == n-1 {
			return true
		}
	}
	return false
}

func computeHeight(v, parent int) int {
	for _, u := range edges[v] {
		if u == parent {
			continue
		}
		h := computeHeight(u, v)
		childrenByHeight[v] = append(childrenByHeight[v], ChildWithHeight{u, h})
	}
	sort.Sort(childrenByHeight[v])
	if len(childrenByHeight[v]) == 0 {
		return 1
	}
	return childrenByHeight[v][0].height + 1
}

var solve2cache []int
var solve1cache []int

func solve2(v int) int {
	if solve2cache[v] != -1 {
		return solve2cache[v]
	}
	cbh := childrenByHeight[v]
	if len(cbh) < 2 {
		return solve1(v)
	}
	children := make(ChildrenByHeight, 0)
	for _, child := range cbh {
		children = append(children, ChildWithHeight{child.vertex, solve2(child.vertex)})
	}
	sort.Sort(children)
	result := 0
	result += solve1(children[0].vertex)
	result += solve1(children[1].vertex)
	for _, child := range children[2:] {
		result += 1 + child.height
	}
	solve2cache[v] = result
	return result
}

func solve1(v int) int {
	if solve1cache[v] != -1 {
		return solve1cache[v]
	}
	cbh := childrenByHeight[v]
	if len(cbh) == 0 {
		return 0
	}
	children := make(ChildrenByHeight, 0)
	for _, child := range cbh {
		children = append(children, ChildWithHeight{child.vertex, solve2(child.vertex)})
	}
	sort.Sort(children)
	result := 0
	result += solve1(children[0].vertex)
	for _, child := range children[1:] {
		result += 1 + child.height
	}
	solve1cache[v] = result
	return result
}

type ChildrenByHeight []ChildWithHeight

type ChildWithHeight struct {
	vertex int
	height int
}

func (a ChildrenByHeight) Less(i, j int) bool {
	return a[i].height > a[j].height
}

func (a ChildrenByHeight) Len() int {
	return len(a)
}

func (a ChildrenByHeight) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}