You are given a string $$$s$$$, consisting of $$$n$$$ letters, each letter is either 'a' or 'b'. The letters in the string are numbered from $$$1$$$ to $$$n$$$.$$$s[l; r]$$$ is a continuous substring of letters from index $$$l$$$ to $$$r$$$ of the string inclusive. A string is called balanced if the number of letters 'a' in it is equal to the number of letters 'b'. For example, strings "baba" and "aabbab" are balanced and strings "aaab" and "b" are not.Find any non-empty balanced substring $$$s[l; r]$$$ of string $$$s$$$. Print its $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$). If there is no such substring, then print $$$-1$$$ $$$-1$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of the string. The second line of the testcase contains a string $$$s$$$, consisting of $$$n$$$ letters, each letter is either 'a' or 'b'.

For each testcase print two integers. If there exists a non-empty balanced substring $$$s[l; r]$$$, then print $$$l$$$ $$$r$$$ ($$$1 \le l \le r \le n$$$). Otherwise, print $$$-1$$$ $$$-1$$$.

NoteIn the first testcase there are no non-empty balanced subtrings.In the second and third testcases there are multiple balanced substrings, including the entire string "abbaba" and substring "baba".

package main

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

type Scanner struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) *Scanner {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	return &Scanner{scanner}
}

func (s *Scanner) Word() string {
	s.Scan()
	return s.Text()
}

func (s *Scanner) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

func (s *Scanner) Int64() int64 {
	s.Scan()
	n, _ := strconv.ParseInt(s.Text(), 10, 64)
	return n
}

func (s *Scanner) Words(count int) []string {
	words := make([]string, count)
	for i := range words {
		words[i] = s.Word()
	}
	return words
}

func (s *Scanner) Ints(count int) []int {
	ints := make([]int, count)
	for i := range ints {
		ints[i] = s.Int()
	}
	return ints
}

func (s *Scanner) Int64s(count int) []int64 {
	int64s := make([]int64, count)
	for i := range int64s {
		int64s[i] = s.Int64()
	}
	return int64s
}

func solve(n int, s string) {

	for i := 1; i < n; i++ {
		if s[i] != s[i-1] {
			fmt.Println(i, i+1)
			return
		}
	}

	fmt.Println("-1 -1")

}

func main() {
	stdin := NewWordScanner(os.Stdin)
	tests := stdin.Int()

	for i := 0; i < tests; i++ {
		n, s := stdin.Int(), stdin.Word()
		solve(n, s)
	}
}

package main

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

type Scanner struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) *Scanner {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	return &Scanner{scanner}
}

func (s *Scanner) Word() string {
	s.Scan()
	return s.Text()
}

func (s *Scanner) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

func (s *Scanner) Int64() int64 {
	s.Scan()
	n, _ := strconv.ParseInt(s.Text(), 10, 64)
	return n
}

func (s *Scanner) Words(count int) []string {
	words := make([]string, count)
	for i := range words {
		words[i] = s.Word()
	}
	return words
}

func (s *Scanner) Ints(count int) []int {
	ints := make([]int, count)
	for i := range ints {
		ints[i] = s.Int()
	}
	return ints
}

func (s *Scanner) Int64s(count int) []int64 {
	int64s := make([]int64, count)
	for i := range int64s {
		int64s[i] = s.Int64()
	}
	return int64s
}

func solve(n int, s string) {
	suma := make([]int, n+1)
	sumb := make([]int, n+1)

	for i, c := range s {
		suma[i+1] = suma[i]
		sumb[i+1] = sumb[i]
		if c == 'a' {
			suma[i+1] = suma[i+1] + 1
		} else {
			sumb[i+1] = sumb[i+1] + 1
		}
	}
	ans := 0
	for i := 1; i <= n; i++ {
		for j := i + 1; j <= n; j++ {
			if suma[j]-suma[i-1] == sumb[j]-sumb[i-1] {
				fmt.Println(i, j)
				return

			}
		}
	}

	if ans == 0 {
		fmt.Println("-1 -1")
	}

}

func main() {
	stdin := NewWordScanner(os.Stdin)
	tests := stdin.Int()

	for i := 0; i < tests; i++ {
		n, s := stdin.Int(), stdin.Word()
		solve(n, s)
	}
}

package main
import(
    "fmt"
    "bufio"
    "os"
    "strings"
)
type coords struct{
	row int
	column int
}
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		var word string
		fmt.Fscan(in,&word)
		a:=strings.Count(word,"a")
		b:= strings.Count(word,"b")
		if a == 0 || b == 0 {
			fmt.Fprintln(out, -1,-1)
		} else {
			for j:=1;j<n;j++{
				if (string(word[j]) == "a" && string(word[j-1]) == "b") || (string(word[j]) == "b" && string(word[j-1]) == "a"){
					fmt.Fprintln(out,j,j+1)
					break
				}
			}
		}
	}
}

package main

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

func Problem1569A(r io.Reader, w io.Writer) {
	in := bufio.NewReader(r)
	out := bufio.NewWriter(w)
	defer out.Flush()

	t := 0
	fmt.Fscanln(in, &t)

	for tcNo := 0; tcNo < t; tcNo++ {
		n := 0
		s := ""
		fmt.Fscanln(in, &n)
		fmt.Fscanln(in, &s)

		countA := 0
		countB := 0
		l := -1
		r := -1
		for i, c := range s {
			switch c {
			case 'a':
				countA++
			case 'b':
				countB++
			}
			if countA == 0 || countB == 0 {
				continue
			}
			if countA > 0 && countB > 0 {
				l = i
				r = i + 1
				break
			}
		}
		fmt.Fprintf(out, "%d %d\n", l, r)
	}
}

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

package main

import (
	"fmt"
)

const N = 100

func getB(x int , n int) int {
	return n - x
}

func foo() {
	var n int
	var s string
	fmt.Scan(&n,&s)
	var a, b [N]int
	cnta := 0
	cntb := 0
	for i := 1; i <= n; i++ {
		if s[i-1] == 'a' {
			cnta++
		} else {
			cntb++
		}
		a[i] = cnta
		b[i] = cntb
	}
	for i := 1; i <= n - 1; i++ {
		for j := n; j > i; j-- {
			cntal := a[i-1]
			cntbl := b[i-1]
			cntar := a[j]
			cntbr := b[j]
			if cntbr - cntbl == cntar - cntal{
				fmt.Println(i, j)
				return
			}
		}
	}
	fmt.Println(-1,-1)
}

func main() {
	var t int
	fmt.Scan(&t)
	for t > 0 {
		t--
		foo()
	}
}

package main

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

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

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

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

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

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

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

func main() {
	defer writer.Flush()
	for t := _int(); t > 0; t-- {
		n := _int()
		s := _string()
		l, r := sol(n, s)
		printf("%d %d\n", l, r)
	}
}

func sol(n int, s string) (int, int) {
	for i := range s {
		if i > 0 && s[i] != s[i-1] {
			return i, i + 1
		}
	}
	return -1, -1
}

package main

import "fmt"

var t, n int
var s string
var frekA, frekB []int

func main() {
	fmt.Scanln(&t)
	for {
		if t == 0 {
			break
		}
		frekA := make([]int, 55)
		frekB := make([]int, 55)
		fmt.Scanln(&n)
		fmt.Scanln(&s)

		for i, c := range s {
			if i == 0 {
				if s[0] == 97 {
					frekA[0] = 1
				} else {
					frekB[0] = 1
				}
				continue
			}

			frekA[i] = frekA[i-1]
			frekB[i] = frekB[i-1]

			if c == 97 {
				frekA[i]++
			} else {
				frekB[i]++
			}
		}

		ansL := -1
		ansR := -1
		for i := 0; i < n; i++ {
			for j := i + 1; j < n; j++ {
				cntA := getCount(frekA, i, j)
				cntB := getCount(frekB, i, j)

				if cntA == cntB {
					ansL = i + 1
					ansR = j + 1
					break
				}
			}
		}
		fmt.Println(ansL, ansR)
		t--
	}
}

func getCount(arr []int, l int, r int) int {
	if l == 0 {
		return arr[r]
	}
	return arr[r] - arr[l-1]
}

package main

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

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n, s := 0, 0, ""
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n, &s)
		l := strings.Index(s, "ab")
		if l > -1 {
			fmt.Fprintln(w, l+1, l+2)
			continue
		}
		l = strings.Index(s, "ba")
		if l > -1 {
			fmt.Fprintln(w, l+1, l+2)
		} else {
			fmt.Fprintln(w, -1, -1)
		}
	}
	w.Flush()
}

func main() {
	solve()
}

package main

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

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

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

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

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

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

/**
Run solve the problem CF1569A
Date: 18/11/21
User: pepradere
URL: https://codeforces.com/problemset/problem/1569/A
Problem: CF1569A
**/
func (in *CF1569A) Run() {

	t := in.NextInt()
	for ;t > 0; t-- {
		in.NextInt()
		str := in.NextString()

		index := strings.Index(str, "ab")
		if index == -1 {
			index = strings.Index(str, "ba")
		}

		if index == -1 {
			fmt.Println(-1,-1)
		}else {
			fmt.Println(index+1, index+2)
		}
	}
}

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

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

