package main

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

func main_div2_781_C() {
	_in, _out := os.Stdin, os.Stdout
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()
	var cas int = 1
	Fscan(in, &cas)
	var sol func()
	/* Begin Coding */
	sol = func() {
		var n int
		Fscan(in, &n)
		children := make([][]int, n+1)
		var pa int
		parent := map[int]struct{}{}
		for i := 2; i <= n; i++ {
			Fscan(in, &pa)
			children[pa] = append(children[pa], i)
			parent[pa] = struct{}{}
		}
		sort.Slice(children, func(i, j int) bool {
			return len(children[i]) > len(children[j])
		})
		arr := []int{}
		Inject := len(parent) + 1
		for i := 0; i < len(children); i++ {
			if len(children[i]) == 0 {
				break
			}
			spreadTime := Inject - i - 1
			if len(children[i])-1 > spreadTime {
				// Inject += (len(children[i]) - 1 - spreadTime + 1) / 2
				arr = append(arr, len(children[i])-1-spreadTime)
			}
		}
		sort.Slice(arr, func(i, j int) bool {
			return arr[i] > arr[j]
		})
		for len(arr) > 0 {
			arr[0] -= 1
			Inject++
			for i := 0; i < len(arr); i++ {
				arr[i]--
			}
			sort.Slice(arr, func(i, j int) bool {
				return arr[i] > arr[j]
			})
			for arr[len(arr)-1] <= 0 {
				arr = arr[:len(arr)-1]
				if len(arr) == 0 {
					break
				}
			}
		}

		// Inject := len(parent) + 1
		// for i := 0; i < len(children); i++ {
		// 	if len(children[i]) == 0 {
		// 		break
		// 	}
		// 	spreadTime := Inject - i - 1
		// 	if len(children[i])-1 > spreadTime {
		// 		Inject += (len(children[i]) - 1 - spreadTime + 1) / 2
		// 	}
		// }
		Fprintln(out, Inject)
	}
	/* Code Ending */
	for i := 0; i < cas; i++ {
		sol()
	}

}

func main() {
	main_div2_781_C()
}

package main

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

const mod = 998244353

var ans int

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int
	fmt.Fscan(in,&n)
	degree := make([]int,n + 1)
	for i := 0;i < n - 1;i++{
		var item int
		fmt.Fscan(in,&item)
		degree[item - 1]++
	}
	degree[n] = 1
	sort.Slice(degree,func(i,j int)bool{
		return degree[i] > degree[j]
	})
	for len(degree) != 0 && degree[len(degree) - 1] == 0{
		degree = degree[:len(degree) - 1]
	}
	ans = len(degree)
	for i,v := range degree{
		if degree[i] != 0{
			degree[i] = v - (len(degree) - i)
		}else{
			break
		}
	}
	sort.Slice(degree,func(i,j int)bool{
		return degree[i] > degree[j]
	})
	for len(degree) != 0 && degree[len(degree) - 1] <= 0{
		degree = degree[:len(degree) - 1]
	}

	proc(degree)
	fmt.Fprintln(out,ans)
}
func proc(arr []int){
	if len(arr) == 0{
		return
	}
	last := 0
	for i,v := range arr{
		if v == arr[0]{
			last = i
		}else{
			break
		}
	}
	arr[last]--
	ans++
	for i := range arr{
		if arr[i] != 0{
			arr[i]--
		}else{
			break
		}
	}
	for len(arr) != 0 && arr[len(arr) - 1] == 0{
		arr = arr[:len(arr) - 1]
	}
	proc(arr)
}

func abs(a,b int)int{
	if a > b{
		return a - b
	}
	return b - a
}
func sum(a,b int64)int64{
	return (b + a) * (b - a + 1) / 2
}

func max(a,b int)int{
	if a > b{
		return a
	}
	return b
}
func min(a,b int)int{
	if a > b{
		return b
	}
	return a
}
func gcd(a,b int)int{
	if a % b == 0{
		return b
	}
	return gcd(b,a%b)
}

func main() {
	stdin := os.Stdin
	stdout := os.Stdout
	in := bufio.NewReader(stdin)
	out := bufio.NewWriter(stdout)
	n := 1
	fmt.Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}

package main

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

const mod = 998244353

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int
	fmt.Fscan(in,&n)
	degree := make([]int,n + 1)
	for i := 0;i < n - 1;i++{
		var item int
		fmt.Fscan(in,&item)
		degree[item - 1]++
	}
	degree[n] = 1
	sort.Slice(degree,func(i,j int)bool{
		return degree[i] > degree[j]
	})
	l := 1
	r := n
	for l <= r{
		mid := (l + r) / 2
		inj := mid
		rest := 0
		for i,v := range degree{
			if v == 0{
				break
			}
			inj--
			if i + v > mid{
				rest += (i + v) - mid
			}
		}

		if inj - rest >= 0{
			r = mid - 1
		}else{
			l = mid + 1
		}
	}
	fmt.Fprintln(out,l)
}

func abs(a,b int)int{
	if a > b{
		return a - b
	}
	return b - a
}
func sum(a,b int64)int64{
	return (b + a) * (b - a + 1) / 2
}

func max(a,b int)int{
	if a > b{
		return a
	}
	return b
}
func min(a,b int)int{
	if a > b{
		return b
	}
	return a
}
func gcd(a,b int)int{
	if a % b == 0{
		return b
	}
	return gcd(b,a%b)
}

func main() {
	stdin := os.Stdin
	stdout := os.Stdout
	in := bufio.NewReader(stdin)
	out := bufio.NewWriter(stdout)
	n := 1
	fmt.Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}

package main

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

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

func A(_r io.Reader, _w io.Writer) {
	in, out := bufio.NewReader(_r), bufio.NewWriter(_w)
	defer out.Flush()
	var c int
	var n int
	Fscan(in, &c)
	for ; c > 0; c-- {
		Fscan(in, &n)
		arr := []int{}
		mp := make(map[int]int)
		for i := 2; i <= n; i++ {
			v := 0
			Fscan(in, &v)
			mp[v]++
		}
		for _, v := range mp {
			arr = append(arr, v)
		}
		arr = append(arr, 1)
		sort.Slice(arr, func(i, j int) bool {
			return arr[i] > arr[j]
		})

		ans := len(arr)
		for i := range arr {
			arr[i]--
			arr[i] -= len(arr) - i - 1
		}
		for len(arr) > 0 && arr[len(arr)-1] <= 0 {
			arr = arr[:len(arr)-1]
		}
		for len(arr) > 0 {
			//扩散
			for i := range arr {
				arr[i]--
			}
			for len(arr) > 0 && arr[len(arr)-1] <= 0 {
				arr = arr[:len(arr)-1]
			}
			//注射
			if len(arr) > 0 {
				arr[0]--
			}
			sort.Slice(arr, func(i, j int) bool {
				return arr[i] > arr[j]
			})
			for len(arr) > 0 && arr[len(arr)-1] <= 0 {
				arr = arr[:len(arr)-1]
			}
			ans++
		}
		Fprintln(out, ans)
	}
}

package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var n,k int
	fmt.Fscan(in, &n)
	for i := 0;i < n;i++ {
		fmt.Fscan(in,&k)
		tree := make(map[int]int)
		arr := []int{}
		for j := 2;j <= k;j++ {
			var t int
			fmt.Fscan(in,&t)
			tree[t]++
		}
		for _,v := range tree {
			arr = append(arr,v)
		}
		arr = append(arr,1)
		sort.Slice(arr, func(i, j int) bool {
			return arr[i] > arr[j]
		})
		res := len(arr)
		for i := range arr {
			arr[i] -= len(arr) - i
		}
		for len(arr) > 0 && arr[len(arr)-1] <= 0 {
			arr = arr[:len(arr)-1]
		}
		for len(arr) > 0 {
			for i := range arr {
				arr[i] --
			}
			for len(arr) > 0 && arr[len(arr)-1] <= 0{
				arr = arr[:len(arr)-1]
			}
			if len(arr) > 0 {
				arr[0]--
			}
			sort.Slice(arr, func(i, j int) bool {
				return arr[i] > arr[j]
			})
			for len(arr) > 0 && arr[len(arr)-1] <= 0{
				arr = arr[:len(arr)-1]
			}
			res++
		}
		fmt.Fprintln(out,res)
	}
}

package main

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

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

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

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

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

		m := make(map[int]int)
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)

			m[v]++
		}

		type vx struct {
			id, c int
		}

		a := []vx{}
		for k, v := range m {
			a = append(a, vx{k, v - 1})
		}

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

		k := len(a)
		var rem int
		for i, vx := range a {
			rem += vx.c - min(vx.c, k)
			a[i].c -= k
			k--
		}

		if rem <= 0 {
			fmt.Fprintln(out, len(a)+1)
		} else {
			tot := len(a)
			b := make([]int, len(a))
			for i := range a {
				b[i] = a[i].c
			}
			for rem > 0 {
				var maxIdx int
				for i := range b {
					if b[i] > 0 {
						b[i]--
						rem--

						if b[i] > b[maxIdx] {
							maxIdx = i
						}
					}
				}

				b[maxIdx]--
				rem--
				tot++
			}
			fmt.Fprintln(out, tot+1)
		}
	}
}

package main

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

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

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

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

		m := make(map[int]int)
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)

			m[v]++
		}

		type vx struct {
			id, c int
		}

		a := []vx{}
		for k, v := range m {
			a = append(a, vx{k, v - 1})
		}

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

		z := len(a)
		var tot int
		for _, v := range a {
			// fmt.Println(v.c - z)
			if v.c-z > 0 {
				tot += (v.c - z) / 2
				if (v.c-z)%2 != 0 {
					tot++
				}
			}
			tot++
			z--
		}

		fmt.Fprintln(out, tot+1)
	}
}

