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

	}

}


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


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