package main

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

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

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		fmt.Fscan(reader, &s)
		var ca, cb int
		for _, k := range s {
			if k == 'a' {
				ca++
			} else {
				cb++
			}
		}
		if ca == 0 || cb == 0 {
			fmt.Println("-1 -1")
			continue
		}
		for i := range s {
			if s[i] != s[i+1] {
				fmt.Printf("%d %d\n", i+1, i+2)
				break
			}
		}
	}
}

package main

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

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

func scanf(f string, a ...interface{}) (n int, err error)  { return fmt.Fscanf(reader, f, a...) }
func printf(f string, a ...interface{}) (n int, err error) { return fmt.Fprintf(writer, f, a...) }

func main() {
	var t int
	scanf("%d\n", &t)
	s := make([]byte, 53)
	for ; t > 0; t-- {
		var n int
		scanf("%d\n", &n)
		scanf("%s\n", &s)
		var l = -1
		var r = -1
		for i := 1; i < n; i++ {
			if l == -1 && s[i-1] != s[i] {
				l = i - 1 + 1
				r = i + 1
			}
		}
		printf("%d %d\n", l, r)
	}
	writer.Flush()
}

package main

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

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

func readInt() int{
	var n int
	fmt.Fscan(in, &n)
	return n
}

func readToken() string{
	var s string
	fmt.Fscan(in, &s)
	return s
}

func Solve(){
	var n int = readInt()
	var s string  = readToken()
	for i := 1; i <= n-1; i++{
		if s[i-1] != s[i]{
			fmt.Println(i, i+1)
			return
		}
	}
	fmt.Println(-1, -1)
}

func main(){
	var t int = readInt()
	for ;t>0;t--{
		Solve()
	}
}

package main

import "fmt"

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

	for ; testcases > 0; testcases-- {
		var (
			n    int
			str  string
			flag bool = true
		)

		fmt.Scanf("%d\n%s\n", &n, &str)

		for iterator, _ := range str {
			if iterator != 0 {
				if str[iterator] != str[iterator-1] {
					flag = false
                    fmt.Println(iterator , iterator + 1)
                    break
				}
			}
		}
        if flag {
            fmt.Println("-1 -1")
        }
	}

}

package main

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

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

	for i := 0; i < tc; i++ {
        n := readInt(in)
        line := readLine(in)
        l, r := -1, -1
        for i := 0; i < n-1; i++ {
            for j := i+1; j < n; j++ {
                if isBalanced(line[i:j+1]) {
                    l, r = i+1, j+1
                    break
                }
            }
            if l != -1 || r != -1 {
                break
            }
        }
        fmt.Println(l, r)
	}
}

func isBalanced(line string) bool {
    countA, countB := 0, 0
    if len(line) % 2 == 1 {
        return false
    }
    for _, l := range line {
        if l == 'a' {
            countA++
        } else {
            countB++
        }
    }
    return countA == countB
}

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

func readLine(in *bufio.Reader) string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	return line
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

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

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

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

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })

func MIN(x, y int64) int64 {
	if x > y {
		return y
	} else {
		return x
	}
}

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

func MKO(x, y int64) int64 {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

func MAX(x, y int64) int64 {
	if x > y {
		return x
	} else {
		return y
	}
}

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}
}

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

func MODULE(x, y int) int {
	if x > y {
		return x - y
	} else {
		return y - x
	}
}

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

func Sum(n, m int) int {
	var ans int

	if n == 1 {
		return 0
	} else {
		for i := 2; i < n; i++ {
			ans = (ans + Sum(i, m)) % m
		}
		for j := 2; j < n+1; j++ {
			ans = (ans + Sum(n/j, m)) % m
		}
		return ans
	}
}

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)

		STRING := make([]byte, 0)
		fmt.Fscan(input, &STRING)

		// ARR := make([]int, n)
		// for i := 0; i < n; i++ {
		// 	fmt.Fscan(input, &ARR[i])
		// }

		var ans int
		for i := 0; i < n-1; i++ {
			if string(STRING[i]) == "a" {
				if string(STRING[i+1]) == "b" {
					ans = i + 1
					break
				}

			} else {
				if string(STRING[i+1]) == "a" {
					ans = i + 1
					break
				}

			}

		}

		if ans > 0 {
			fmt.Println(ans)
			fmt.Println(ans + 1)
		} else {
			fmt.Println(-1)
			fmt.Println(-1)

		}

	}
}

package main

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

var (
	in = bufio.NewReader(os.Stdin)
)

func main() {
	var test = 1
	fmt.Fscan(in, &test)
	for i := 0; i < test; i++ {
		solve()
	}

}

func solve() {
	var n int
	fmt.Fscan(in, &n)
	var givenString string
	fmt.Fscan(in, &givenString)
	var hasfound = false
	right := 0
	left := 0
	for i := 1; i < len(givenString); i++ {
		if givenString[i-1] != givenString[i] {
			hasfound = true
			right = i + 1
			left = i
			break
		}
	}
	if hasfound {
		fmt.Println(left, right)
	} else {
		fmt.Println(-1, -1)
	}
}

//x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-TEMPLATE_STARTING-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-

type pair struct {
	a int64
	b int64
}

func sortPair(pairs []pair) {
	sort.Slice(pairs, func(i, j int) bool {
		return pairs[i].a < pairs[j].a
	})
}
func min(a int64, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func max(a int64, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

func printArray(arr []int) {
	for i := 1; i < len(arr); i++ {
		fmt.Print(arr[i], " ")
	}
	fmt.Println()
}

type runeSort []rune

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

package main

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

func main() {
	r := bufio.NewReaderSize(os.Stdin, 1024*1024)

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

	for t := 0; t < T; t++ {
		var n int
		var s string

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

		found := false
		for i := 0; i < n; i++ {
			a := 0
			b := 0
			for j := i; j < n; j++ {
				if s[j] == 'a' {
					a++
				}
				if s[j] == 'b' {
					b++
				}
				if a == b {
					fmt.Println(i+1, j+1)
					found = true
					break
				}
			}
			if found {
				break
			}
		}

		if !found {
			fmt.Println(-1, -1)
		}
	}
}

package main

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

type Scanner struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) *Scanner {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	return &Scanner{scanner}
}

func (s *Scanner) Word() string {
	s.Scan()
	return s.Text()
}

func (s *Scanner) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

func (s *Scanner) Int64() int64 {
	s.Scan()
	n, _ := strconv.ParseInt(s.Text(), 10, 64)
	return n
}

func (s *Scanner) Words(count int) []string {
	words := make([]string, count)
	for i := range words {
		words[i] = s.Word()
	}
	return words
}

func (s *Scanner) Ints(count int) []int {
	ints := make([]int, count)
	for i := range ints {
		ints[i] = s.Int()
	}
	return ints
}

func (s *Scanner) Int64s(count int) []int64 {
	int64s := make([]int64, count)
	for i := range int64s {
		int64s[i] = s.Int64()
	}
	return int64s
}

func solve(n int, s string) {

	for i := 1; i < n; i++ {
		if s[i] != s[i-1] {
			fmt.Println(i-1, i)
			return
		}
	}

	fmt.Println("-1 -1")

}

func main() {
	stdin := NewWordScanner(os.Stdin)
	tests := stdin.Int()

	for i := 0; i < tests; i++ {
		n, s := stdin.Int(), stdin.Word()
		solve(n, s)
	}
}

package main

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

type Scanner struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) *Scanner {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	return &Scanner{scanner}
}

func (s *Scanner) Word() string {
	s.Scan()
	return s.Text()
}

func (s *Scanner) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

func (s *Scanner) Int64() int64 {
	s.Scan()
	n, _ := strconv.ParseInt(s.Text(), 10, 64)
	return n
}

func (s *Scanner) Words(count int) []string {
	words := make([]string, count)
	for i := range words {
		words[i] = s.Word()
	}
	return words
}

func (s *Scanner) Ints(count int) []int {
	ints := make([]int, count)
	for i := range ints {
		ints[i] = s.Int()
	}
	return ints
}

func (s *Scanner) Int64s(count int) []int64 {
	int64s := make([]int64, count)
	for i := range int64s {
		int64s[i] = s.Int64()
	}
	return int64s
}

func solve(n int, s string) {

	for i := 1; i < n; i++ {
		if s[i] != s[i-1] {
			fmt.Println(i-1, i)
		}
	}

	fmt.Println("-1 -1")

}

func main() {
	stdin := NewWordScanner(os.Stdin)
	tests := stdin.Int()

	for i := 0; i < tests; i++ {
		n, s := stdin.Int(), stdin.Word()
		solve(n, s)
	}
}