package main

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

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

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

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

		m := make(map[int]int)
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)

			m[v]++
		}

		type vx struct {
			id, c int
		}

		a := []vx{}
		for k, v := range m {
			a = append(a, vx{k, v - 1})
		}

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

		z := len(a) + 1
		var tot int
		for _, v := range a {
			if v.c-z > 0 {
				tot += (v.c - z) / 2
				if (v.c-z)%2 != 0 {
					tot++
				}
			}
			tot++
			z--
		}

		fmt.Fprintln(out, tot+1)
	}
}

package main

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

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

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

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

		m := make(map[int]int)
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)

			m[v]++
		}

		type vx struct {
			id, c int
		}

		a := []vx{}
		for k, v := range m {
			a = append(a, vx{k, v})
		}

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

		z := len(a) + 1
		var tot int
		for _, v := range a {
			if v.c-z > 0 {
				tot += (v.c - z) / 2
				if (v.c-z)%2 != 0 {
					tot++
				}
			}
			tot++
			z--
		}

		fmt.Fprintln(out, tot+1)
	}
}

package main

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

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

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

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

		m := make(map[int]int)
		u := 1
		var sibs int
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)

			if m[v] == 0 {
				u++
			} else {
				sibs++
			}
			m[v]++
		}

		if sibs-u <= 0 {
			fmt.Fprintln(out, u)
		} else {
			tot := u + (sibs / 2)
			// if sibs%2 != 0 {
			// 	tot++
			// }
			fmt.Fprintln(out, tot)
		}
	}
}

package main

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

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

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

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

		m := make(map[int]int)
		u := 1
		var sibs int
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)

			if m[v] == 0 {
				u++
			} else {
				sibs++
			}
			m[v]++
		}

		if sibs-u < 0 {
			fmt.Fprintln(out, u)
		} else {
			tot := u + (sibs / 2)
			// if sibs%2 != 0 {
			// 	tot++
			// }
			fmt.Fprintln(out, tot)
		}
	}
}

package main

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

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

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

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

		m := make(map[int]int)
		u := 1
		var sibs int
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)

			if m[v] == 0 {
				u++
			} else {
				sibs++
			}
			m[v]++
		}

		if sibs-u < 0 {
			fmt.Fprintln(out, u)
		} else {
			tot := u + sibs/2
			if sibs%2 != 0 {
				tot++
			}
			fmt.Fprintln(out, tot)
		}
	}
}

package main

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

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

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

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

		m := make(map[int]int)
		u := 1
		var sibs int
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)

			if m[v] == 0 {
				u++
			} else {
				sibs++
			}
			m[v]++
		}

		if sibs-u < 0 {
			fmt.Fprintln(out, u)
		} else {
			tot := u + (sibs-u)/2
			if sibs-u%2 != 0 {
				tot++
			}
			fmt.Fprintln(out, tot)
		}
	}
}

package main

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

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

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

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

		m := make(map[int]int)
		u := 1
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)

			_, ok := m[v]
			if !ok {
				u++
			}
			m[v]++
		}

		tot := u
		for _, v := range m {
			if v > tot {
				tot += (v - u) / 2
				if (v-u)%2 != 0 {
					tot++
				}
			}
		}
		fmt.Fprintln(out, tot)
	}
}

package main

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

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

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

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

		m := make(map[int]int)
		var u int
		for i := 0; i < n-1; i++ {
			var v int
			fmt.Fscan(in, &v)

			_, ok := m[v]
			if !ok {
				u++
			}
			m[v]++
		}

		tot := u
		for _, v := range m {
			if v > tot {
				tot += (v - u) / 2
				if (v-u)%2 != 0 {
					tot++
				}
			}
		}
		fmt.Fprintln(out, tot+1)
	}
}

package main

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

const mod = 998244353

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int
	fmt.Fscan(in,&n)
	degree := make([]int,n)
	for i := 0;i < n - 1;i++{
		var item int
		fmt.Fscan(in,&item)
		degree[item - 1]++
	}
	sort.Slice(degree,func(i,j int)bool{
		return degree[i] > degree[j]
	})
	l := 1
	r := int(1e5) + 100
	ans := -1
	for l <= r{
		mid := (l + r) / 2
		inj := mid
		for i,v := range degree{
			if v == 0{
				break
			}
			inj--
			if i + v > mid{
				inj -= i + v - mid
			}
		}
		if inj < 1{
			l = mid + 1
		}else{
			ans = mid
			r = r - 1
		}
	}
	fmt.Fprintln(out,ans)
}

func abs(a,b int)int{
	if a > b{
		return a - b
	}
	return b - a
}
func sum(a,b int64)int64{
	return (b + a) * (b - a + 1) / 2
}

func max(a,b int)int{
	if a > b{
		return a
	}
	return b
}
func min(a,b int)int{
	if a > b{
		return b
	}
	return a
}
func gcd(a,b int)int{
	if a % b == 0{
		return b
	}
	return gcd(b,a%b)
}

func main() {
	stdin := os.Stdin
	stdout := os.Stdout
	in := bufio.NewReader(stdin)
	out := bufio.NewWriter(stdout)
	n := 1
	fmt.Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}

package main

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

const mod = 998244353

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int
	fmt.Fscan(in,&n)
	degree := make([]int,n)
	for i := 0;i < n - 1;i++{
		var item int
		fmt.Fscan(in,&item)
		degree[item - 1]++
	}
	sort.Slice(degree,func(i,j int)bool{
		return degree[i] > degree[j]
	})
	l := 1
	r := int(1e5) + 1
	for l <= r{
		mid := (l + r) / 2
		inj := mid
		for i,v := range degree{
			if v == 0{
				break
			}
			inj--
			if i + v > mid{
				inj -= i + v - mid
			}
		}
		if inj < 1{
			l = mid + 1
		}else{
			r = r - 1
		}
	}
	fmt.Println(l)
}

func abs(a,b int)int{
	if a > b{
		return a - b
	}
	return b - a
}
func sum(a,b int64)int64{
	return (b + a) * (b - a + 1) / 2
}

func max(a,b int)int{
	if a > b{
		return a
	}
	return b
}
func min(a,b int)int{
	if a > b{
		return b
	}
	return a
}
func gcd(a,b int)int{
	if a % b == 0{
		return b
	}
	return gcd(b,a%b)
}

func main() {
	stdin := os.Stdin
	stdout := os.Stdout
	in := bufio.NewReader(stdin)
	out := bufio.NewWriter(stdout)
	n := 1
	fmt.Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}

package main

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

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

func A(_r io.Reader, _w io.Writer) {
	in, out := bufio.NewReader(_r), bufio.NewWriter(_w)
	defer out.Flush()
	var c int
	var n int
	Fscan(in, &c)
	for ; c > 0; c-- {
		Fscan(in, &n)
		arr := []int{}
		mp := make(map[int]int)
		for i := 2; i <= n; i++ {
			v := 0
			Fscan(in, &v)
			mp[v]++
		}
		for _, v := range mp {
			arr = append(arr, v)
		}
		arr = append(arr, 1)
		sort.Slice(arr, func(i, j int) bool {
			return arr[i] > arr[j]
		})
		p := 0
		x := 0
		ans := 0
		for n > 0 {
			ans++
			//注入
			for p < len(arr) && arr[p] <= 0 {
				p++
			}
			if p == len(arr) {
				p = 0
			}
			for p < len(arr) && arr[p] <= 0 {
				p++
			}
			arr[p]--
			n--
			p++
			if p == len(arr) {
				p = 0
			}
			//扩散
			for i := 0; i < min(x, len(arr)); i++ {
				if arr[i] > 0 {
					n--
					arr[i]--
				}
			}
			x++
		}
		Fprintf(out, "%d\n", ans)
	}
}
func min(i, j int) int {
	if i < j {
		return i
	}
	return j
}

package main

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

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

func A(_r io.Reader, _w io.Writer) {
	in, out := bufio.NewReader(_r), bufio.NewWriter(_w)
	defer out.Flush()
	var c int
	var n int
	Fscan(in, &c)
	for ; c > 0; c-- {
		Fscan(in, &n)
		arr := []int{}
		mp := make(map[int]int)
		for i := 2; i <= n; i++ {
			v := 0
			Fscan(in, &v)
			mp[v]++
		}
		for _, v := range mp {
			arr = append(arr, v)
		}
		arr = append(arr, 1)
		sort.Slice(arr, func(i, j int) bool {
			return arr[i] > arr[j]
		})
		Println(arr)
		p := 0
		x := 0
		ans := 0
		for n > 0 {
			ans++
			//注入
			for p < len(arr) && arr[p] <= 0 {
				p++
			}
			if p == len(arr) {
				p = 0
			}
			for p < len(arr) && arr[p] <= 0 {
				p++
			}
			arr[p]--
			n--
			p++
			if p == len(arr) {
				p = 0
			}
			//扩散
			for i := 0; i < min(x, len(arr)); i++ {
				if arr[i] > 0 {
					n--
					arr[i]--
				}
			}
			x++
		}
		Fprintf(out, "%d\n", ans)
	}
}
func min(i, j int) int {
	if i < j {
		return i
	}
	return j
}

package main

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

func main_div2_781_C() {
	_in, _out := os.Stdin, os.Stdout
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()
	var cas int = 1
	Fscan(in, &cas)
	var sol func()
	/* Begin Coding */
	sol = func() {
		var n int
		Fscan(in, &n)
		children := make([][]int, n+1)
		var pa int
		parent := map[int]struct{}{}
		for i := 2; i <= n; i++ {
			Fscan(in, &pa)
			children[pa] = append(children[pa], i)
			parent[pa] = struct{}{}
		}
		sort.Slice(children, func(i, j int) bool {
			return len(children[i]) > len(children[j])
		})
		Inject := len(parent) + 1
		//Fprintln(out, "Inject:", Inject)
		for i := 0; i < len(children); i++ {
			if len(children[i]) == 0 {
				break
			}
			spreadTime := Inject - i - 1
			if len(children[i])-1 > spreadTime {
				Inject += (len(children[i]) - 1 - spreadTime + 1) / 2
			}
			//	Fprintln(out, "Inject:", Inject)
		}
		Fprintln(out, Inject)
	}
	/* Code Ending */
	for i := 0; i < cas; i++ {
		sol()
	}

}

func main() {
	main_div2_781_C()
}


package main

import (
	"fmt"
)

func main() {
	var n int
	var s int64
	fmt.Scan(&n)
	fmt.Scan(&s)
	var arr [100001]int64
	for i := 0; i < n ; i++ {
		fmt.Scan(&arr[i])
	}
	lo := (int64)(0)
	hi := (int64)(1000*1000*1000)
	res := (int64)(-1)
	for ;lo <= hi; {

		mid := (int64)(lo + (hi - lo) / 2)
		var cur int64
		cur = 0
		for i := 0 ; i < n ; i++ {
			if arr[i] >= mid {
				cur += arr[i] - mid;
			} else {
				cur = -1;
				break;
			}
		}
		if cur >= s {
			lo = mid + 1
			res = mid
		} else {
			hi = mid - 1;
		}
	}
	fmt.Println(res)
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)

func scanNum() int64 {
	scanner.Scan()
	num, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return num
}

func main() {
	scanner.Split(bufio.ScanWords)
	n, s := scanNum(), scanNum()
	v := make([]int64, n)
	min := int64(1e13)
	for i := int64(0); i < n; i++ {
		v[i] = scanNum()
		if v[i] < min {
			min = v[i]
		}
	}
	extra := int64(0)
	for i := int64(0); i < n; i++ {
		extra += v[i] - min
	}
	if extra >= s {
		fmt.Println(min)
		os.Exit(0)
	}

	cut := int64(math.Ceil(float64(s-extra) / float64(n)))
	if cut > min {
		fmt.Println(-1)
		os.Exit(0)
	}
	fmt.Println(min - cut)
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)

func scanInt64() int64 {
	scanner.Scan()
	num, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return num
}

func main() {
	scanner.Split(bufio.ScanWords)
	n := scanInt64()
	s := scanInt64()
	kegs := make([]int64, n)
	extra := int64(0)
	sum := int64(0)
	min := int64(math.MaxInt64)

	for i := int64(0); i < n; i++ {
		k := scanInt64()
		if k < min {
			min = k
		}
		kegs[i] = k
	}

	for i := int64(0); i < n; i++ {
		sum += kegs[i]
		extra += kegs[i] - min
	}

	if sum < s {
		fmt.Println(-1)
		return
	}
	if extra >= s {
		fmt.Println(min)
		return
	}
	fmt.Println(min - int64(math.Ceil(float64(s-extra) / float64(n))))
}

package main

import (
	"fmt"
	"sort"
)

type SortByInt64 []int64

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

func main() {
	var n int64
	var s int64
	_, _ = fmt.Scan(&n)
	_, _ = fmt.Scan(&s)
	var k int64
	var kegs []int64
	sumKegs := int64(0)

	for i := int64(0); i < n; i++ {
		_, _ = fmt.Scan(&k)
		sumKegs += k
		kegs = append(kegs, k)
	}

	if k < s {
		fmt.Println(-1)
		return
	}

	p := int64(0)
	for p < s {
		sort.Sort(SortByInt64(kegs))
		subtract := kegs[len(kegs) - 1] - kegs[0]
		if subtract == 0 {
			subtract = 1
		}
		p += subtract
		kegs[len(kegs) - 1] -= subtract
	}
	sort.Sort(SortByInt64(kegs))
	fmt.Println(kegs[0])
}


package main

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

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

	var n int
	Fscan(in, &n)
	s := make([]string, n)
	for i := range s {
		Fscan(in, &s[i])
	}
	sort.Slice(s, func(i, j int) (less bool) { return s[i]+s[j] < s[j]+s[i] })
	for _, val := range s {
		Fprint(out, val)
	}
}

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

package main

import (
	"fmt"
	"sort"
)

const MAXC = 26
const MAXN = 50006

var arr[] string

type ByLex[] string

func (s ByLex) Len() int {
	return len(s)
}

func (s ByLex) Swap(i,j int) {
	s[i], s[j] = s[j], s[i]
}

func (s ByLex) Less(i,j int) bool {
	// lenI, lenJ, k, ml := len(s[i]), len(s[j]), 0, 0
	// if lenI < lenJ {
	// 	ml = lenI
	// } else {
	// 	ml = lenJ
	// }
	// for k=0; k<ml; k++ {
	// 	if s[i][k] != s[j][k] {return s[i][k] < s[j][k]}
	// }
	// if lenI == lenJ {return false}
	// if lenI < lenJ {
	// 	for ; k<lenJ; k++ {
	// 		if s[j][k-ml] != s[j][k] {return s[j][k-ml] != s[j][k]}
	// 	}
	// }
	IJ, JI := s[i]+s[j], s[j]+s[i]
	return IJ < JI
}

func main() {
	var N int
	var str string
	fmt.Scanf("%d\n", &N)
	for ; N>0; N-- {
		fmt.Scanf("%s\n", &str)
		arr = append(arr,str)
	}
	sort.Sort(ByLex(arr))
	lengtharr := len(arr)
	for i:=0; i<lengtharr; i++ {
		lengthstr := len(arr[i])
		for j:=0; j<lengthstr; j++ {
			fmt.Printf("%c", arr[i][j])
		}
	}
	fmt.Printf("\n")
}

package main

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

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

type StringSlice []string

func (p StringSlice) Len() int      { return len(p) }
func (p StringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p StringSlice) Less(i, j int) bool {
	s, t := p[i], p[j]
	isSwap := false

	for t != "" {
		if len(s) > len(t) {
			s, t = t, s

			if isSwap {
				isSwap = false
			} else {
				isSwap = true
			}
		}

		l := len(s)

		if s != t[:l] {
			if isSwap {
				return t[:l] < s
			} else {
				return s < t[:l]
			}
		}

		t = t[l:]
	}

	return true
}

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

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	a := make([]string, n)

	for i := range a {
		a[i] = next()
	}

	sort.Sort(StringSlice(a))

	for i := range a {
		print(a[i])
	}

	println()
}

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

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

import (
	"fmt"
	"sort"
)

const MAXC = 26
const MAXN = 50006

var arr[] string

func main() {
	var N int
	var str string
	fmt.Scanf("%d\n", &N)
	for ; N>0; N-- {
		fmt.Scanf("%s\n", &str)
		str = str + string(65)
		arr = append(arr,str)
	}
	sort.Strings(arr)
	lengtharr := len(arr)
	for i:=0; i<lengtharr; i++ {
		lengthstr := len(arr[i])
		lengthstr--
		lengthstr--
		for j:=0; j<lengthstr; j++ {
			fmt.Printf("%c", arr[i][j])
		}
	}
	fmt.Printf("\n")
}

package main

import (
	"fmt"
	"sort"
)

const MAXC = 26
const MAXN = 50006

var arr[] string

func main() {
	var N int
	var str string
	fmt.Scanf("%d\n", &N)
	for ; N>0; N-- {
		fmt.Scanf("%s\n", &str)
		str = str + string(150)
		arr = append(arr,str)
	}
	sort.Strings(arr)
	lengtharr := len(arr)
	for i:=0; i<lengtharr; i++ {
		lengthstr := len(arr[i])
		lengthstr--
		for j:=0; j<lengthstr; j++ {
			fmt.Printf("%c", arr[i][j])
		}
	}
	fmt.Printf("\n")
}

package main

import "fmt"

const MAXC = 26
const MAXN = 50006

var TrieSZ int
var Trie[MAXN][MAXC] int
var Cnt[MAXN] int

func insert(str string) {
	i,length,cur,ch := 0, len(str), 0, 0
	for i=0; i<length; i++ {
		ch = int(str[i]) - 97
		if Trie[cur][ch] == 0 {
			TrieSZ++
			Trie[cur][ch] = TrieSZ
			Cnt[TrieSZ] = 0
		}
		cur = Trie[cur][ch]
		Cnt[cur]++
	}
}

var ans string

func print(cur,ch int) {
	ans = ans + string(ch+97)
	Cnt[cur]--
	for ch=0; ch<MAXC; ch++ {
		nxt := Trie[cur][ch]
		if nxt != 0 && Cnt[nxt] > 0 {
			print(nxt,ch)
			break
		}
	}
}

func gen() {
	ch, cur, nxt := 0,0,0
	ans = ""
	for ch=0; ch<MAXC; {
		nxt = Trie[cur][ch]
		if nxt != 0 && Cnt[nxt] > 0 {
			print(nxt,ch)
		} else {
			ch++
			continue
		}
	}
	fmt.Printf("%s\n", ans)
}

func main() {
	var N int
	var str string
	fmt.Scanf("%d", &N)
	for ; N>0; N-- {
		fmt.Scanf("%s", &str)
		insert(str)
	}
	gen()
}

package main

import (
	"fmt"
	"sort"
)

const MAXC = 26
const MAXN = 50006

var arr[] string

func main() {
	var N int
	var str string
	fmt.Scanf("%d\n", &N)
	for ; N>0; N-- {
		fmt.Scanf("%s\n", &str)
		str = str + string(96)
		arr = append(arr,str)
	}
	sort.Strings(arr)
	lengtharr := len(arr)
	for i:=0; i<lengtharr; i++ {
		lengthstr := len(arr[i])
		lengthstr--
		lengthstr--
		for j:=0; j<lengthstr; j++ {
			fmt.Printf("%c", arr[i][j])
		}
	}
	fmt.Printf("\n")
}

package main

import (
	"fmt"
	"sort"
)

const MAXC = 26
const MAXN = 50006

var arr[] string