package main
import(
    "fmt"
    "bufio"
    "os"
    "strings"
)
type coords struct{
	row int
	column int
}
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		var word string
		fmt.Fscan(in,&word)
		a:=strings.Count(word,"a")
		b:= strings.Count(word,"b")
		if a == 1 || b == 1 {
			fmt.Fprintln(out, -1,-1)
		} else {
			for j:=1;j<n;j++{
				if (string(word[j]) == "a" && string(word[j-1]) == "b") || (string(word[j]) == "a" && string(word[j-1]) == "b"){
					fmt.Fprintln(out,j,j+1)
					break
				}
			}
		}
	}
}

package main

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

func Problem1569A(r io.Reader, w io.Writer) {
	in := bufio.NewReader(r)
	out := bufio.NewWriter(w)
	defer out.Flush()

	t := 0
	fmt.Fscanln(in, &t)

	for tcNo := 0; tcNo < t; tcNo++ {
		n := 0
		s := ""
		fmt.Fscanln(in, &n)
		fmt.Fscanln(in, &s)

		countA := 0
		countB := 0
		l := -1
		r := -1
		for i, c := range s {
			switch c {
			case 'a':
				countA++
			case 'b':
				countB++
			}
			if countA == 0 || countB == 0 {
				continue
			}
			if countA > 0 && countB > 0 {
				l = i - 1
				r = i + 1
				break
			}
		}
		fmt.Fprintf(out, "%d %d\n", l, r)
	}
}

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

package main

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

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

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

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

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

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

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

func main() {
	defer writer.Flush()
	for t := _int(); t > 0; t-- {
		n := _int()
		s := _string()
		l, r := sol(n, s)
		printf("%d %d\n", l, r)
	}
}

func sol(n int, s string) (int, int) {
	countA := 0
	countB := 0
	for i := range s {
		if s[i] == 'a' {
			countA++
		}
		if s[i] == 'b' {
			countB++
		}
		if countA != countB && i >= 1 {
			return 1, i + 1
		}
	}
	return -1, -1
}


For the first place at the competition, Alex won many arrays of integers and was assured that these arrays are very expensive. After the award ceremony Alex decided to sell them. There is a rule in arrays pawnshop: you can sell array only if it can be compressed to a generator.This generator takes four non-negative numbers $$$n$$$, $$$m$$$, $$$c$$$, $$$s$$$. $$$n$$$ and $$$m$$$ must be positive, $$$s$$$ non-negative and for $$$c$$$ it must be true that $$$0 \leq c < m$$$. The array $$$a$$$ of length $$$n$$$ is created according to the following rules:   $$$a_1 = s \bmod m$$$, here $$$x \bmod y$$$ denotes remainder of the division of $$$x$$$ by $$$y$$$;  $$$a_i = (a_{i-1} + c) \bmod m$$$ for all $$$i$$$ such that $$$1 < i \le n$$$. For example, if $$$n = 5$$$, $$$m = 7$$$, $$$c = 4$$$, and $$$s = 10$$$, then $$$a = [3, 0, 4, 1, 5]$$$.Price of such an array is the value of $$$m$$$ in this generator.Alex has a question: how much money he can get for each of the arrays. Please, help him to understand for every array whether there exist four numbers $$$n$$$, $$$m$$$, $$$c$$$, $$$s$$$ that generate this array. If yes, then maximize $$$m$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of arrays. The first line of array description contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the size of this array. The second line of array description contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$ ) — elements of the array.  It is guaranteed that the sum of array sizes does not exceed $$$10^5$$$.

For every array print:    $$$-1$$$, if there are no such four numbers that generate this array;  $$$0$$$, if $$$m$$$ can be arbitrary large;  the maximum value $$$m$$$ and any appropriate $$$c$$$ ($$$0 \leq c < m$$$) in other cases.

package main

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

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

	var t, n, m, c int
	fmt.Fscan(in, &t)

MainLoop:
	for ; t > 0; t-- {
		fmt.Fscan(in, &n)

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

		if n < 3 {
			fmt.Fprintln(out, 0)
			continue MainLoop
		}

		m = 0
		c = a[1] - a[0]
		if c > 0 {
			for i := 1; i < n; i++ {
				if a[i]-a[i-1] != c {
					if a[i] >= a[i-1] {
						fmt.Fprintln(out, -1)
						continue MainLoop
					}
					m = a[i-1] + c - a[i]
					break
				}
			}
		} else if c < 0 {
			for i := 1; i < n; i++ {
				if a[i]-a[i-1] != c {
					if a[i] <= a[i-1] || a[i-1]+c >= 0 {
						fmt.Fprintln(out, -1)
						continue MainLoop
					}
					c = a[i] - a[i-1]
					m = a[0] + c - a[1]
					break
				}
			}
		} else {
			for i := 1; i < n; i++ {
				if a[i] != a[i-1] {
					fmt.Fprintln(out, -1)
					continue MainLoop
				}
			}
		}

		if m == 0 {
			fmt.Fprintln(out, 0)
		} else {
			if a[0] >= m {
				fmt.Fprintln(out, -1)
				continue MainLoop
			}
			for i := 1; i < n; i++ {
				if a[i] != (a[i-1]+c)%m {
					fmt.Fprintln(out, -1)
					continue MainLoop
				}
			}
			fmt.Fprintln(out, m, c)
		}
	}
	out.Flush()
}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

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

func MKO(x, y int) int {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })
var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {

		var n int64

		fmt.Fscan(input, &n)

		// STRING := make([]byte, 0)
		// fmt.Fscan(input, &STRING)

		OurCCC := make([]int64, 0)
		OurMMinusCCC := make([]int64, 0)
		ARRAY := make([]int64, n)
		var MA int64
		for i := 0; int64(i) < n; i++ {
			fmt.Fscan(input, &ARRAY[i])
			if ARRAY[i] > MA {
				MA = ARRAY[i]
			}
			if i > 0 {
				if ARRAY[i] > ARRAY[i-1] {
					OurCCC = append(OurCCC, ARRAY[i]-ARRAY[i-1])
				}
				if ARRAY[i] == ARRAY[i-1] {
					OurCCC = append(OurCCC, 0)
				}

				if ARRAY[i] < ARRAY[i-1] {
					OurMMinusCCC = append(OurMMinusCCC, ARRAY[i-1]-ARRAY[i])
				}

			}
		}

		if len(OurCCC) > 0 {
			sort.Slice(OurCCC, func(i, j int) bool {
				return OurCCC[i] < OurCCC[j]
			})
			if OurCCC[0] != OurCCC[len(OurCCC)-1] {
				fmt.Println(-1)
			} else {
				if len(OurMMinusCCC) == 0 {
					fmt.Println(0)
				} else {
					sort.Slice(OurMMinusCCC, func(i, j int) bool {
						return OurMMinusCCC[i] < OurMMinusCCC[j]
					})
					if OurMMinusCCC[0] != OurMMinusCCC[len(OurMMinusCCC)-1] {
						fmt.Println(-1)
					} else {
						if OurMMinusCCC[0]+OurCCC[0] <= MA {
							fmt.Println(-1)
						} else {
							fmt.Println(OurMMinusCCC[0] + OurCCC[0])
							fmt.Println(OurCCC[0])
						}
					}
				}
			}
		} else {
			if len(OurMMinusCCC) == 0 {
				fmt.Println(0)
			} else {
				sort.Slice(OurMMinusCCC, func(i, j int) bool {
					return OurMMinusCCC[i] < OurMMinusCCC[j]
				})
				if OurMMinusCCC[0] != OurMMinusCCC[len(OurMMinusCCC)-1] {
					fmt.Println(-1)
				} else {
					fmt.Println(0)
				}
			}
		}

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

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

		// if len(OurCCC)*len(OurMMinusCCC) == 0 {
		// 	if len(OurCCC)+len(OurMMinusCCC) == 0 {
		// 		fmt.Println(0)
		// 	} else {
		// 		if len(OurCCC) == 0 {
		// 			if OurMMinusCCC[0] != OurCCC[len(OurMMinusCCC)-1] {
		// 				fmt.Println(-1)
		// 			} else {
		// 				fmt.Println(0)
		// 			}
		// 		} else {
		// 			if OurCCC[0] != OurCCC[len(OurCCC)-1] {
		// 				fmt.Println(-1)
		// 			} else {
		// 				fmt.Println(0)
		// 			}
		// 		}
		// 	}
		// } else {
		// 	if OurMMinusCCC[0] != OurMMinusCCC[len(OurMMinusCCC)-1] {
		// 		fmt.Println(-1)
		// 	} else {
		// 		if OurCCC[0] != OurCCC[len(OurCCC)-1] {
		// 			fmt.Println(-1)
		// 		} else {
		// 			if OurMMinusCCC[0]+OurCCC[0] <= MA {
		// 				fmt.Println(-1)
		// 			} else {
		// 				fmt.Println(OurMMinusCCC[0] + OurCCC[0])
		// 				fmt.Println(OurCCC[0])
		// 			}
		// 		}
		// 	}

	}
}

package main

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

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

	var T, n int