func main() {
	var N int
	var str string
	fmt.Scanf("%d\n", &N)
	for ; N>0; N-- {
		fmt.Scanf("%s\n", &str)
		str = str + string(150)
		arr = append(arr,str)
	}
	sort.Strings(arr)
	lengtharr := len(arr)
	for i:=0; i<lengtharr; i++ {
		lengthstr := len(arr[i])
		lengthstr--
		lengthstr--
		for j:=0; j<lengthstr; j++ {
			fmt.Printf("%c", arr[i][j])
		}
	}
	fmt.Printf("\n")
}

package main

import (
	"fmt"
	"sort"
)

const MAXC = 26
const MAXN = 50006

var arr[] string

type ByLex[] string

func (s ByLex) Len() int {
	return len(s)
}

func (s ByLex) Swap(i,j int) {
	s[i], s[j] = s[j], s[i]
}

func (s ByLex) Less(i,j int) bool {
	// lenI, lenJ, k, ml := len(s[i]), len(s[j]), 0, 0
	// if lenI < lenJ {
	// 	ml = lenI
	// } else {
	// 	ml = lenJ
	// }
	// for k=0; k<ml; k++ {
	// 	if s[i][k] != s[j][k] {return s[i][k] < s[j][k]}
	// }
	// if lenI == lenJ {return false}
	// if lenI < lenJ {
	// 	for ; k<lenJ; k++ {
	// 		if s[j][k-ml] != s[j][k] {return s[j][k-ml] != s[j][k]}
	// 	}
	// }
	IJ, JI := s[i]+s[j], s[j]+s[i]
	return IJ < JI
}

func main() {
	var N int
	var str string
	fmt.Scanf("%d\n", &N)
	for ; N>0; N-- {
		fmt.Scanf("%s\n", &str)
		str = str + string(65)
		arr = append(arr,str)
	}
	sort.Strings(ByLex(arr))
	lengtharr := len(arr)
	for i:=0; i<lengtharr; i++ {
		lengthstr := len(arr[i])
		lengthstr--
		for j:=0; j<lengthstr; j++ {
			fmt.Printf("%c", arr[i][j])
		}
	}
	fmt.Printf("\n")
}

package main

import "fmt"

const MAXC = 26
const MAXN = 50006

var TrieSZ int
var Trie[MAXN][MAXC] int
var Cnt[MAXN] int

func insert(str string) {
	i,length,cur,ch := 0, len(str), 0, 0
	for i=0; i<length; i++ {
		ch = int(str[i]) - 97
		if Trie[cur][ch] == 0 {
			TrieSZ++
			Trie[cur][ch] = TrieSZ
			Cnt[TrieSZ] = 0
		}
		cur = Trie[cur][ch]
		Cnt[cur]++
	}
}

var ans string

func print(cur,ch int) {
	ans = ans + string(ch+97)
	Cnt[cur]--
	for ch=0; ch<MAXC; ch++ {
		nxt := Trie[cur][ch]
		if nxt != 0 && Cnt[nxt] > 0 {
			print(nxt,ch)
			break
		}
	}
}

func gen() {
	ch, cur, nxt := 0,0,0
	ans = ""
	for ch=0; ch<MAXC; {
		nxt = Trie[cur][ch]
		if nxt != 0 && Cnt[nxt] > 0 {
			print(nxt,ch)
		} else {
			ch++
			continue
		}
	}
	fmt.Printf("%s\n", ans)
}

func main() {
	var N int
	var str string
	fmt.Scanf("%d\n", &N)
	for ; N>0; N-- {
		fmt.Scanf("%s\n", &str)
		insert(str)
	}
	gen()
}

package main

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

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

type Strings struct {
	sort.StringSlice
}

func (s Strings) Less(i, j int) bool {
	l := len(s.StringSlice[i])

	if len(s.StringSlice[j]) < len(s.StringSlice[i]) {
		l = len(s.StringSlice[j])
	}

	for k := 0; k < l; k++ {
		if s.StringSlice[i][k] != s.StringSlice[j][k] {
			return s.StringSlice[i][k] < s.StringSlice[j][k]
		}
	}

	return l == len(s.StringSlice[j])
}

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	a := make([]string, n)

	for i := range a {
		a[i] = next()
	}

	sort.Sort(Strings{sort.StringSlice(a)})

	for i := range a {
		print(a[i])
	}

	println()
}

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

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

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

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

	var n int
	Fscan(in, &n)
	ss := make([]string, n)
	for i := range ss {
		Fscan(in, &ss[i])
	}
	sort.Slice(ss, func(i, j int) (less bool) {
		swap := false
		defer func() {
			if swap {
				less = !less
			}
		}()
		si, sj := ss[i], ss[j]
		if len(si) > len(sj) {
			si, sj = sj, si
			swap = true
		}
		for s, t := 0, len(si); s < t; {
			if si != sj[s:t] {
				return si < sj[s:t]
			}
			s = t
			t += len(si)
			if t > len(sj) {
				t = len(sj)
			}
		}
		return true
	})
	for _, s := range ss {
		Fprint(out, s)
	}
}

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


package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"os"
	"runtime/pprof"
	"strings"
)

func IsPalindrome(str string) bool {
	length := len(str)
	left := 0
	right := length - 1
	for left < right {
		if str[left] != str[right] {
			return false
		}
		left++
		right--
	}
	return true
}

func FindPalindrom(str string) string {
	if IsPalindrome(str) {
		return str
	}
	length := len(str)
	i := 0
	j := length - 1
	for str[i] == str[j] {
		i++
		j--
	}
	left := i
	right := j
	for ; left < j; left++ {
		if IsPalindrome(str[left : j+1]) {
			break
		}
	}
	for ; right > i; right-- {
		if IsPalindrome(str[i : right+1]) {
			break
		}
	}
	if (i + length - left) > (length - j + right) {
		return str[:i] + str[left:]
	}

	return str[:right+1] + str[j+1:]
}

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

func main() {
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}
	var n int64
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	_, err := fmt.Scanf("%d\n", &n)
	if err != nil {
		fmt.Printf("err1: %v", err.Error())
		os.Exit(1)
	}
	for ; n > 0; n-- {
		str, _ := reader.ReadString('\n')
		result := FindPalindrom(strings.TrimSpace(str))
		writer.WriteString(result)
		writer.WriteString("\n")
	}
	writer.Flush()
}

package main

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

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

func readNum(scanner *bufio.Scanner) (a int) {
	scanner.Scan()
	readInt(scanner.Bytes(), 0, &a)
	return
}

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

func readNNums(scanner *bufio.Scanner, n int) []int {
	res := make([]int, n)
	x := 0
	scanner.Scan()
	for i := 0; i < n; i++ {
		for x < len(scanner.Bytes()) && scanner.Bytes()[x] == ' ' {
			x++
		}
		x = readInt(scanner.Bytes(), x, &res[i])
	}
	return res
}

func fillNNums(scanner *bufio.Scanner, n int, res []int) {
	x := 0
	scanner.Scan()
	for i := 0; i < n; i++ {
		for x < len(scanner.Bytes()) && scanner.Bytes()[x] == ' ' {
			x++
		}
		x = readInt(scanner.Bytes(), x, &res[i])
	}
}

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

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

	return i
}

func readInt64(bytes []byte, from int, val *int64) int {
	i := from
	var tmp int64
	for i < len(bytes) && bytes[i] != ' ' {
		tmp = tmp*10 + int64(bytes[i]-'0')
		i++
	}
	*val = tmp
	return i
}

func readNInt64Nums(scanner *bufio.Scanner, n int) []int64 {
	res := make([]int64, n)
	x := -1
	scanner.Scan()
	for i := 0; i < n; i++ {
		x = readInt64(scanner.Bytes(), x+1, &res[i])
	}
	return res
}

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

	line, _ := reader.ReadString('\n')

	tc, _ := strconv.Atoi(strings.TrimSpace(line))

	for tc > 0 {
		tc--
		s, _ := reader.ReadString('\n')
		if len(s) == 0 {
			fmt.Println("no input read")
		} else {
			fmt.Println(solve(strings.TrimSpace(s)))
		}
	}
}

func solve(s string) string {
	var l, r int = 0, len(s) - 1
	for l <= r && s[l] == s[r] {
		l++
		r--
	}
	if l > r {
		return s
	}
	// l < r
	x := s[l : r+1]

	a := findLongestPrefixPalindrome(x)
	b := findLongestPrefixPalindrome(reverse(x))

	if len(a) < len(b) {
		a, b = b, a
	}

	return s[:l] + a + s[r+1:]
}

const BASE = 26
const MOD = 1000000007

func findLongestPrefixPalindrome(s string) string {
	n := len(s)
	var m int
	var a int64
	var b int64
	var X int64 = 1

	for i := 0; i < n; i++ {
		a = (a*BASE + int64(s[i]-'a')) % MOD
		b = (X*int64(s[i]-'a') + b) % MOD
		X = (X * BASE) % MOD
		if a != b {
			continue
		}

		j, k := 0, i

		for j < k && s[j] == s[k] {
			j++
			k--
		}

		if j >= k {
			m = i + 1
		}
	}
	return s[:m]
}

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

package main

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

type node struct {
	l, r, id int
}

type nodes []node

func (a nodes) Len() int           { return len(a) }
func (a nodes) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a nodes) Less(i, j int) bool { return a[i].r > a[j].r }

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	nn := 0
	fmt.Fscanf(in, "%d\n", &nn)
	for ii := 0; ii < nn; ii++ {
		s := ""
		fmt.Fscanf(in, "%s\n", &s)
		if len(s) == 1 {
			fmt.Fprintf(out, "%s\n", s)
			continue
		}
		l := 0
		r := len(s) - 1

		for l < r {
			if s[l] == s[r] {
				l++
				r--
			} else {
				break
			}
		}
		if l >= r {
			fmt.Fprintf(out, "%s\n", s)
			continue
		}
		fmt.Fprintf(out, "%s\n", s[:l]+getMax(s[l:r+1])+s[r+1:])
	}
	return
}

func getMax(s string) string {
	l, r := getLeft(s), getRight(s)
	if len(l) > len(r) {
		return l
	}
	return r
}

func getLeft(s string) string {
	for i := len(s) - 1; i >= 0; i-- {
		if isP(s[:i+1]) {
			return s[:i+1]
		}
	}
	return s[:1]
}

func isP(s string) bool {
	for i := 0; i < len(s); i++ {
		j := len(s) - i - 1
		if s[i] != s[j] {
			return false
		}
	}
	return true
}

func getRight(s string) string {
	for i := 0; i < len(s); i++ {
		if isP(s[i:]) {
			return s[i:]
		}
	}
	return s[len(s)-1:]
}

func findPattern(a []int, m int) int {
	sort.Ints(a)
	for i := 1; i <= len(a)/2; i++ {
		if len(a)%i == 0 {
			if work(a, i, m) {
				return len(a) / i
			}
		}
	}
	return 1
}

func work(a []int, l int, m int) bool {
	//fmt.Println(a, l, m)
	n := len(a)
	numOfSeg := n / l
	for i := 1; i < numOfSeg; i++ {
		if a[i*l]-a[(i-1)*l] != (a[0] + m - a[(numOfSeg-1)*l]) {
			//fmt.Println(a, l, "debug")
			return false
		}
	}
	for j := 1; j < l; j++ {
		for i := 1; i < n/l; i++ {
			if a[i*l+j]-a[i*l+j-1] != a[j]-a[j-1] {
				//fmt.Println(a, l, "debug2")
				return false
			}
		}
	}
	return true
}

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

package main

import (
	"bufio"
	"fmt"
	"io"
	"math/rand"
	"os"
	"sort"
	"strconv"
)

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

type CartesianNode struct {
	l *CartesianNode
	r *CartesianNode
	x int
	y int
}

func (node *CartesianNode) Propagate() {
}

func (node *CartesianNode) Update() {

}

func NewCartesianNode(x int) *CartesianNode {
	node := &CartesianNode{}
	node.x = x
	node.y = rand.Intn(1000500)
	return node
}

type CartesianTree struct {
	root *CartesianNode
}

func (t *CartesianTree) Split(node *CartesianNode, x int) (*CartesianNode, *CartesianNode) {
	if node == nil {
		return nil, nil
	}
	node.Propagate()
	if node.x < x {
		lt, rt := t.Split(node.r, x)
		node.r = lt
		node.Update()
		return node, rt
	} else {
		lt, rt := t.Split(node.l, x)
		node.l = rt
		node.Update()
		return lt, node
	}
}

func (t *CartesianTree) Merge(lt *CartesianNode, rt *CartesianNode) *CartesianNode {
	if lt == nil {
		return rt
	}
	if rt == nil {
		return lt
	}
	if lt.y > rt.y {
		lt.Propagate()
		lt.r = t.Merge(lt.r, rt)
		lt.Update()
		return lt
	} else {
		rt.Propagate()
		rt.l = t.Merge(lt, rt.l)
		rt.Update()
		return rt
	}
}

func (t *CartesianTree) Min(l, r int) int {
	lt, rt := t.Split(t.root, l)
	mid, rt := t.Split(rt, r+1)

	node := mid
	for node != nil && node.l != nil {
		node = node.l
	}
	var res int
	if node == nil {
		res = -1
	} else {
		res = node.x
	}

	t.root = t.Merge(lt, t.Merge(mid, rt))
	return res
}

func (t *CartesianTree) Max(l, r int) int {
	lt, rt := t.Split(t.root, l)
	mid, rt := t.Split(rt, r+1)

	node := mid
	for node != nil && node.r != nil {
		node = node.r
	}
	var res int
	if node == nil {
		res = -1
	} else {
		res = node.x
	}

	t.root = t.Merge(lt, t.Merge(mid, rt))
	return res
}

func (t *CartesianTree) Add(x int) {
	lt, rt := t.Split(t.root, x)
	xmid := NewCartesianNode(x)
	t.root = t.Merge(t.Merge(lt, xmid), rt)
}

func (t *CartesianTree) Delete(x int) {
	lt, rt := t.Split(t.root, x)
	_, rt = t.Split(rt, x+1)
	t.root = t.Merge(lt, rt)
}

func NewCartesianTree() *CartesianTree {
	return &CartesianTree{}
}

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

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

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)

	T := NextInt()

	s := make([]byte, 400001)
	p := make([]int, 400001)
	events := make([][3]int, 800002)
	left := make([]int, 200001)
	right := make([]int, 200001)
	for t := 0; t < T; t++ {
		os := NextBytes()
		n := len(os)
		// stderr("here")
		for i := 0; i < 2*n+1; i++ {
			if (i & 1) == 0 {
				s[i] = '#'
			} else {
				s[i] = os[i>>1]
			}
		}
		// stderr("new s", string(s[:2*n+1]))
		c, r := 0, -1
		var rad int
		for i := 0; i < 2*n+1; i++ {
			if i <= r {
				rad = min(p[2*c-i], r-i)
			} else {
				rad = 0
			}
			for i+rad < 2*n+1 && i-rad >= 0 && s[i-rad] == s[i+rad] {
				rad++
			}
			p[i] = rad
			if i+rad-1 > r {
				c = i
				r = i + rad - 1
			}
		}
		// stderr("p", p[:2*n+1])
		// p[2*n] = 0

		for i := 0; i < 2*n+1; i++ {
			events[i*2][0] = i
			events[i*2][1] = 1
			events[i*2][2] = i
			events[i*2+1][0] = i + p[i]
			events[i*2+1][1] = -1
			events[i*2+1][2] = i
		}
		elen := (2*n + 1) * 2

		sort.Slice(events[:elen], func(i, j int) bool {
			return events[i][0] < events[j][0] || events[i][0] == events[j][0] && events[i][1] < events[j][1]
		})

		// stderr("sorted events")
		tree := NewCartesianTree()
		for i, j := 0, 0; i < 2*n+1; i++ {
			for j < elen && events[j][0] <= i {
				if events[j][1] == 1 {
					// stderr("applying event", events[j])
					tree.Add(events[j][2])
				} else if events[j][1] == -1 {
					// stderr("applying event", events[j])
					tree.Delete(events[j][2])
				}
				j++
			}

			if i%2 == 1 {
				minc := tree.Min(n, 2*n)
				// stderr("minc", i, minc)
				if minc == -1 {
					left[i>>1] = 0
					continue
				}
				halflen := i - minc
				halflen++
				left[i>>1] = halflen
			}
		}

		for i := 0; i < 2*n+1; i++ {
			events[i*2][0] = i
			events[i*2][1] = 1
			events[i*2][2] = i
			events[i*2+1][0] = i - p[i]
			events[i*2+1][1] = -1
			events[i*2+1][2] = i
		}

		sort.Slice(events[:elen], func(i, j int) bool {
			return events[i][0] > events[j][0] || events[i][0] == events[j][0] && events[i][1] < events[j][1]
		})

		tree = NewCartesianTree()
		for i, j := 2*n, 0; i >= 0; i-- {
			for j < elen && events[j][0] >= i {
				if events[j][1] == 1 {
					tree.Add(events[j][2])
				} else if events[j][1] == -1 {
					tree.Delete(events[j][2])
				}
				j++
			}

			if i%2 == 1 {
				maxc := tree.Max(0, n)
				if maxc == -1 {
					right[i>>1] = 0
					continue
				}
				// stderr("maxc", i, maxc)
				halflen := (maxc - i)
				halflen++
				right[i>>1] = halflen
			}
		}
		// stderr("left", left[:n])
		// stderr("right", right[:n])

		var result, rl, rr int
		if right[0] > left[n-1] {
			result = right[0]
			rl = right[0]
			rr = 0
		} else {
			result = left[n-1]
			rr = left[n-1]
			rl = 0
		}
		for i := 0; i < n-i-1 && os[i] == os[n-i-1]; i++ {
			l := (i + 1) * 2
			if i+1 < n {
				l += right[i+1]
			}
			// stderr("L", i, l)
			if l > result {
				result = l
				rl = i + 1
				rr = i + 1
				if i+1 < n {
					rl += right[i+1]
				}
			}
			r := (i + 1) * 2
			if n-i-2 >= 0 {
				r += left[n-i-2]
			}
			if r > result {
				result = r
				rl = i + 1
				rr = i + 1
				if n-i-2 >= 0 {
					rr += left[n-i-2]
				}
			}
		}
		// stderr("result", result, rl, rr)
		fmt.Fprint(out, string(os[:rl]))
		if n-rr < n {
			fmt.Fprint(out, string(os[n-rr:n]))
		}
		fmt.Fprintln(out)
	}

}

package main

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

func isPalindrome(str string, s, e int) bool {
	if s > e {
		return true
	}

	for s < e {
		if str[s] != str[e] {
			return false
		}
		s++
		e--
	}

	return true
}

func check1(str string, s, e int) int {
	for i := e; i >= s+1; i-- {
		if str[s] == str[i] {
			if isPalindrome(str, s+1, i-1) {
				return i
			}
		}
	}

	return s
}

func check2(str string, s, e int) int {
	for i := s; i < e; i++ {
		if str[e] == str[i] {
			if isPalindrome(str, i+1, e-1) {
				return i
			}
		}
	}

	return e
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	bf := make([]byte, 1024*1024)
	sc.Buffer(bf, 10*1024*1024)
	sc.Split(bufio.ScanWords)

	in := func() int {
		sc.Scan()
		i, _ := strconv.Atoi(sc.Text())
		return i
	}

	ins := func() string {
		sc.Scan()
		return sc.Text()
	}

	for t := in(); t > 0; t-- {
		str := ins()

		n := len(str)

		if n == 1 {
			fmt.Println(str)
			continue
		}

		s := -1
		e := n

		for s < e && str[s+1] == str[e-1] {
			s++
			e--
		}

		if e-s > 2 {
			e1 := check1(str, s+1, e-1)
			s1 := check2(str, s+1, e-1)

			if e1-s > e-s1 {
				s = e1
			} else {
				e = s1
			}
		}

		for i := 0; i < n; i++ {
			if i <= s || i >= e {
				fmt.Print(string(str[i]))
			}
		}

		fmt.Println()

	}

}