o:
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		if n > 2 {
			for i, d := 2, a[1]-a[0]; i < n; i++ {
				if dd := a[i] - a[i-1]; dd != d {
					m := abs(dd - d)
					if d < 0 {
						d += m
					}
					for i, v := range a {
						if v >= m || i > 0 && (a[i-1]+d)%m != v {
							Fprintln(out, -1)
							continue o
						}
					}
					Fprintln(out, m, d)
					continue o
				}
			}
		}
		Fprintln(out, 0)
	}
}

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

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

package main

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

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

	var t, n, m, c int
	fmt.Fscan(in, &t)

MainLoop:
	for ; t > 0; t-- {
		fmt.Fscan(in, &n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &a[i])
		}
		if n < 3 {
			fmt.Fprintln(out, 0)
			continue MainLoop
		}
		m = 0
		if a[1] > a[0] {
			c = a[1] - a[0]
			for i := 1; i < n; i++ {
				if a[i]-a[i-1] != c {
					if a[i] >= a[i-1] {
						fmt.Fprintln(out, -1)
						continue MainLoop
					}
					m = a[i-1] + c - a[i]
					break
				}
			}
		} else if a[1] < a[0] {
			c = a[1] - a[0]
			for i := 1; i < n; i++ {
				if a[i]-a[i-1] != c {
					if a[i] <= a[i-1] || a[i-1]+c >= 0 {
						fmt.Fprintln(out, -1)
						continue MainLoop
					}
					c = a[i] - a[i-1]
					m = a[0] + c - a[1]
				}
			}
		} else {
			for i := 1; i < n; i++ {
				if a[i] != a[i-1] {
					fmt.Fprintln(out, -1)
					continue MainLoop
				}
			}
		}

		if m == 0 {
			fmt.Fprintln(out, 0)
		} else {
			if a[0] >= m {
				fmt.Fprintln(out, -1)
				continue MainLoop
			}
			for i := 1; i < n; i++ {
				if a[i] != (a[i-1]+c)%m {
					fmt.Fprintln(out, -1)
					continue MainLoop
				}
			}
			fmt.Fprintln(out, m, c)
		}
	}
	out.Flush()
}

package main

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

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

	var t, n, m, c int
	fmt.Fscan(in, &t)

MainLoop:
	for ; t > 0; t-- {
		fmt.Fscan(in, &n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &a[i])
		}
		if n < 3 {
			fmt.Fprintln(out, 0)
			continue MainLoop
		}
		m = 0
		if a[1] > a[0] {
			c = a[1] - a[0]
			for i := 1; i < n; i++ {
				if a[i]-a[i-1] != c {
					if a[i] >= a[i-1] {
						fmt.Fprintln(out, -1)
						continue MainLoop
					}
					m = a[i-1] + c - a[i]
					break
				}
			}
		} else if a[1] < a[0] {
			c = a[1] - a[0]
			for i := 1; i < n; i++ {
				if a[i]-a[i-1] != c {
					if a[i] <= a[i-1] || a[i-1]+c > 0 {
						fmt.Fprintln(out, -1)
						continue MainLoop
					}
					c = a[i] - a[i-1]
					m = a[0] + c - a[1]
				}
			}
		} else {
			for i := 1; i < n; i++ {
				if a[i] != a[i-1] {
					fmt.Fprintln(out, -1)
					continue MainLoop
				}
			}
		}

		if m == 0 {
			fmt.Fprintln(out, 0)
		} else {
			if a[0] >= m {
				fmt.Fprintln(out, -1)
				continue MainLoop
			}
			for i := 1; i < n; i++ {
				if a[i] != (a[i-1]+c)%m {
					fmt.Fprintln(out, -1)
					continue MainLoop
				}
			}
			fmt.Fprintln(out, m, c)
		}
	}
	out.Flush()
}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

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

func MKO(x, y int) int {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })
var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t+1; o++ {

		var n int

		fmt.Fscan(input, &n)

		// STRING := make([]byte, 0)
		// fmt.Fscan(input, &STRING)

		OurCCC := make([]int64, 0)

		OurMMinusCCC := make([]int64, 0)

		ARRAY := make([]int64, n)
		var MA int64
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &ARRAY[i])
			if ARRAY[i] > MA {
				MA = ARRAY[i]
			}
			if i > 0 {
				if ARRAY[i] > ARRAY[i-1] {
					OurCCC = append(OurCCC, ARRAY[i]-ARRAY[i-1])
				}
				if ARRAY[i] == ARRAY[i-1] {
					OurCCC = append(OurCCC, 0)
				}

				if ARRAY[i] < ARRAY[i-1] {
					OurMMinusCCC = append(OurMMinusCCC, ARRAY[i-1]-ARRAY[i])
				}

			}
		}
		if len(OurCCC) > 0 {
			sort.Slice(OurCCC, func(i, j int) bool {
				return OurCCC[i] < OurCCC[j]
			})
			if OurCCC[0] != OurCCC[len(OurCCC)-1] {
				fmt.Println(-1)
			} else {
				if len(OurMMinusCCC) == 0 {
					fmt.Println(0)
				} else {
					sort.Slice(OurMMinusCCC, func(i, j int) bool {
						return OurMMinusCCC[i] < OurMMinusCCC[j]
					})
					if OurMMinusCCC[0] != OurMMinusCCC[len(OurMMinusCCC)-1] {
						fmt.Println(-1)
					} else {
						if OurMMinusCCC[0]+OurCCC[0] <= MA {
							fmt.Println(-1)
						} else {
							fmt.Println(OurMMinusCCC[0] + OurCCC[0])
							fmt.Println(OurCCC[0])
						}
					}
				}
			}
		} else {
			if len(OurMMinusCCC) == 0 {
				fmt.Println(0)
			} else {
				sort.Slice(OurMMinusCCC, func(i, j int) bool {
					return OurMMinusCCC[i] < OurMMinusCCC[j]
				})
				if OurMMinusCCC[0] != OurCCC[len(OurMMinusCCC)-1] {
					fmt.Println(-1)
				} else {
					fmt.Println(0)
				}
			}
		}

	}

}


Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.

The first line contains an integer n, which is the number of contestants in the room (1 ≤ n ≤ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" — it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers:    0 ≤ plusi, minusi ≤ 50;  150 ≤ ai ≤ 500 or ai = 0, if problem A is not solved;  300 ≤ bi ≤ 1000 or bi = 0, if problem B is not solved;  450 ≤ ci ≤ 1500 or ci = 0, if problem C is not solved;  600 ≤ di ≤ 2000 or di = 0, if problem D is not solved;  750 ≤ ei ≤ 2500 or ei = 0, if problem E is not solved.  All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).

Print on the single line the handle of the room leader.

NoteThe number of points that each participant from the example earns, are as follows:   Petr — 3860  tourist — 4140  Egor — 4030  c00lH4x0R —  - 350  some_participant — 2220 Thus, the leader of the room is tourist.

package main

import "os"
import "bufio"
import "strconv"

func main(){
	var n int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	var s [50]string
	a := -100000000
	b, c, o := 0, 0, 0
	for i:=0; i<n; i++ {
		r.Scan()
		s[i] = r.Text()
		r.Scan()
		b, _ = strconv.Atoi(r.Text())
		r.Scan()
		c, _ = strconv.Atoi(r.Text())
		b = 100 * b - 50 * c
		for j:=0; j<5; j++ {
			r.Scan()
			c, _ = strconv.Atoi(r.Text())
			b += c
		}
		if b > a {
			a, o = b, i
		}
	}
	w.WriteString(string(s[o])+"\n")
	w.Flush()
}

package main

import "fmt"

func main() {
    var n,p,m,a,b,c,d,e int
    var winner,h string
    fmt.Scan(&n)
    max := -1000000000
    for i := 0; i < n; i++ {
        fmt.Scan(&h,&p,&m,&a,&b,&c,&d,&e)
        total := (100*p)+(-50*m)+a+b+c+d+e
        if max < total {
            max = total
            winner = h
        }
    }
    fmt.Println(winner)
}

// 74A
package main

import (
	"fmt"
)

func main() {
	var n, ans, p, m, a, b, c, d, e int
	ans = -1000000000
	var x, skr string
	for fmt.Scan(&n); n > 0; n-- {
		fmt.Scan(&skr, &p, &m, &a, &b, &c, &d, &e)
		score := p*100 - m*50 + a + b + c + d + e
		if score > ans {
			ans = score
			x = skr
		}
	}
	fmt.Println(x)
}

// 74A-mic_rizal
package main

import (
    "fmt"
)

func main() {
    var n, s int
    fmt.Scan(&n)
    sum := -100000000
    var str, a string
    var u, us, sc int
    for i := 0; i < n; i++ {
        fmt.Scan(&str, &u, &us)
        s = 0
        for j := 0; j < 5; j++ {
            fmt.Scan(&sc)
            s += sc
        }
        s += ((u * 100) - (us * 50))
        if s > sum {
            sum = s
            a = str
        }
    }
    fmt.Println(a)
}

package main

import "fmt"

func main() {
    var n,p,m,a,b,c,d,e int
    var winner,h string
    fmt.Scan(&n)
    max := 0
    for i := 0; i < n; i++ {
        fmt.Scan(&h,&p,&m,&a,&b,&c,&d,&e)
        total := (100*p)+(-50*m)+a+b+c+d+e
        if max < total {
            max = total
            winner = h
        }
    }
    fmt.Println(winner)
}

// 74A-mic_rizal
package main

import (
    "fmt"
)

func main() {
    var n, s int
    fmt.Scan(&n)
    sum := -100000000
    var str, a string
    var u, us, sc int
    for i := 0; i < n; i++ {
        fmt.Scan(&str, &us, &us)
        s = 0
        for j := 0; j < 5; j++ {
            fmt.Scan(&sc)
            s += sc
        }
        s += ((u * 100) - (us * 50))
        if s > sum {
            sum = s
            a = str
        }
    }
    fmt.Println(a)
}


The only difference between easy and hard versions is constraints.There are $$$n$$$ kids, each of them is reading a unique book. At the end of any day, the $$$i$$$-th kid will give his book to the $$$p_i$$$-th kid (in case of $$$i = p_i$$$ the kid will give his book to himself). It is guaranteed that all values of $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$ (i.e. $$$p$$$ is a permutation). The sequence $$$p$$$ doesn't change from day to day, it is fixed.For example, if $$$n=6$$$ and $$$p=[4, 6, 1, 3, 5, 2]$$$ then at the end of the first day the book of the $$$1$$$-st kid will belong to the $$$4$$$-th kid, the $$$2$$$-nd kid will belong to the $$$6$$$-th kid and so on. At the end of the second day the book of the $$$1$$$-st kid will belong to the $$$3$$$-th kid, the $$$2$$$-nd kid will belong to the $$$2$$$-th kid and so on.Your task is to determine the number of the day the book of the $$$i$$$-th child is returned back to him for the first time for every $$$i$$$ from $$$1$$$ to $$$n$$$.Consider the following example: $$$p = [5, 1, 2, 4, 3]$$$. The book of the $$$1$$$-st kid will be passed to the following kids:  after the $$$1$$$-st day it will belong to the $$$5$$$-th kid,  after the $$$2$$$-nd day it will belong to the $$$3$$$-rd kid,  after the $$$3$$$-rd day it will belong to the $$$2$$$-nd kid,  after the $$$4$$$-th day it will belong to the $$$1$$$-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 200$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 200$$$) — the number of kids in the query. The second line of the query contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct, i.e. $$$p$$$ is a permutation), where $$$p_i$$$ is the kid which will get the book of the $$$i$$$-th kid.

For each query, print the answer on it: $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the number of the day the book of the $$$i$$$-th child is returned back to him for the first time in this query.

package main

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

/* solution */

func solve() {
	q := readInt()
	for i := 0; i < q; i++ {
		solveOne()
	}
}

func solveOne() {
	n := readInt()
	a := make([]int, n+1)
	for i := 1; i <= n; i++ {
		a[i] = readInt()
	}
	use := make([]int, n+1)
	for i := 1; i <= n; i++ {
		if use[i] == 0 {
			cnt := 1
			p := a[i]
			for p != i {
				p = a[p]
				cnt++
			}
			use[i] = cnt
			p = a[i]
			for p != i {
				use[p] = cnt
				p = a[p]
			}
		}
	}
	for i := 1; i <= n; i++ {
		printInt(use[i])
	}
	ln()
}

/* stubs */

func main() {

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

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

	reader = bufio.NewScanner(f)

	const maxCapacity = 1024 * 1024
	buf := make([]byte, maxCapacity)
	reader.Buffer(buf, maxCapacity)

	reader.Split(bufio.ScanWords)

	solve()

}

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

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

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

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

func ln() {
	writer.WriteString("\n")
}

func printInt(i int) {
	print(strconv.Itoa(i))
}

func printInt64(i int64) {
	print(strconv.FormatInt(i, 10))
}

func readInt64() int64 {
	reader.Scan()
	ret, _ := strconv.ParseInt(reader.Text(), 10, 64)
	return ret
}

package main

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

func solve() {
	q := readInt32()
	for i := 0; i < q; i++ {
		n := readInt32()
		arr := make([]int, n)
		for j := range arr {
			arr[j] = readInt32() - 1
		}
		ans := make([]int, n)
		for i := range ans{
			cnt := 1
			for cur := arr[i]; ; cur = arr[cur] {
				if cur == i {
					ans[i] = cnt
					break
				} else {
					cnt++
				}
			}
		}
		writeSlice(ans)
		ln()
	}

}

/*   Helping stuff   */
type pair struct {
	a, b int
}

func newPair(a, b int) pair {
	return pair{a, b}
}

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

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

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

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

	solve()
}

/*   Scanner   */
var in *bufio.Reader
var out *bufio.Writer
var stringParts []string

func readLine() string {
	str, _, _ := in.ReadLine()
	return string(str)
}

func readNext() string {
	if len(stringParts) == 0 {
		stringParts = strings.Split(readLine(), " ")
	}
	res := stringParts[0]
	stringParts = stringParts[1:]
	return res
}

func readInt32() int {
	res, _ := strconv.ParseInt(readNext(), 10, 32)
	return int(res)
}

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

func readFloat32() float32 {
	res, _ := strconv.ParseFloat(readNext(), 32)
	return float32(res)
}

func readFloat64() float64 {
	res, _ := strconv.ParseFloat(readNext(), 32)
	return res
}

func writeString(s interface{}) {
	out.WriteString(fmt.Sprintf("%v ", s))
	out.Flush()
}

func writeSlice(s interface{}) {
	writeString(strings.Trim(strings.Join(strings.Split(fmt.Sprint(s), " "), " "), "[]"))
}

func ln() {
	out.Write([]byte{'\n'})
}

package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

	return s
}

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

var q int
var n int
var P []int
var flags []bool
var answers []int

func main() {
	q = ReadInt()

	for i := 0; i < q; i++ {
		n = ReadInt()
		P = []int{-1}
		tmp := ReadIntSlice(n)
		P = append(P, tmp...)
		flags = make([]bool, n+1)
		for j := 0; j <= n; j++ {
			flags[j] = false
		}
		answers = make([]int, n+1)

		for j := 1; j <= n; j++ {
			if flags[j] {
				continue
			}
			sub(j, 0)
		}
		fmt.Println(PrintIntsLine(answers[1:]...))
	}
}

func sub(id, num int) int {
	if flags[id] {
		return num
	}

	flags[id] = true
	nextId := P[id]
	answers[id] = sub(nextId, num+1)
	return answers[id]
}

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

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

package main

import "fmt"

func main() {
	var q, n int
	var stack []int
	fmt.Scan(&q)

	for ; q > 0; q-- {
		fmt.Scan(&n)
		kids := make([]int, n+1)
		bucket := make([]int, n+1)
		for i := 1; i <= n; i++ {
			fmt.Scan(&kids[i])
		}

		for i := 1; i <= n; i++ {
			if bucket[i] != 0 {
				continue
			}
			cont := 1
			guia := kids[i]

			for guia != i {
				stack = append(stack, guia)
				guia = kids[guia]
				cont++
			}

			for len(stack) > 0 {
				bucket[stack[0]] = cont
				stack = stack[1:]
			}
			bucket[i] = cont
		}

		for i, elem := range bucket {
			if i > 0 {
				fmt.Print(elem)
				fmt.Print(" ")
			}
		}
		fmt.Println()
	}
}

package main

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

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

	var q int
	for Fscan(in, &q); q > 0; q-- {
		var n int
		Fscan(in, &n)
		p := make([]int, n)
		for i := range p {
			Fscan(in, &p[i])
			p[i]--
		}
		ans := make([]interface{}, n)
		vis := make([]bool, n)
		for _, pi := range p {
			if vis[pi] {
				continue
			}
			cycle := 0
			vals := []int{}
			for j := pi; !vis[j]; j = p[j] {
				vis[j] =true
				cycle++
				vals = append(vals, j)
			}
			for _, val := range vals {
				ans[val] = cycle
			}
		}
		Fprintln(out, ans...)
	}
}

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