package main

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

const (
	maxn = int(1e5 + 50)
	mod  = int(1e9 + 7)
	eps  = 1e-8
	inf  = int(0x3f3f3f3f)
)

func isPar(s string) bool {
	for i, j := 0, len(s) - 1; i < j; i, j = i + 1, j - 1 {
		if s[i] != s[j] {
			return false
		}
	}
	return true
}

func findPre(s string) int {
	res := 0
	for i := range s {
		if isPar(s[:i+1]) {
			res = max(res, i + 1)
		}
	}
	return res
}

func findLas(s string) int {
	res := 0
	for i:= range s {
		if isPar(s[i:]) {
			//printString(s[i:])
			res = max(res, len(s) - i)
		}
	}
	return res
}

func findBoth(res1, res2 *string, s string) (int, int) {
	var tmp []rune
	i, j := 0, len(s) - 1
	for ; i <= j; i, j = i + 1, j - 1 {
		if s[i] != s[j] {
			*res1 += string(tmp)
			reverse(&tmp, 0, len(tmp))
			*res2 += string(tmp)
			return i - 1, j + 1
		} else {
			tmp = append(tmp, rune(s[i]))
		}
	}
	return i - 1, j + 1
}

func main() {
	var T int
	scanInt(&T)
	for kase := 1; kase <= T; kase++ {
		s := scanString()
		res := 0
		ress := ""
		{
			resstring1 := ""
			resstring2 := ""
			resstring3 := ""
			realres := 0
			res1, res2 := findBoth(&resstring1, &resstring2, s)
			if res1 + 1 >= res2 - 1 {
				printString(s)
				continue
			}
			if res1 + 1 < res2 - 1 {
				tt1 := findPre(s[res1+1:res2])
				tt2 := findLas(s[res1+1:res2])
				realres = res1 + 1 + len(s) - res2 + max(tt1, tt2)
				if tt1 < tt2 {
					resstring3 = s[res2-tt2:res2]
				} else {
					resstring3 = s[res1+1:res1+tt1+1]
				}
			}
			if res < realres {
				res = realres
				ress = resstring1 + resstring3 + resstring2
			}
		}
		{
			realres := findPre(s)
			resstring := s[:realres]
			if res < realres {
				res = realres
				ress = resstring
			}
		}
		{
			realres := findLas(s)
			resstring := s[len(s)-realres:]
			if res < realres {
				res = realres
				ress = resstring
			}
		}
		printString(ress)
		//{
		//	res2 :=
		//}
	}
	close(channelType)
	oWg.Wait()
	out.Flush()
}

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

var channelType chan string
var in *bufio.Scanner
var out = bufio.NewWriter(os.Stdout)
var oWg *sync.WaitGroup

// string and slice are the return value
func init() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)
	channelType = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)
	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

		for line := range channelType {
			writer.WriteString(line + "\n")
		}
	}()
}
func scanString() string { in.Scan(); return in.Text() }
func scanInt(a *int)     { *a, _ = strconv.Atoi(scanString()) }
func scanInts(a ...*int) {
	for i := range a {
		*a[i], _ = strconv.Atoi(scanString())
	}
}
func scanInt64(a *int64) { *a, _ = strconv.ParseInt(scanString(), 10, 64) }
func scanInt64s(a ...*int64) {
	for i := range a {
		*a[i], _ = strconv.ParseInt(scanString(), 10, 64)
	}
}
func scanStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = scanString()
	}
	return s
}
func scanIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		scanInt(&arr[i])
	}
	return arr
}
func scanInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		scanInt64(&arr[i])
	}
	return arr
}
func printlnInts(args ...int) {
	for _, x := range args {
		fmt.Fprint(out, x, " ")
	}
	fmt.Fprintln(out)
}
func printlnInt64s(args ...int64) {
	for _, x := range args {
		fmt.Fprint(out, x, " ")
	}
	fmt.Fprintln(out)
}
func printIntSlice(a []int, flag bool) {
	for _, x := range a {
		fmt.Fprint(out, x, " ")
	}
	if flag { fmt.Fprintln(out) }
}
func printInt64Slice(a []int64, flag bool) {
	for _, x := range a {
		fmt.Fprint(out, x, " ")
	}
	if flag { fmt.Fprintln(out) }
}
func printRuneSlice(a []rune, flag bool) {
	for _, x := range a {
		fmt.Fprintf(out, "%c", x)
	}
	if flag { fmt.Fprintln(out) }
}
func putchar(a ...rune) {
	for _, x := range a {
		fmt.Fprintf(out, "%c", x)
	}
}
func printString(s string) { fmt.Fprintln(out, s) }

/*********************** Utils ***********************/

func stringEquivalent(v interface{}) string { return fmt.Sprintf("%v", v) }
func spaceSeperatedStringFromArray(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func spaceSeperatedStringFromArray64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func minMaxFromArray(args ...int64) (int64, int64) {
	minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64)
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func minElementFromArray(args ...int64) int64 { mn, _ := minMaxFromArray(args...); return mn }
func maxElementFromArray(args ...int64) int64 { _, mx := minMaxFromArray(args...); return mx }
func lcmCalculation(a, b int64) int64         { return a / gcdCalculation(a, b) * b }
func gcdCalculation(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return gcdCalculation(b%a, a)
}
func sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func absoluteValue(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}
func min(args ...int) int { mn, _ := minMaxFinder(args...); return mn }
func max(args ...int) int { _, mx := minMaxFinder(args...); return mx }
func minMaxFinder(args ...int) (int, int) {
	minVal, maxVal := int(math.MaxInt32), int(math.MinInt32)
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func same(x, y double) bool { return math.Abs(float64(x-y)) < eps }
func popcount(x int) (res int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			res++
		}
	}
	return
}
func qp(a, n int64) (res int64) {
	for ; n > 0; n >>= 1 {
		if (n & 1) == 1 {
			res = res * a % int64(mod)
		}
		a = a * a % int64(mod)
	}
	return
}
func divUp(a, b int64) int64 {
	if a % b == 0 { return a / b } else { return a / b + 1 }
}
// [l, r)
func reverse(a *[]rune, l, r int) {
	for i, j := l, r - 1; i < j; i, j = i + 1, j - 1 {
		(*a)[i], (*a)[j] = (*a)[j], (*a)[i]
	}
}

/*********************** Structs ***********************/
type pair struct{ X, Y int }
type double float64
type pairSlice []pair

func (p pairSlice) Len() int { return len(p) }
func (p pairSlice) Less(i, j int) bool {
	if p[i].X != p[j].X {
		return p[i].X < p[j].X
	} else {
		return p[i].Y < p[j].Y
	}
}
func (p pairSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1326D2(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}
	var maxLen []int
	manacher := func(origin string) {
		n := len(origin)
		s := make([]byte, 2*n+3)
		s[0] = '^'
		for i := range origin {
			s[2*i+1] = '#'
			s[2*i+2] = origin[i]
		}
		s[2*n+1] = '#'
		s[2*n+2] = '$'
		maxLen = make([]int, 2*n+3)
		var mid, right int
		for i := 1; i < 2*n+2; i++ {
			if i < right {
				maxLen[i] = min(maxLen[2*mid-i], right-i)
			} else {
				maxLen[i] = 1
			}
			for s[i+maxLen[i]] == s[i-maxLen[i]] {
				maxLen[i]++
			}
			if right < i+maxLen[i] {
				mid = i
				right = i + maxLen[i]
			}
		}
	}
	q := func(l, r int) bool { return maxLen[l+r+2] >= r-l+1 }

	var t int
	var s string
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &s)
		i, j := 0, len(s)-1
		for i < j && s[i] == s[j] {
			i++
			j--
		}
		if i >= j {
			Fprintln(out, s)
			continue
		}
		l, r := i, j
		manacher(s)
		for ; r > i && !q(i, r); r-- {
		}
		for ; l < j && !q(l, j); l++ {
		}
		if r-i > j-l {
			Fprintln(out, s[:r+1]+s[j+1:])
		} else {
			Fprintln(out, s[:i]+s[l:])
		}
	}
}

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

package main

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

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

func readNum(scanner *bufio.Scanner) (a int) {
	scanner.Scan()
	readInt(scanner.Bytes(), 0, &a)
	return
}

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

func readNNums(scanner *bufio.Scanner, n int) []int {
	res := make([]int, n)
	x := 0
	scanner.Scan()
	for i := 0; i < n; i++ {
		for x < len(scanner.Bytes()) && scanner.Bytes()[x] == ' ' {
			x++
		}
		x = readInt(scanner.Bytes(), x, &res[i])
	}
	return res
}

func fillNNums(scanner *bufio.Scanner, n int, res []int) {
	x := 0
	scanner.Scan()
	for i := 0; i < n; i++ {
		for x < len(scanner.Bytes()) && scanner.Bytes()[x] == ' ' {
			x++
		}
		x = readInt(scanner.Bytes(), x, &res[i])
	}
}

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

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

	return i
}

func readInt64(bytes []byte, from int, val *int64) int {
	i := from
	var tmp int64
	for i < len(bytes) && bytes[i] != ' ' {
		tmp = tmp*10 + int64(bytes[i]-'0')
		i++
	}
	*val = tmp
	return i
}

func readNInt64Nums(scanner *bufio.Scanner, n int) []int64 {
	res := make([]int64, n)
	x := -1
	scanner.Scan()
	for i := 0; i < n; i++ {
		x = readInt64(scanner.Bytes(), x+1, &res[i])
	}
	return res
}

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

	line, _ := reader.ReadString('\n')

	tc, _ := strconv.Atoi(strings.TrimSpace(line))

	for tc > 0 {
		tc--
		s, _ := reader.ReadString('\n')
		if len(s) == 0 {
			fmt.Println("no input read")
		} else {
			fmt.Println(solve(strings.TrimSpace(s)))
		}
	}
}

func solve(s string) string {
	var l, r int = 0, len(s) - 1
	for l <= r && s[l] == s[r] {
		l++
		r--
	}
	if l > r {
		return s
	}
	// l < r
	x := s[l : r+1]

	a := findLongestPrefixPalindrome(x)
	b := findLongestPrefixPalindrome(reverse(x))

	if len(a) < len(b) {
		a, b = b, a
	}

	return s[:l] + a + s[r+1:]
}

func findLongestPrefixPalindrome(s string) string {
	n := len(s)

	check := func(l int) bool {
		if l > n {
			return false
		}
		i, j := 0, l-1
		for i <= j && s[i] == s[j] {
			i++
			j--
		}
		return i > j
	}

	l, r := 1, n+1
	for l < r {
		mid := (l + r) / 2
		if check(mid) {
			l = mid + 1
		} else {
			r = mid
		}
	}

	return s[:r-1]
}

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


package main

import (
	"strings"
	"fmt"
	"strconv"
	"errors"
	"io"
	"unicode/utf8"
	"bytes"
	"os"
)

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

func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("error: ", r)
		}
	}()
	n := nextInt()
	times := make([]int, n)
	for i := 0; i < n; i++ {
		times[i] = nextInt()
	}
	if len(times) == 1 {
		printf("1 0\n")
		return
	}
	ap, bp, at, bt := 0, n - 1, times[0], times[len(times) - 1]
	for ap < bp {
		if at == 0 {
			ap++
			at = times[ap]
		}
		if bt == 0 {
			if bp > ap + 1 {
				bp--
				bt = times[bp]
			} else {
				bt = 100000
				continue
			}
		}
		dt := min(at, bt)
		at, bt = at - dt, bt - dt
	}
	printf("%d %d\n", ap, n - bp)
}

var lineScanner *Scanner
var wordScanner *Scanner

func init() {
	lineScanner = NewScanner(os.Stdin)
	wordScanner = NewScanner(strings.NewReader(""))
	wordScanner.Split(ScanWords)
}

func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

func nextWord() string {
	for !wordScanner.Scan() {
		if err := wordScanner.Err(); err != nil {
			panic(err)
		}
		line, err := nextLine()
		if err != nil {
			return ""
		}
		wordScanner = NewScanner(strings.NewReader(line))
		wordScanner.Split(ScanWords)
	}
	return wordScanner.Text()
}

func nextInt() int {
	res, err := strconv.Atoi(nextWord())
	if err != nil {
		panic(err)
	}
	return res
}

func nextInt64() int64 {
	res, err := strconv.ParseInt(nextWord(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}

func nextFloat64() float64 {
	res, err := strconv.ParseFloat(nextWord(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

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

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

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

const (
// MaxScanTokenSize is the maximum size used to buffer a token
// unless the user provides an explicit buffer with Scan.Buffer.
// The actual maximum token size may be smaller as the buffer
// may need to include, for instance, a newline.
	MaxScanTokenSize = 2 * 1024 * 2014

	startBufSize = 4096 // Size of initial allocation for buffer.
)

// NewScanner returns a new Scanner to read from r.
// The split function defaults to ScanLines.
func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        ScanLines,
		maxTokenSize: MaxScanTokenSize,
	}
}

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

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

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

// ErrFinalToken is a special sentinel error value. It is intended to be
// returned by a Split function to indicate that the token being delivered
// with the error is the last token and scanning should stop after this one.
// After ErrFinalToken is received by Scan, scanning stops with no error.
// The value is useful to stop processing early or when it is necessary to
// deliver a final empty token. One could achieve the same behavior
// with a custom error value but providing one here is tidier.
// See the emptyFinalToken example for a use of this value.
var ErrFinalToken = errors.New("final token")

// Scan advances the Scanner to the next token, which will then be
// available through the Bytes or Text method. It returns false when the
// scan stops, either by reaching the end of the input or an error.
// After Scan returns false, the Err method will return any error that
// occurred during scanning, except that if it was io.EOF, Err
// will return nil.
// Scan panics if the split function returns 100 empty tokens without
// advancing the input. This is a common error mode for scanners.
func (s *Scanner) Scan() bool {
	if s.done {
		return false
	}
	s.scanCalled = true
	// Loop until we have a token.
	for {
		// See if we can get a token with what we already have.
		// If we've run out of data but have an error, give the split function
		// a chance to recover any remaining, possibly empty token.
		if s.end > s.start || s.err != nil {
			advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
			if err != nil {
				if err == ErrFinalToken {
					s.token = token
					s.done = true
					return true
				}
				s.setErr(err)
				return false
			}
			if !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				if s.err == nil || advance > 0 {
					s.empties = 0
				} else {
					// Returning tokens not advancing input at EOF.
					s.empties++
					if s.empties > 100 {
						panic("bufio.Scan: 100 empty tokens without progressing")
					}
				}
				return true
			}
		}
		// We cannot generate a token with what we are holding.
		// If we've already hit EOF or an I/O error, we are done.
		if s.err != nil {
			// Shut it down.
			s.start = 0
			s.end = 0
			return false
		}
		// Must read more data.
		// First, shift data to beginning of buffer if there's lots of empty space
		// or space is needed.
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf) / 2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		// Is the buffer full? If so, resize.
		if s.end == len(s.buf) {
			// Guarantee no overflow in the multiplication below.
			const maxInt = int(^uint(0) >> 1)
			if len(s.buf) >= s.maxTokenSize || len(s.buf) > maxInt / 2 {
				s.setErr(ErrTooLong)
				return false
			}
			newSize := len(s.buf) * 2
			if newSize == 0 {
				newSize = startBufSize
			}
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		// Finally we can read some input. Make sure we don't get stuck with
		// a misbehaving Reader. Officially we don't need to do this, but let's
		// be extra careful: Scanner is for safe, simple jobs.
		for loop := 0;; {
			n, err := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if err != nil {
				s.setErr(err)
				break
			}
			if n > 0 {
				s.empties = 0
				break
			}
			loop++
			if loop > 10 {
				s.setErr(io.ErrNoProgress)
				break
			}
		}
	}
}

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

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

// Buffer sets the initial buffer to use when scanning and the maximum
// size of buffer that may be allocated during scanning. The maximum
// token size is the larger of max and cap(buf). If max <= cap(buf),
// Scan will use this buffer only and do no allocation.
//
// By default, Scan uses an internal buffer and sets the
// maximum token size to MaxScanTokenSize.
//
// Buffer panics if it is called after scanning has started.
func (s *Scanner) Buffer(buf []byte, max int) {
	if s.scanCalled {
		panic("Buffer called after Scan")
	}
	s.buf = buf[0:cap(buf)]
	s.maxTokenSize = max
}

// Split sets the split function for the Scanner.
// The default split function is ScanLines.
//
// Split panics if it is called after scanning has started.
func (s *Scanner) Split(split SplitFunc) {
	if s.scanCalled {
		panic("Split called after Scan")
	}
	s.split = split
}

// Split functions

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

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

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

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

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

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

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

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

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

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

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

package main

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

var cs map[int]int = make(map[int]int)

func Init() {}
func Solve(io *FastIO) {
	n := io.NextInt()
	if n == 1 {
		io.Println(1, 0)
		return
	}
	a := io.NextIntArray(n)
	sa, sb := a[0], a[n-1]
	ia, ib := 1, n-2
	for ia < ib+1 {
		if sa <= sb {
			sa += a[ia]
			ia += 1
		}
		if sa > sb {
			sb += a[ib]
			ib -= 1
		}
		//io.Println(sa, sb)
	}
	io.Println(ia, n-ia)
}

type FastIO struct {
	//by megaspazz
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}
func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = res*10 + int(c-'0')
		c = io.NextChar()
	}
	return res * sgn
}
func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = int64(-1)
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = res*10 + int64(c-'0')
		c = io.NextChar()
	}
	return res * sgn
}
func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}
func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size+offset)
	for i := 0; i < size; i++ {
		arr[i+offset] = io.NextInt()
	}
	return arr
}
func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}
func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size+offset)
	for i := 0; i < size; i++ {
		arr[i+offset] = io.NextLong()
	}
	return arr
}
func (io *FastIO) NextString() string {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}
func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}
func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}
func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}
func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}
func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}
func IsLineBreakChar(c byte) bool {
	switch c {
	case 0, '\n', '\r':
		return true
	default:
		return false
	}
}
func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}

package main

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

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	choco := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d ", &choco[i])
	}
	ca, cb, ta, tb := 0, n-1, 0, 0
	for {
		if ca > cb {
			break
		}
		if ta <= tb {
			ca, ta = ca+1, ta+choco[ca]
		} else {
			cb, tb = cb-1, tb+choco[cb]
		}
	}
	fmt.Printf("%d %d", ca, n-ca)
}

package main

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

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

	n := readNum(reader)

	bars := readNNums(reader, n)

	a, b := solve(n, bars)

	fmt.Printf("%d %d\n", a, b)
}

func solve(n int, bars []int) (int, int) {
	if n == 1 {
		return 1, 0
	}
	if n == 2 {
		return 1, 1
	}
	var i, j = 0, n - 1
	var a, b = bars[i], bars[j]
	i++
	j--

	for i <= j {
		if i == j {
			if a <= b {
				i++
			} else {
				j--
			}
			continue
		}
		if a < b {
			a += bars[i]
			i++
		} else if a > b {
			b += bars[j]
			j--
		} else {
			a += bars[i]
			i++
			if i < j {
				b += bars[j]
				j--
			}
		}
	}

	return i, n - i
}

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

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

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

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

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

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

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

	return i
}