package main

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

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func diff(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}
func larger(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func smaller(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func largest(a, b, c int) (lgst int) {
	if a > b {
		lgst = a
	} else {
		lgst = b
	}
	if c > lgst {
		lgst = c
	}
	return
}
func smallest(a, b, c int) (slst int) {
	if a < b {
		slst = a
	} else {
		slst = b
	}
	if c < slst {
		slst = c
	}
	return
}
func intsMax(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func max: argument slice length must not be zero")
	}
	val = a[0]
	for i, aa := range a {
		if aa > val {
			idx, val = i, aa
		}
	}
	return
}
func intsMin(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func min: argument slice length must not be zero")
	}
	val = a[0]
	for i, aa := range a {
		if aa < val {
			idx, val = i, aa
		}
	}
	return
}
func intsSum(a []int) int {
	res := 0
	for _, v := range a {
		res += v
	}
	return res
}
func intsAdd(ints *[]int, x int) { *ints = append(*ints, x) }
func intsJoin(a, b []int) []int  { return append(a, b...) }
func intsClear(a []int) []int    { return a[:0] }
func intsCopy(a []int) []int     { return append([]int(nil), a...) }
func intsSorted(a []int) []int {
	s := intsCopy(a)
	sort.Ints(s)
	return s
}
func intsReverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func intsFill(a []int, val int) {
	for i := 0; i < len(a); i++ {
		a[i] = val
	}
	return
}
func intsPeekBack(a []int) int {
	if len(a) == 0 {
		panic("func peekBack: zero length slice")
	}
	return a[len(a)-1]
}
func intsPeekFront(a []int) int {
	if len(a) == 0 {
		panic("func peekFront: zero length slice")
	}
	return a[0]
}
func intsPopBack(a []int) (int, []int) {
	if len(a) == 0 {
		panic("func popBack: zero length slice")
	}
	return a[len(a)-1], a[:len(a)-1]
}
func intsPopFront(a []int) (int, []int) {
	if len(a) == 0 {
		panic("func popFront: zero length slice")
	}
	return a[0], a[1:]
}
func intsPushBack(a []int, x int) []int  { return append(a, x) }
func intsPushFront(a []int, x int) []int { return append([]int{x}, a...) }
func intsAppendSentinelHead(a []int, sentinel int) []int {
	return append([]int{sentinel}, a...)
}
func intsAppendSentinelTail(a []int, sentinel int) []int {
	return append(a, sentinel)
}
func intsAppendSentinel(a []int, sentinel int) []int {
	return append(append([]int{sentinel}, a[:len(a):len(a)+2]...), sentinel)
}
func isEven(n int) bool    { return n&1 == 0 }
func isOdd(n int) bool     { return n&1 == 1 }
func ceil(x float64) int   { return int(math.Ceil(x)) }
func ceilDiv(x, y int) int { return (x + y - 1) / y }
func pow(x, y int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for i := y; i != 0; i >>= 1 {
		if i&1 == 1 {
			z *= x
		}
		x *= x
	}
	return z
}
func fact(x int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact *= i
	}
	return fact
}
func sigmaK(n int) int  { return n * (n + 1) / 2 }
func sigmaKK(n int) int { return (n * (n + 1) / 2) * (2*n + 1) / 3 }
func euclideanDistance(a, b point) float64 {
	s := diff(a.x, b.x)
	s *= s
	t := diff(a.y, b.y)
	t *= t
	return math.Sqrt(float64(s) + float64(t))
}
func manhattanDistance(a, b point) int {
	s := diff(a.x, b.x)
	t := diff(a.y, b.y)
	return s + t
}
func swap(a, b *int) { *a, *b = *b, *a }
func chmax(a *int, b int) {
	if *a < b {
		*a = b
	}
}
func chmin(a *int, b int) {
	if *a > b {
		*a = b
	}
}
func cumSum(a []int) []int {
	b := append([]int{0}, a...)
	for i := 1; i < len(b); i++ {
		b[i] += b[i-1]
	}
	return b
}
func runesReverse(a []rune) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func bytesReverse(a []byte) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func strUpperCase(s string) string { return strings.ToUpper(s) }
func strLowerCase(s string) string { return strings.ToLower(s) }
func strToInt(s string) int {
	i, err := strconv.Atoi(s)
	if err != nil {
		panic(err)
	}
	return i
}
func intToStr(i int) string  { return strconv.Itoa(i) }
func CalcMod(a, mod int) int { return (a%mod + mod) % mod }
func ModPow(x, y, mod int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for i := y; i != 0; i >>= 1 {
		if i&1 == 1 {
			z = (z * x) % mod
		}
		x = (x * x) % mod
	}
	return z
}
func ModFact(x, mod int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact = fact * i % mod
	}
	return fact
}
func ModInv(x, mod int) int { return ModPow(x, mod-2, mod) }
func initMatrixBool(parentSize, childSize int, initialValue bool) *[][]bool {
	res := make([][]bool, parentSize)
	for i := range res {
		res[i] = make([]bool, childSize)
		for j := range res[i] {
			res[i][j] = initialValue
		}
	}
	return &res
}
func initMatrixInt(parentSize, childSize int, initialValue int) *[][]int {
	res := make([][]int, parentSize)
	for i := range res {
		res[i] = make([]int, childSize)
		for j := range res[i] {
			res[i][j] = initialValue
		}
	}
	return &res
}

var (
	sc = bufio.NewScanner(os.Stdin)
	bw = bufio.NewWriterSize(os.Stdout, bwBufSize)
)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1e7), 1e7)
}
func ru() (n int) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}
func ri() (n int) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	b := sc.Bytes()
	neg := false
	if b[0] == 45 {
		neg = true
		b = b[1:]
	}
	for _, v := range b {
		n = n*10 + int(v-48)
	}
	if neg {
		n = -n
	}
	return
}
func ri64() (n int64) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	b := sc.Bytes()
	neg := false
	if b[0] == 45 {
		neg = true
		b = b[1:]
	}
	for _, v := range b {
		n = n*10 + int64(v-48)
	}
	if neg {
		n = -n
	}
	return
}
func rf64() float64 {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	f, err := strconv.ParseFloat(sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return f
}
func rs() string {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return sc.Text()
}
func rb() []byte {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return sc.Bytes()
}
func rr() []rune {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return []rune(sc.Text())
}
func ris(n int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = ri()
	}
	return s
}
func risZeroBased(n int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = ri() - 1
	}
	return s
}
func ri64s(n int) []int64 {
	s := make([]int64, n)
	for i := range s {
		s[i] = ri64()
	}
	return s
}
func rss(n int) []string {
	s := make([]string, n)
	for i := range s {
		s[i] = rs()
	}
	return s
}
func pf(format string, a ...interface{}) {
	if _, err := fmt.Fprintf(bw, format, a...); err != nil {
		panic(err)
	}
}
func pln(a ...interface{}) {
	if _, err := fmt.Fprintln(bw, a...); err != nil {
		panic(err)
	}
}
func pints(a []int) {
	for _, v := range a {
		fmt.Fprintln(bw, v)
	}
}
func pintsol(a []int) {
	s := fmt.Sprint(a)
	if _, err := fmt.Fprintln(bw, s[1:len(s)-1]); err != nil {
		panic(err)
	}
}
func dbg(a ...interface{}) {
	if _, err := fmt.Fprintln(os.Stderr, a...); err != nil {
		panic(err)
	}
}
func YESorNO(b bool) string {
	if b {
		return "YES"
	} else {
		return "NO"
	}
}
func YesOrNo(b bool) string {
	if b {
		return "Yes"
	} else {
		return "No"
	}
}
func main() {
	solve()
	bw.Flush()
}

const (
	bwBufSize = 1e6

	alphabetUpper = "abcdefghijklmnopqrstuvwxyz"
	alphabetLower = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

	// maxInt64  = 9223372036854775807  // 9e18
	// maxInt32  = 2147483647           // 2e9
	// maxUint64 = 18446744073709551615 // 1e19
	inf = 1 << 60
	mod = 1e9 + 7
)

type pair struct{ fi, se int }
type byFiSe []pair

func (p byFiSe) Len() int      { return len(p) }
func (p byFiSe) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p byFiSe) Less(i, j int) bool {
	if p[i].fi == p[j].fi {
		return p[i].se < p[j].se
	}
	return p[i].fi < p[j].fi
}

type point struct{ x, y int }

type djSet struct{ p []int }

func newDj(size int) *djSet {
	dj := &djSet{}
	dj.initDjSet(size)
	return dj
}
func (dj *djSet) initDjSet(size int) {
	dj.p = make([]int, size)
	for i := 0; i < size; i++ {
		dj.p[i] = -1
	}
	return
}
func (dj *djSet) unite(x, y int) bool {
	xr, yr := dj.find(x), dj.find(y)
	if xr != yr {
		if dj.p[yr] < dj.p[xr] {
			x, y = y, x
			xr, yr = yr, xr
		}
		dj.p[xr] += dj.p[yr]
		dj.p[yr] = x
	}
	return xr != yr
}
func (dj *djSet) find(x int) int {
	if dj.p[x] < 0 {
		return x
	}
	return dj.find(dj.p[x])
}
func (dj *djSet) isSame(x, y int) bool { return dj.find(x) == dj.find(y) }
func (dj *djSet) size(x int) int       { return -dj.p[dj.find(x)] }

func solve() {
	q := ri()
	for i := 0; i < q; i++ {
		n := ri()
		ps := risZeroBased(n)

		dj := newDj(n)
		for j := range ps {
			dj.unite(j, ps[j])
		}

		for j := range ps {
			if j == n-1 {
				pf("%d\n", dj.size(j))
			} else {
				pf("%d ", dj.size(j))
			}
		}
	}
}

package main

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

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func diff(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}
func larger(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func smaller(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func largest(a, b, c int) (lgst int) {
	if a > b {
		lgst = a
	} else {
		lgst = b
	}
	if c > lgst {
		lgst = c
	}
	return
}
func smallest(a, b, c int) (slst int) {
	if a < b {
		slst = a
	} else {
		slst = b
	}
	if c < slst {
		slst = c
	}
	return
}
func intsMax(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func max: argument slice length must not be zero")
	}
	val = a[0]
	for i, aa := range a {
		if aa > val {
			idx, val = i, aa
		}
	}
	return
}
func intsMin(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func min: argument slice length must not be zero")
	}
	val = a[0]
	for i, aa := range a {
		if aa < val {
			idx, val = i, aa
		}
	}
	return
}
func intsSum(a []int) int {
	res := 0
	for _, v := range a {
		res += v
	}
	return res
}
func intsAdd(ints *[]int, x int) { *ints = append(*ints, x) }
func intsJoin(a, b []int) []int  { return append(a, b...) }
func intsClear(a []int) []int    { return a[:0] }
func intsCopy(a []int) []int     { return append([]int(nil), a...) }
func intsSorted(a []int) []int {
	s := intsCopy(a)
	sort.Ints(s)
	return s
}
func intsReverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func intsFill(a []int, val int) {
	for i := 0; i < len(a); i++ {
		a[i] = val
	}
	return
}
func intsPeekBack(a []int) int {
	if len(a) == 0 {
		panic("func peekBack: zero length slice")
	}
	return a[len(a)-1]
}
func intsPeekFront(a []int) int {
	if len(a) == 0 {
		panic("func peekFront: zero length slice")
	}
	return a[0]
}
func intsPopBack(a []int) (int, []int) {
	if len(a) == 0 {
		panic("func popBack: zero length slice")
	}
	return a[len(a)-1], a[:len(a)-1]
}
func intsPopFront(a []int) (int, []int) {
	if len(a) == 0 {
		panic("func popFront: zero length slice")
	}
	return a[0], a[1:]
}
func intsPushBack(a []int, x int) []int  { return append(a, x) }
func intsPushFront(a []int, x int) []int { return append([]int{x}, a...) }
func intsAppendSentinelHead(a []int, sentinel int) []int {
	return append([]int{sentinel}, a...)
}
func intsAppendSentinelTail(a []int, sentinel int) []int {
	return append(a, sentinel)
}
func intsAppendSentinel(a []int, sentinel int) []int {
	return append(append([]int{sentinel}, a[:len(a):len(a)+2]...), sentinel)
}
func isEven(n int) bool    { return n&1 == 0 }
func isOdd(n int) bool     { return n&1 == 1 }
func ceil(x float64) int   { return int(math.Ceil(x)) }
func ceilDiv(x, y int) int { return (x + y - 1) / y }
func pow(x, y int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for i := y; i != 0; i >>= 1 {
		if i&1 == 1 {
			z *= x
		}
		x *= x
	}
	return z
}
func fact(x int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact *= i
	}
	return fact
}
func sigmaK(n int) int  { return n * (n + 1) / 2 }
func sigmaKK(n int) int { return (n * (n + 1) / 2) * (2*n + 1) / 3 }
func euclideanDistance(a, b point) float64 {
	s := diff(a.x, b.x)
	s *= s
	t := diff(a.y, b.y)
	t *= t
	return math.Sqrt(float64(s) + float64(t))
}
func manhattanDistance(a, b point) int {
	s := diff(a.x, b.x)
	t := diff(a.y, b.y)
	return s + t
}
func swap(a, b *int) { *a, *b = *b, *a }
func chmax(a *int, b int) {
	if *a < b {
		*a = b
	}
}
func chmin(a *int, b int) {
	if *a > b {
		*a = b
	}
}
func cumSum(a []int) []int {
	b := append([]int{0}, a...)
	for i := 1; i < len(b); i++ {
		b[i] += b[i-1]
	}
	return b
}
func runesReverse(a []rune) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func bytesReverse(a []byte) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func strUpperCase(s string) string { return strings.ToUpper(s) }
func strLowerCase(s string) string { return strings.ToLower(s) }
func strToInt(s string) int {
	i, err := strconv.Atoi(s)
	if err != nil {
		panic(err)
	}
	return i
}
func intToStr(i int) string  { return strconv.Itoa(i) }
func CalcMod(a, mod int) int { return (a%mod + mod) % mod }
func ModPow(x, y, mod int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for i := y; i != 0; i >>= 1 {
		if i&1 == 1 {
			z = (z * x) % mod
		}
		x = (x * x) % mod
	}
	return z
}
func ModFact(x, mod int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact = fact * i % mod
	}
	return fact
}
func ModInv(x, mod int) int { return ModPow(x, mod-2, mod) }
func initMatrixBool(parentSize, childSize int, initialValue bool) *[][]bool {
	res := make([][]bool, parentSize)
	for i := range res {
		res[i] = make([]bool, childSize)
		for j := range res[i] {
			res[i][j] = initialValue
		}
	}
	return &res
}
func initMatrixInt(parentSize, childSize int, initialValue int) *[][]int {
	res := make([][]int, parentSize)
	for i := range res {
		res[i] = make([]int, childSize)
		for j := range res[i] {
			res[i][j] = initialValue
		}
	}
	return &res
}

var (
	sc = bufio.NewScanner(os.Stdin)
	bw = bufio.NewWriterSize(os.Stdout, bwBufSize)
)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1e7), 1e7)
}
func ru() (n int) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}
func ri() (n int) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	b := sc.Bytes()
	neg := false
	if b[0] == 45 {
		neg = true
		b = b[1:]
	}
	for _, v := range b {
		n = n*10 + int(v-48)
	}
	if neg {
		n = -n
	}
	return
}
func ri64() (n int64) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	b := sc.Bytes()
	neg := false
	if b[0] == 45 {
		neg = true
		b = b[1:]
	}
	for _, v := range b {
		n = n*10 + int64(v-48)
	}
	if neg {
		n = -n
	}
	return
}
func rf64() float64 {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	f, err := strconv.ParseFloat(sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return f
}
func rs() string {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return sc.Text()
}
func rb() []byte {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return sc.Bytes()
}
func rr() []rune {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return []rune(sc.Text())
}
func ris(n int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = ri()
	}
	return s
}
func risZeroBased(n int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = ri() - 1
	}
	return s
}
func ri64s(n int) []int64 {
	s := make([]int64, n)
	for i := range s {
		s[i] = ri64()
	}
	return s
}
func rss(n int) []string {
	s := make([]string, n)
	for i := range s {
		s[i] = rs()
	}
	return s
}
func pf(format string, a ...interface{}) {
	if _, err := fmt.Fprintf(bw, format, a...); err != nil {
		panic(err)
	}
}
func pln(a ...interface{}) {
	if _, err := fmt.Fprintln(bw, a...); err != nil {
		panic(err)
	}
}
func pints(a []int) {
	for _, v := range a {
		fmt.Fprintln(bw, v)
	}
}
func pintsol(a []int) {
	s := fmt.Sprint(a)
	if _, err := fmt.Fprintln(bw, s[1:len(s)-1]); err != nil {
		panic(err)
	}
}
func dbg(a ...interface{}) {
	if _, err := fmt.Fprintln(os.Stderr, a...); err != nil {
		panic(err)
	}
}
func YESorNO(b bool) string {
	if b {
		return "YES"
	} else {
		return "NO"
	}
}
func YesOrNo(b bool) string {
	if b {
		return "Yes"
	} else {
		return "No"
	}
}
func main() {
	solve()
	bw.Flush()
}

const (
	bwBufSize = 1e6

	alphabetUpper = "abcdefghijklmnopqrstuvwxyz"
	alphabetLower = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

	// maxInt64  = 9223372036854775807  // 9e18
	// maxInt32  = 2147483647           // 2e9
	// maxUint64 = 18446744073709551615 // 1e19
	inf = 1 << 60
	mod = 1e9 + 7
)

type pair struct{ fi, se int }
type byFiSe []pair

func (p byFiSe) Len() int      { return len(p) }
func (p byFiSe) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p byFiSe) Less(i, j int) bool {
	if p[i].fi == p[j].fi {
		return p[i].se < p[j].se
	}
	return p[i].fi < p[j].fi
}

type point struct{ x, y int }

type djSet struct{ p []int }

func newDj(size int) *djSet {
	dj := &djSet{}
	dj.initDjSet(size)
	return dj
}
func (dj *djSet) initDjSet(size int) {
	dj.p = make([]int, size)
	for i := 0; i < size; i++ {
		dj.p[i] = -1
	}
	return
}
func (dj *djSet) unite(x, y int) bool {
	xr, yr := dj.find(x), dj.find(y)
	if xr != yr {
		if dj.p[yr] < dj.p[xr] {
			x, y = y, x
			xr, yr = yr, xr
		}
		dj.p[xr] += dj.p[yr]
		dj.p[yr] = x
	}
	return xr != yr
}
func (dj *djSet) find(x int) int {
	if dj.p[x] < 0 {
		return x
	}
	return dj.find(dj.p[x])
}
func (dj *djSet) isSame(x, y int) bool { return dj.find(x) == dj.find(y) }
func (dj *djSet) size(x int) int       { return -dj.p[dj.find(x)] }