package main

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

func solve() {
	n := readInt()
	t := make([]int, n)

	alices := 0
	bobs := 0

	for i, _ := range t {
		t[i] = readInt()
	}

	ap := 0
	bp := len(t) - 1

	anext := 0
	bnext := 0
	curtime := 0

	for barsleft := n; barsleft > 0; {
		if curtime == anext {
			alices++
			barsleft--
			if barsleft == 0 {
				break
			}
			anext = curtime + t[ap]
			ap++
		}
		if curtime == bnext {
			bobs++
			barsleft--
			if barsleft == 0 {
				break
			}
			bnext = curtime + t[bp]
			bp--
		}
		curtime = min(anext, bnext)
	}
	fmt.Println(alices, bobs)
}

func min(i, j int) int {
	if i < j {
		return i
	}
	return j
}

var scanner *bufio.Scanner

func main() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

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

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

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

//http://codeforces.com/contest/6/problem/C
//C. Alice, Bob and Chocolate

package main

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

func main() {
	var (
		i, j, sa, sb, nbars int32 // small,big
		bars                []int32
	)

	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &nbars)
	bars = make([]int32, nbars, nbars)
	for i = 0; i < nbars; i++ {
		fmt.Fscan(in, &bars[i])
	}
	sa, sb = 0, 0
	i, j = -1, nbars
	for {
		//		fmt.Println("i,j,sa,sb=", i, j, sa, sb)
		if sa <= sb {
			if i+1 >= j {
				break
			}
			i++
			sa += bars[i]
		} else {
			if i >= j-1 {
				break
			}
			j--
			sb += bars[j]
		}
	}
	fmt.Println(i+1, nbars-(i+1))
}

// 6C
package main

import (
	"fmt"
)

func main() {
	s, k, n, i, u, v := 0, 0, 0, 0, 0, 0
	var a [200000]int
	fmt.Scan(&n)
	for i = 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	k = n - 1
	for s <= k {
		if v < u {
			v += a[k]
			k--
		} else {
			u += a[s]
			s++
		}
	}
	fmt.Print(s, n-s)
}

package main

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

var cs map[int]int = make(map[int]int)

func Init() {}
func Solve(io *FastIO) {
	n := io.NextInt()
	if n == 1 {
		io.Println(1, 0)
		return
	}
	a := io.NextIntArray(n)
	sa, sb := a[0], a[n-1]
	ia, ib := 1, n-2
	for ia < ib+1 {
		if sa <= sb {
			sa += a[ia]
			ia += 1
		}
		if sa >= sb {
			sb += a[ib]
			ib -= 1
		}
		//io.Println(sa, sb)
	}
	io.Println(ia, n-ia)
}

type FastIO struct {
	//by megaspazz
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}
func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = res*10 + int(c-'0')
		c = io.NextChar()
	}
	return res * sgn
}
func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = int64(-1)
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = res*10 + int64(c-'0')
		c = io.NextChar()
	}
	return res * sgn
}
func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}
func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size+offset)
	for i := 0; i < size; i++ {
		arr[i+offset] = io.NextInt()
	}
	return arr
}
func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}
func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size+offset)
	for i := 0; i < size; i++ {
		arr[i+offset] = io.NextLong()
	}
	return arr
}
func (io *FastIO) NextString() string {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}
func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}
func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}
func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}
func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}
func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}
func IsLineBreakChar(c byte) bool {
	switch c {
	case 0, '\n', '\r':
		return true
	default:
		return false
	}
}
func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}

package main

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

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

	n := readNum(reader)

	bars := readNNums(reader, n)

	a, b := solve(n, bars)

	fmt.Printf("%d %d\n", a, b)
}

func solve(n int, bars []int) (int, int) {
	var a, b int
	var i, j = 0, n - 1

	for i < j {
		if a < b {
			a += bars[i]
			i++
		} else if a > b {
			b += bars[j]
			j--
		} else {
			a += bars[i]
			i++
			if i < j {
				b += bars[j]
				j--
			}
		}
	}

	return i, n - i
}

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

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

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

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

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

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

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

	return i
}

package main

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

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

	n := readNum(reader)

	bars := readNNums(reader, n)

	a, b := solve(n, bars)

	fmt.Printf("%d %d\n", a, b)
}

func solve(n int, bars []int) (int, int) {
	if n == 1 {
		return 1, 0
	}
	var a, b int
	var i, j = 0, n - 1

	for i < j {
		if a < b {
			a += bars[i]
			i++
		} else if a > b {
			b += bars[j]
			j--
		} else {
			a += bars[i]
			i++
			if i < j {
				b += bars[j]
				j--
			}
		}
	}

	return i, n - i
}

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

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

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

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

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

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

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

	return i
}

package main

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

func solve() {
	n := readInt()
	t := make([]int, n)

	alices := 0
	bobs := 0

	for i, _ := range t {
		t[i] = readInt()
	}

	ap := 0
	bp := len(t) - 1

	atime := 0
	btime := 0

	for alices+bobs != n {
		if atime == btime {
			alices++
			atime = t[ap]
			if alices+bobs != n {
				bobs++
				btime = t[bp]
			}
			continue
		} else if atime < btime {
			// Alice consumes one
			alices++
			btime -= atime
			ap++
			atime = t[ap]
		} else {
			// Bob consumes one
			bobs++
			atime -= btime
			bp--
			btime = t[bp]
		}
	}
	fmt.Println(alices, bobs)
}

var scanner *bufio.Scanner

func main() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

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

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

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

package main

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

func solve() {
	n := readInt()
	t := make([]int, n)

	alices := 0
	bobs := 0

	for i, _ := range t {
		t[i] = readInt()
	}

	ap := -1
	bp := len(t)

	atime := 0
	btime := 0

	for alices+bobs != n {
		if atime == 0 {
			alices++
			ap++
		}
		if btime == 0 && alices+bobs != n {
			bobs++
			bp--
		}
		if alices+bobs == n {
			break
		}
		atime = t[ap] - min(t[ap], t[bp])
		btime = t[bp] - min(t[ap], t[bp])
	}
	fmt.Println(alices, bobs)
}

func min(i, j int) int {
	if i < j {
		return i
	}
	return j
}

var scanner *bufio.Scanner

func main() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

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

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

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

package main

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

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

func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("error: ", r)
		}
	}()
	n := nextInt()
	times := make([]int, n)
	for i := 0; i < n; i++ {
		times[i] = nextInt()
	}
	if len(times) == 1 {
		printf("1 0\n")
		return
	}
	ap, bp, at, bt := 0, n - 1, times[0], times[len(times) - 1]
	for ap < bp {
		if at == 0 {
			ap++
			at = times[ap]
		}
		if bt == 0 {
			if bp > ap + 1 {
				bp--
				bt = times[bp]
			} else {
				bt = 100000
				continue
			}
		}
		dt := min(at, bt)
		at, bt = at - dt, bt - dt
	}
	printf("%d %d\n", ap, n - bp)
}

var lineScanner *bufio.Scanner
var wordScanner *bufio.Scanner

func init() {
	lineScanner = bufio.NewScanner(os.Stdin)
	wordScanner = bufio.NewScanner(strings.NewReader(""))
	wordScanner.Split(bufio.ScanWords)
}
func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

func nextWord() string {
	for !wordScanner.Scan() {
		if err := wordScanner.Err(); err != nil {
			panic(err)
		}
		line, err := nextLine()
		if err != nil {
			return ""
		}
		wordScanner = bufio.NewScanner(strings.NewReader(line))
		wordScanner.Split(bufio.ScanWords)
	}
	return wordScanner.Text()
}

func nextInt() int {
	res, err := strconv.Atoi(nextWord())
	if err != nil {
		panic(err)
	}
	return res
}

func nextInt64() int64 {
	res, err := strconv.ParseInt(nextWord(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}

func nextFloat64() float64 {
	res, err := strconv.ParseFloat(nextWord(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

package main

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

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

func main() {
	n := nextInt()
	times := make([]int, n)
	for i := 0; i < n; i++ {
		times[i] = nextInt()
	}
	ap, bp, at, bt := 0, n - 1, times[0], times[len(times) - 1]
	for ap < bp {
		if at == 0 {
			ap++
			at = times[ap]
		}
		if bt == 0 {
			if bp > ap + 1 {
				bp--
				bt = times[bp]
			} else {
				bt = 100000
				continue
			}
		}
		dt := min(at, bt)
		at, bt = at - dt, bt - dt
	}
	printf("%d %d\n", ap, n - bp)
}

var lineScanner *bufio.Scanner
var wordScanner *bufio.Scanner

func init() {
	lineScanner = bufio.NewScanner(os.Stdin)
	wordScanner = bufio.NewScanner(strings.NewReader(""))
	wordScanner.Split(bufio.ScanWords)
}
func printf(format string, a ...interface{}) {
	fmt.Printf(format, a...)
}
func nextLine() (string, error) {
	if !lineScanner.Scan() {
		if err := lineScanner.Err(); err != nil {
			panic(err)
		}
		return "", errors.New("nextLine: EOF reached")
	}
	return lineScanner.Text(), nil
}

func nextWord() string {
	for !wordScanner.Scan() {
		if err := wordScanner.Err(); err != nil {
			panic(err)
		}
		line, err := nextLine()
		if err != nil {
			return ""
		}
		wordScanner = bufio.NewScanner(strings.NewReader(line))
		wordScanner.Split(bufio.ScanWords)
	}
	return wordScanner.Text()
}

func nextInt() int {
	res, err := strconv.Atoi(nextWord())
	if err != nil {
		panic(err)
	}
	return res
}

func nextInt64() int64 {
	res, err := strconv.ParseInt(nextWord(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}

func nextFloat64() float64 {
	res, err := strconv.ParseFloat(nextWord(), 64)
	if err != nil {
		panic(err)
	}
	return res
}