func solve() {
	q := ri()
	for i := 0; i < q; i++ {
		query()
	}
}

func query() {
	n := ri()
	ps := risZeroBased(n)

	dj := newDj(n)
	for j := range ps {
		dj.unite(j, ps[j])
	}

	for j := range ps {
		if j == n-1 {
			pf("%d\n", dj.size(j))
		} else {
			pf("%d ", dj.size(j))
		}
	}
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n, q int
	fmt.Fscanf(reader, "%d\n", &q)

	for ; q > 0; q-- {
		fmt.Fscanf(reader, "%d\n", &n)

		p := make([]int, n+1)
		num := make([]int, n+1)
		for i := 1; i <= n; i++ {
			if i == n {
				fmt.Fscanf(reader, "%d\n", &p[i])
			} else {
				fmt.Fscanf(reader, "%d ", &p[i])
			}

			num[i] = i
		}

		ans := make([]int, n+1)
		sum := 0

		for k := 1; sum < n; k++ {
			tmp := make([]int, n+1)
			for i := 1; i <= n; i++ {
				tmp[p[i]] = num[i]
			}
			num = tmp
			for i := 1; i <= n; i++ {
				if num[i] == i && ans[i] == 0 {
					sum++
					ans[i] = k
				}
			}
		}

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

	}

}

package main

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

type WordScanner struct {
	*bufio.Scanner
}

func NewWordScanner() *WordScanner {
	s := bufio.NewScanner(os.Stdin)
	s.Split(bufio.ScanWords)
	return &WordScanner{Scanner: s}
}

func (s *WordScanner) NextInt() int {
	s.Scan()
	i, _ := strconv.Atoi(s.Text())
	return i
}

func (s *WordScanner) NextInt64() int64 {
	s.Scan()
	i, _ := strconv.ParseInt(s.Text(), 10, 64)
	return i
}

func (s *WordScanner) NextString() string {
	s.Scan()
	return s.Text()
}

func main() {
	ws := NewWordScanner()
	q := ws.NextInt()
	for ; q > 0; q-- {
		n := ws.NextInt()
		sl := []int{}
		for ; n > 0; n-- {
			sl = append(sl, ws.NextInt())
		}
		p(sol(sl))
	}
}

func p(o []int) {
	s := []string{}
	for _, i := range o {
		s = append(s, strconv.Itoa(i))
	}
	fmt.Println(strings.Join(s, " "))
}

func sol(sl []int) []int {
    seen := map[int]bool{}
    ret := make([]int, len(sl))
    for _, i := range sl {
        if seen[i] {
            continue
        }
        c := findCycle(sl, i)
        for _, v := range c {
            ret[v-1] = len(c)
        }
    }
    return ret
}

func findCycle(sl []int, i int) []int {
    ret := []int{i}
    curr := sl[i-1]
    for curr != i {
        ret = append(ret, i)
        curr = sl[curr-1]
    }
    return ret
}

package main

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

func main() {
	defer Flush()

	q := readi()
	for i := 0; i < q; i++ {
		n, p := readInts(0)
		b := solve(n, p)
		sp := ""
		for _, v := range b {
			printf("%s%d", sp, v)
			sp = " "
		}
		println()
	}
}

func dfs(a, b []int, seen []bool, d, v int) int {
	if seen[v] {
		return d
	}
	seen[v] = true
	u := a[v] - 1
	b[v] = dfs(a, b, seen, d+1, u)
	return b[v]
}

func solve(n int, a []int) []int {

	seen := make([]bool, n)
	b := make([]int, n)

	for i := range a {
		if !seen[i] {
			dfs(a, b, seen, 0, i)
		}
	}
	return b
}

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

// IO helper functions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// IO functions

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

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

// Read next line as []byte.  Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

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

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

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

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

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

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

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

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

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

// Utilities

func sumSlice(a []int) int {
	var res int
	for _, v := range a {
		res += v
	}
	return res
}

func sumSlicell(a []int64) int64 {
	var res int64
	for _, v := range a {
		res += v
	}
	return res
}

func readInts(N int) (int, []int) {
	if N == 0 {
		N = readi()
	}
	a := make([]int, N)
	for i := range a {
		a[i] = readi()
	}
	return N, a
}

func readIntsll(N int) (int, []int64) {
	if N == 0 {
		N = readi()
	}
	a := make([]int64, N)
	for i := range a {
		a[i] = readll()
	}
	return N, a
}

// reverse slice in place
func reverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
}

// areverse: allocating reverse
func areverse(a []int) []int {
	b := make([]int, len(a))
	for i := range a {
		b[i] = a[len(a)-i-1]
	}
	return b
}

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

// Simple math functions

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

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

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

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

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

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

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

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

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

func absf(a float64) float64 {
	if a < 0 {
		return -a
	}
	return a
}

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

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

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

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

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

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

package main

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

func main() {
	defer Flush()

	q := readi()
	for i := 0; i < q; i++ {
		n, p := readInts(0)
		b := solve(n, p)
		sp := ""
		for _, v := range b {
			printf("%s%d", sp, v)
			sp = " "
		}
		println()
	}
}

func solve(n int, a []int) []int {

	p := make([]int, n+10)
	s := make([]int, n+10)
	for i := range p {
		p[i] = i
		s[i] = 1
	}

	var find func(i int) (int, int)
	find = func(i int) (int, int) {
		pid := p[i]
		if pid == i {
			return i, s[i]
		}
		x, v := find(pid)
		p[i] = x
		s[i] = v
		return x, v
	}
	connect := func(i, j int) {
		pi, si := find(i)
		pj, sj := find(j)
		if pi == pj {
			return
		}
		if sj < si {
			si, sj = sj, si
			pi, pj = pj, pi
		}
		p[pi] = pj
		s[pj] = si + sj
	}

	for i, v := range a {
		v--
		connect(i, v)
	}

	res := make([]int, n)
	for i := range res {
		_, sz := find(i)
		res[i] = sz
	}
	return res
}

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

// IO helper functions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// IO functions

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

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

// Read next line as []byte.  Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

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

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

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

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

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

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

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

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

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

// Utilities

func sumSlice(a []int) int {
	var res int
	for _, v := range a {
		res += v
	}
	return res
}

func sumSlicell(a []int64) int64 {
	var res int64
	for _, v := range a {
		res += v
	}
	return res
}

func readInts(N int) (int, []int) {
	if N == 0 {
		N = readi()
	}
	a := make([]int, N)
	for i := range a {
		a[i] = readi()
	}
	return N, a
}

func readIntsll(N int) (int, []int64) {
	if N == 0 {
		N = readi()
	}
	a := make([]int64, N)
	for i := range a {
		a[i] = readll()
	}
	return N, a
}

// reverse slice in place
func reverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
}

// areverse: allocating reverse
func areverse(a []int) []int {
	b := make([]int, len(a))
	for i := range a {
		b[i] = a[len(a)-i-1]
	}
	return b
}

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

// Simple math functions

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

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

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

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

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

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

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

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

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

func absf(a float64) float64 {
	if a < 0 {
		return -a
	}
	return a
}

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

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

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

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

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

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

package main

import (
    "fmt"
    "bufio"
    "os"
)
var input *bufio.Reader

func solve() {
    var n int
    fmt.Fscanf(input, "%d\n", &n)
    p := make([]int, n+1)
    ans := make([]int, n+1)
    vis := make([]bool, n+1)
    for i:=1; i<=n; i++ {
        fmt.Fscanf(input, "%d", &p[i])
    }
    fmt.Fscanf(input, "\n")
    for i:=1; i<=n; i++ {
        if vis[i] {
            continue
        }
        j := i
        cnt := 0
        vec := make([]int, 0)
        for !vis[j] {
            vis[j] = true
            vec = append(vec, j)
            j = p[j]
            cnt++
        }
        for _, j := range vec {
            ans[j] = cnt
        }
    }
    for i:=1; i<=n; i++ {
        fmt.Printf("%d ", ans[i])
    }
    fmt.Println()
}

func main(){
    input = bufio.NewReader(os.Stdin)
    var T int
    fmt.Fscanf(input, "%d\n", &T)
    for i:=0; i<T; i++ {
        solve()
    }
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n, q int
	fmt.Fscanf(reader, "%d\n", &q)

	for ; q > 0; q-- {
		fmt.Fscanf(reader, "%d\n", &n)

		p := make([]int, n+1)

		for i := 1; i <= n; i++ {
			if i == n {
				fmt.Fscanf(reader, "%d\n", &p[i])
			} else {
				fmt.Fscanf(reader, "%d ", &p[i])
			}
		}

		ans := make([]int, n+1)

		for i := 1; i <= n; i++ {
			t := i
			cache := make(map[int]bool, 100)
			for k := 1; ans[i] == 0; k++ {
				t = p[t]

				if t == i {
					ans[i] = k
				} else {
					cache[t] = true
				}
			}

			for key, _ := range cache {
				ans[key] = ans[i]
			}
		}

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

	}

}

package main

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

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

	var n int
	Fscan(in, &n)

}

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