Given a sequence $$$a_1, a_2, \ldots, a_n$$$, find the minimum number of elements to remove from the sequence such that after the removal, the sum of every $$$2$$$ consecutive elements is even.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2,\dots,a_n$$$ ($$$1\leq a_i\leq10^9$$$) — elements of the sequence. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer — the minimum number of elements to remove from the sequence such that the sum of every $$$2$$$ consecutive elements is even.

NoteIn the first test case, after removing $$$3$$$, the sequence becomes $$$[2,4,6,8]$$$. The pairs of consecutive elements are $$$\{[2, 4], [4, 6], [6, 8]\}$$$. Each consecutive pair has an even sum now. Hence, we only need to remove $$$1$$$ element to satisfy the condition asked.In the second test case, each consecutive pair already has an even sum so we need not remove any element.

package main

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

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

	var tc int
	Fscan(in, &tc)

	for _t := 0; _t < tc; _t++ {
		var n int
		Fscan(in, &n)

		var numOfEven, numOfOdd, ans int

		for i := 0; i < n; i++ {
			var temp int
			Fscan(in, &temp)

			if temp%2 == 0 {
				numOfEven++
			} else {
				numOfOdd++
			}
		}
		ans = numOfEven
		if numOfOdd > numOfEven {
			ans = numOfOdd
		}
		Fprintln(out, n-ans)
	}
}

*/

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

	var tc int
	Fscan(in, &tc)

	for _t := 0; _t < tc; _t++ {
		var n int
		Fscan(in, &n)

		num := make([]int, n, n)
		parityCounter := make(map[int]int)
		for i := 0; i < n; i++ {
			Fscan(in, &num[i])
			parityCounter[num[i]%2]++
		}
		var ans = parityCounter[0]
		if parityCounter[1] > ans {
			ans = parityCounter[1]
		}
		Fprintln(out, n-ans)
	}
}

package main

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

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

	var tc int
	Fscan(in, &tc)

	for _t := 0; _t < tc; _t++ {
		var n int
		Fscan(in, &n)

		var numOfEven, numOfOdd, ans int

		for i := 0; i < n; i++ {
			var temp int
			Fscan(in, &temp)

			if temp%2 == 0 {
				numOfEven++
			} else {
				numOfOdd++
			}
		}
		ans = numOfEven
		if numOfOdd > numOfEven {
			ans = numOfOdd
		}
		Fprintln(out, n-ans)
	}
}

package main

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

var fin = bufio.NewReader(os.Stdin)
var fout = bufio.NewWriter(os.Stdout)

func solve(){
    var n int
    fmt.Fscan(fin,&n)
    cnt1:=0
    cnt2:=0
    nums := make([]int,n)
    for i:=0;i<n;i++{
        fmt.Fscan(fin,&nums[i])
    }
    for _,v := range nums {
        if v%2 ==0 {
            cnt2++
        } else {
            cnt1++
        }
    }
    ans:=0
    if cnt1 > cnt2 {
        ans = n - cnt1
    } else {
        ans = n - cnt2
    }
    fmt.Fprintln(fout,ans)
}

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

package main

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

var fin = bufio.NewReader(os.Stdin)
var fout = bufio.NewWriter(os.Stdout)

func solve(){
    var n int
    fmt.Fscan(fin,&n)
    cnt1:=0
    cnt2:=0
    for i:=0;i<n;i++{
        var x int
        fmt.Fscan(fin,&x)
        if x%2==0 {
            cnt2++
        } else {
            cnt1++
        }
    }
    ans:=0
    if cnt1 > cnt2 {
        ans = n - cnt1
    } else {
        ans = n - cnt2
    }
    fmt.Fprintln(fout,ans)
}

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

package main

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

var fin = bufio.NewReader(os.Stdin)
var fout = bufio.NewWriter(os.Stdout)

func main(){
    defer fout.Flush()
    var t int
    fmt.Fscan(fin,&t)
    for ;t>0;t--{
        var n int
        fmt.Fscan(fin,&n)
        cnt1:=0
        cnt2:=0
        for i:=0;i<n;i++{
            var x int
            fmt.Fscan(fin,&x)
            if x%2==0 {
                cnt2++
            } else {
                cnt1++
            }
        }
        ans:=0
        if cnt1 > cnt2 {
            ans = n - cnt1
        } else {
            ans = n - cnt2
        }
        fmt.Fprintln(fout,ans)
    }
}

package main

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

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

	var testCases int
	Fscan(in, &testCases)

	for c := 0; c < testCases; c++ {
		var n int
		Fscan(in, &n)

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

		Fprintln(out, solve(nums))
	}

}

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

func solve(nums []int) int {
	oddCount := 0
	evenCount := 0

	for i := 0; i < len(nums); i++ {
		if isEven(nums[i]) {
			evenCount++
		} else {
			oddCount++
		}
	}

	return min(oddCount, evenCount)
}

func isEven(n int) bool {
	return n%2 == 0
}

package main

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

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

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

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

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

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

/**
Run solve the problem CF1691A
Date: 4/06/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1691/A
Problem: CF1691A
**/
func (in *CF1691A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)
		even := 0
		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
			if arr[i]%2 == 0 {
				even++
			}
		}

		ans := 0
		if even < n-even {
			ans = even
		}else {
			ans = n -even
		}

		fmt.Println(ans)

	}
}

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

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

package main

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

var (
	_r = bufio.NewReader(os.Stdin)
	_w = bufio.NewWriter(os.Stdout)
)

func main() {
	defer _w.Flush()
	var t int
	fmt.Fscan(_r, &t)
	for ; t > 0; t-- {
		solve()
	}
}
func solve() {
	var n int
	fmt.Fscan(_r, &n)
	a := make([]int, 2)
	for i := 0; i < n; i++ {
		var x int
		fmt.Fscan(_r, &x)
		a[x%2]++
	}
	fmt.Fprintln(_w, min(a[0], a[1]))
}
func min(x, y int) int {
	if x <= y {
		return x
	}
	return y
}

package main
import (
	"bufio"
	"fmt"
	"os"
)
var fin = bufio.NewReader(os.Stdin)
var fout = bufio.NewWriter(os.Stdout)
func main() {
	defer fout.Flush()
	t := 0
	fmt.Fscan(fin, &t)
	for tt := 0; tt < t; tt++ {
		n := 0
		fmt.Fscan(fin, &n)
		c := [2]int{}
		for i := 0; i < n; i++ {
			x := 0
			fmt.Fscan(fin, &x)
			c[x % 2] += 1
		}
		if c[0] < c[1] {
			fmt.Fprintln(fout, c[0])
		} else {
			fmt.Fprintln(fout, c[1])
		}
	}
}

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		odds:=0
		evens:=0
		for j:=0;j<n;j++{
			var x int
			fmt.Fscan(in,&x)
			if x%2 == 0 {
				evens++
			} else {
				odds++
			}
		}
		if evens > odds {
			fmt.Fprintln(out,odds)
		} else {
			fmt.Fprintln(out,evens)
		}
	}
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t, n   int
	a      []int
)

func solve(n int, a []int) int {
	var odd int
	for _, x := range a {
		odd += x % 2
	}
	if odd > n-odd {
		return n - odd
	}
	return odd
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		a = make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i])
		}
		fmt.Println(solve(n, a))
	}
}

package main

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

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

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

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

func main() {
	in := bufio.NewReader(os.Stdin)
	t := readInt(in)
	for ; t > 0; t-- {
		n := readInt(in)
		arr := readArrInt(in)
		var oddCnt, evenCnt int
		for i := 0; i < n; i++ {
			if arr[i]&1 == 1 {
				oddCnt++
			} else {
				evenCnt++
			}
		}
		if oddCnt == 0 || evenCnt == 0 {
			fmt.Println(0)
		} else if oddCnt < evenCnt {
			fmt.Println(oddCnt)
		} else {
			fmt.Println(evenCnt)
		}
	}
}

package main

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

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

func scan(a ...interface{}) {
	fmt.Fscan(in, a...)
}
func printf(f string, a ...interface{}) {
	fmt.Fprintf(out, f, a...)
}

func solve() {
	var n,x int
	scan(&n)
	odd := 0
	for i := 0; i < n; i++ {
		scan(&x)
		if x & 1 != 0 {
			odd += 1
		}
	}
	printf("%d\n", int(math.Min(float64(odd), float64(n - odd))))
}
func main() {
	defer out.Flush()
	n := 0
	scan(&n)
	for i := 0; i < n; i++ {
		solve()
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func gi2() (int,int) { return gi(),gi() }
func gi3() (int,int,int) { return gi(),gi(),gi() }
func gi4() (int,int,int,int) { return gi(),gi(),gi(),gi() }
func gis(n int) []int  { res := make([]int,n); for i:=0;i<n;i++ { res[i] = gi() }; return res }
func gf() float64 { f,e := strconv.ParseFloat(gs(),64); if e != nil {panic(e)}; return f }
func gbs() []byte { return []byte(gs()) }
func gfs(n int) []float64  { res := make([]float64,n); for i:=0;i<n;i++ { res[i] = gf() }; return res }
func gss(n int) []string  { res := make([]string,n); for i:=0;i<n;i++ { res[i] = gs() }; return res }
func ia(m int) []int { return make([]int,m) }
func iai(m int,v int) []int { a := make([]int,m); for i:=0;i<m;i++ { a[i] = v }; return a }
func twodi(n int,m int,v int) [][]int {
	r := make([][]int,n); for i:=0;i<n;i++ { x := make([]int,m); for j:=0;j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill2(m int) ([]int,[]int) { a,b := ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i] = gi(),gi()}; return a,b }
func fill3(m int) ([]int,[]int,[]int) { a,b,c := ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i] = gi(),gi(),gi()}; return a,b,c }
func fill4(m int) ([]int,[]int,[]int,[]int) { a,b,c,d := ia(m),ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i],d[i] = gi(),gi(),gi(),gi()}; return a,b,c,d }
func abs(a int) int { if a < 0 { return -a }; return a }
func rev(a []int) { i,j := 0,len(a)-1; for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
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 tern(cond bool, a int, b int) int { if cond { return a }; return b }
func terns(cond bool, a string, b string) string { if cond { return a }; return b }
func maxarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr(a []int) int { ans := 0; for _,aa := range(a) { ans += aa }; return ans }
func zeroarr(a []int) { for i:=0; i<len(a); i++ { a[i] = 0 } }
func powmod(a,e,mod int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint(a,e int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd(a,b int) int { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended(a,b int) (int,int,int) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv(a,m int) (int,bool) { g,x,_ := gcdExtended(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func makefact(n int,mod int) ([]int,[]int) {
	fact,factinv := make([]int,n+1),make([]int,n+1)
	fact[0] = 1; for i:=1;i<=n;i++ { fact[i] = fact[i-1] * i % mod }
	factinv[n] = powmod(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * (i+1) % mod }
	return fact,factinv
}
func vecintstring(a []int) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.Itoa(a) }; return strings.Join(astr," ") }
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N := gi(); A := gis(N)
		nume,numo := 0,0
		for _,a := range A { if a % 2 == 0 { nume++ } else { numo++ } }
		ans := min(nume,numo)
		fmt.Fprintln(wrtr,ans)
	}
}

package main

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

var t, m, n int

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

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

	t, _ = strconv.Atoi(next())
	for i := 0; i < t; i++ {
		n, _ = strconv.Atoi(next())

		var even, odd int
		for i := 0; i < n; i++ {
			ai, _ := strconv.Atoi(next())
			if ai%2 == 0 {
				even++
			} else {
				odd++
			}
		}
		fmt.Println(math.Min(float64(even), float64(odd)))
	}
}

package main

import (
	"bufio"
	"container/heap"
	. "fmt"
	"math"
	"os"
)

type Int int64

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

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

	var T int
	Fscan(in, &T)

	for tt := 0; tt < T; tt++ {
		var n, x int
		Fscan(in, &n)
		cnt := L0
		count := L0
		for i := 0; i < n; i++ {
			Fscan(in, &x)
			if x%2 == 0 {
				cnt++
			} else {
				count++
			}
		}
		Fprintln(out, Min(cnt, count))

	}

}

func MakeGrid(h, w int) [][]Int {
	index := make([][]Int, h)
	data := make([]Int, h*w)
	for i := 0; i < h; i++ {
		index[i] = data[i*w : (i+1)*w]
	}
	return index
}

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

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

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

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

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

var (
	mod  Int
	fmod func(Int) Int = doNothing
)

// SetMod sets the mod. It must be called first.
func SetMod(newMod Int) {
	mod = newMod
	fmod = dynamicMod
}

func dynamicMod(m Int) Int {
	m %= mod
	if m < 0 {
		return m + mod
	}
	return m
}

func doNothing(m Int) Int {
	return m
}

// Mod returns m % mod.
func (m Int) Mod() Int {
	return fmod(m)
}

// Inv returns modular multiplicative inverse
func (m Int) Inv() Int {
	return m.Pow(Int(0).Sub(2))
}

// Pow returns m^n
func (m Int) Pow(n Int) Int {
	p := Int(1)
	for n > 0 {
		if n&1 == 1 {
			p.MulAs(m)
		}
		m.MulAs(m)
		n >>= 1
	}
	return p
}

// Add returns m+x
func (m Int) Add(x Int) Int {
	return (m + x).Mod()
}

// Sub returns m-x
func (m Int) Sub(x Int) Int {
	return (m - x).Mod()
}

// Mul returns m*x
func (m Int) Mul(x Int) Int {
	return (m * x).Mod()
}

// Div returns m/x
func (m Int) Div(x Int) Int {
	return m.Mul(x.Inv())
}

// AddAs assigns *m + x to *m and returns m
func (m *Int) AddAs(x Int) *Int {
	*m = m.Add(x)
	return m
}

// SubAs assigns *m - x to *m and returns m
func (m *Int) SubAs(x Int) *Int {
	*m = m.Sub(x)
	return m
}

// MulAs assigns *m * x to *m and returns m
func (m *Int) MulAs(x Int) *Int {
	*m = m.Mul(x)
	return m
}

// DivAs assigns *m / x to *m and returns m
func (m *Int) DivAs(x Int) *Int {
	*m = m.Div(x)
	return m
}

func (m *Int) MaxAs(x ...Int) *Int {
	*m = Max(append(x, *m)...)
	return m
}

func (m *Int) MinAs(x ...Int) *Int {
	*m = Min(append(x, *m)...)
	return m
}

type Void struct{}

var void Void

type HashSet struct {
	ma map[Int]Void
}

func NewHashSet() *HashSet {
	return &HashSet{
		ma: make(map[Int]Void),
	}
}

func (s *HashSet) add(x Int) bool {
	_, exists := s.ma[x]
	if !exists {
		s.ma[x] = void
		return true
	} else {
		return false
	}
}

func (s *HashSet) del(x Int) {
	delete(s.ma, x)
}

func (s *HashSet) exist(x Int) bool {
	_, exists := s.ma[x]
	return exists
}

// An Item is something we manage in a priority queue.
type Item struct {
	value    Int // The value of the item; arbitrary.
	priority Int // The priority of the item in the queue.
	indices  Int
	// The index is needed by update and is maintained by the heap.Interface methods.
	index int // The index of the item in the heap.
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func NewItem(value, priority Int) *Item {
	return &Item{
		value:    value,
		priority: priority,
		index:    -1,
	}

}

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].priority < pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value Int, priority Int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

type SegTree struct {
	st []Segment
}

type Segment struct {
	l, r, val, add, minIndex Int
}

func newSegTree(n Int) SegTree {
	segTree := SegTree{make([]Segment, n<<2)}
	segTree.Build(1, 1, n)
	return segTree
}

func (segTree SegTree) Build(x, l, r Int) {
	segTree.st[x].l = l
	segTree.st[x].r = r
	if l == r {
		segTree.st[x].minIndex = l
		return
	}
	mid := (l + r) >> 1
	segTree.Build(x<<1, l, mid)
	segTree.Build(x<<1|1, mid+1, r)
}

func (segTree SegTree) push(x Int) {
	if segTree.st[x].add != 0 {
		segTree.modifyOne(x<<1, segTree.st[x].add)
		segTree.modifyOne(x<<1|1, segTree.st[x].add)
		segTree.st[x].add = 0
	}
}

func (segTree SegTree) update(x Int) {
	if segTree.st[x<<1].val < segTree.st[x<<1|1].val {
		segTree.st[x].val = segTree.st[x<<1].val
		segTree.st[x].minIndex = segTree.st[x<<1].minIndex
	} else {
		segTree.st[x].val = segTree.st[x<<1|1].val
		segTree.st[x].minIndex = segTree.st[x<<1|1].minIndex
	}
}

func (segTree SegTree) modifyOne(x, add Int) {
	segTree.st[x].val += add
	if segTree.st[x].l != segTree.st[x].r {
		segTree.st[x].add += add
	}
}

func (segTree SegTree) Modify(x, l, r, add Int) {
	if segTree.st[x].l >= l && segTree.st[x].r <= r {
		segTree.modifyOne(x, add)
		return
	}
	segTree.push(x)
	mid := (segTree.st[x].l + segTree.st[x].r) >> 1
	if mid >= l {
		segTree.Modify(x<<1, l, r, add)
	}
	if mid < r {
		segTree.Modify(x<<1|1, l, r, add)
	}
	segTree.update(x)
}

func updateRes(cRes, cIndex, res, index Int) (Int, Int) {
	if cRes > res {
		return res, index
	}
	return cRes, cIndex
}

func (segTree SegTree) Query(x, l, r Int) (Int, Int) {
	res := Int(math.MaxInt64)
	resInd := -L1
	if segTree.st[x].l >= l && segTree.st[x].r <= r {
		res, resInd = updateRes(res, resInd, segTree.st[x].val, segTree.st[x].minIndex)
		return res, resInd
	}
	mid := (segTree.st[x].l + segTree.st[x].r) >> 1
	if mid >= l {
		sonRes, sonInd := segTree.Query(x<<1, l, r)
		res, resInd = updateRes(res, resInd, sonRes, sonInd)
	}
	if mid < r {
		sonRes, sonInd := segTree.Query(x<<1|1, l, r)
		res, resInd = updateRes(res, resInd, sonRes, sonInd)
	}
	return res, resInd
}

type Graph struct {
	nodeSize Int
	edges    []Edge
	head     []Int
	dis      []Int
	vis      []bool
	nCnt     Int
	ans      []Int
}

type Edge struct {
	u, v, c, indices, next Int
}

func NewGraph(nodeSize Int) *Graph {
	return &Graph{
		nodeSize: nodeSize,
		edges:    make([]Edge, (2e5+10)<<2),
		head:     make([]Int, nodeSize+100),
		dis:      make([]Int, nodeSize+100),
		vis:      make([]bool, nodeSize+100),
		nCnt:     L1,
		ans:      make([]Int, nodeSize),
	}
}

func (g *Graph) addEdge(u Int, v Int, cost Int, indices Int) {
	g.nCnt++
	g.edges[g.nCnt] = Edge{u, v, cost, indices, g.head[u]}
	g.head[u] = g.nCnt
}

func (g *Graph) Dijkstra(begin Int) {
	for i := L1; i <= g.nodeSize; i++ {
		g.dis[i] = math.MaxInt64
	}
	pq := make(PriorityQueue, 0)
	heap.Init(&pq)

	g.dis[begin] = 0
	heap.Push(&pq, &Item{begin, 0, -1, -1})

	id := L0

	for len(pq) > 0 {
		it := heap.Pop(&pq).(*Item)
		u := it.value
		if g.vis[u] {
			continue
		}
		g.vis[u] = true

		if it.indices != -1 && id < g.nodeSize-1 {
			g.ans[id] = it.indices
			id++
		}

		for i := g.head[u]; i != 0; i = g.edges[i].next {
			v := g.edges[i].v
			if g.dis[v] > g.dis[u]+g.edges[i].c {
				g.dis[v] = g.dis[u] + g.edges[i].c

				heap.Push(&pq, &Item{v, g.dis[v], g.edges[i].indices, -1})
			}
		}
	}
}

package main

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

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

func slove() {
	var n int
	fmt.Fscan(r, &n)
	nums := make([]int, n)
	for i:=0;i<n;i++ {
		fmt.Fscan(r, &nums[i])
	}
	cnt := 0
	for i := range nums {
		if nums[i] % 2 == 0 {
			cnt++
		}
	}
	fmt.Fprintln(w, min(cnt, n-cnt))
}
func min(a, b int) int {if a < b {return a} else {return b}}
func main() {
	defer w.Flush()
	var n int
	fmt.Fscan(r, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
)

///////// red black tree //////////////

type Comparator func(a, b interface{}) int

type color bool

const (
	black, red color = true, false
)

type RBTree struct {
	Root       *RBNode
	size       int
	Comparator Comparator
}

type RBNode struct {
	Key    interface{}
	Value  interface{}
	color  color
	Left   *RBNode
	Right  *RBNode
	Parent *RBNode
}

func NewRBTree(comparator Comparator) *RBTree {
	return &RBTree{Comparator: comparator}
}

func (tree *RBTree) Put(key interface{}, value interface{}) {
	var insertedRBNode *RBNode
	if tree.Root == nil {
		tree.Comparator(key, key)
		tree.Root = &RBNode{Key: key, Value: value, color: red}
		insertedRBNode = tree.Root
	} else {
		node := tree.Root
		loop := true
		for loop {
			compare := tree.Comparator(key, node.Key)
			switch {
			case compare == 0:
				node.Key = key
				node.Value = value
				return
			case compare < 0:
				if node.Left == nil {
					node.Left = &RBNode{Key: key, Value: value, color: red}
					insertedRBNode = node.Left
					loop = false
				} else {
					node = node.Left
				}
			case compare > 0:
				if node.Right == nil {
					node.Right = &RBNode{Key: key, Value: value, color: red}
					insertedRBNode = node.Right
					loop = false
				} else {
					node = node.Right
				}
			}
		}
		insertedRBNode.Parent = node
	}
	tree.insertCase1(insertedRBNode)
	tree.size++
}

func (tree *RBTree) Begin() *RBNode {
	if tree.Root == nil {
		return nil
	}

	node := tree.Root
	for node.Left != nil {
		node = node.Left
	}
	return node
}

func (tree *RBTree) Last() *RBNode {
	if tree.Root == nil {
		return nil
	}

	node := tree.Root
	for node.Right != nil {
		node = node.Right
	}
	return node
}

func (tree *RBTree) Get(key interface{}) (value interface{}, found bool) {
	node := tree.lookup(key)
	if node != nil {
		return node.Value, true
	}
	return nil, false
}

func (tree *RBTree) GetRBNode(key interface{}) *RBNode {
	return tree.lookup(key)
}

func (tree *RBTree) Remove(key interface{}) {
	var child *RBNode
	node := tree.lookup(key)
	if node == nil {
		return
	}
	if node.Left != nil && node.Right != nil {
		pred := node.Left.maximumRBNode()
		node.Key = pred.Key
		node.Value = pred.Value
		node = pred
	}
	if node.Left == nil || node.Right == nil {
		if node.Right == nil {
			child = node.Left
		} else {
			child = node.Right
		}
		if node.color == black {
			node.color = nodeColor(child)
			tree.deleteCase1(node)
		}
		tree.replaceRBNode(node, child)
		if node.Parent == nil && child != nil {
			child.color = black
		}
	}
	tree.size--
}

func (tree *RBTree) Empty() bool {
	return tree.size == 0
}

func (tree *RBTree) Size() int {
	return tree.size
}

func (node *RBNode) Size() int {
	if node == nil {
		return 0
	}
	size := 1
	if node.Left != nil {
		size += node.Left.Size()
	}
	if node.Right != nil {
		size += node.Right.Size()
	}
	return size
}

func (tree *RBTree) Keys() []interface{} {
	keys := []interface{}{}
	var dfs func(node *RBNode)
	dfs = func(node *RBNode) {
		if node == nil {
			return
		}
		dfs(node.Left)
		keys = append(keys, node.Key)
		dfs(node.Right)
	}

	dfs(tree.Root)
	return keys
}

func (tree *RBTree) Values() []interface{} {
	values := []interface{}{}
	var dfs func(node *RBNode)
	dfs = func(node *RBNode) {
		if node == nil {
			return
		}
		dfs(node.Left)
		values = append(values, node.Value)
		dfs(node.Right)
	}

	dfs(tree.Root)
	return values
}

func (tree *RBTree) Left() *RBNode {
	var parent *RBNode
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Left
	}
	return parent
}

func (tree *RBTree) Right() *RBNode {
	var parent *RBNode
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Right
	}
	return parent
}

func (tree *RBTree) Floor(key interface{}) (floor *RBNode, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			node = node.Left
		case compare > 0:
			floor, found = node, true
			node = node.Right
		}
	}
	if found {
		return floor, true
	}
	return nil, false
}

func (tree *RBTree) Ceiling(key interface{}) (ceiling *RBNode, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			ceiling, found = node, true
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	if found {
		return ceiling, true
	}
	return nil, false
}

func (tree *RBTree) Clear() {
	tree.Root = nil
	tree.size = 0
}

func (tree *RBTree) String() string {
	str := "RedBlackRBTree\n"
	if !tree.Empty() {
		output(tree.Root, "", true, &str)
	}
	return str
}

func (node *RBNode) String() string {
	return fmt.Sprintf("%v", node.Key)
}

func output(node *RBNode, prefix string, isTail bool, str *string) {
	if node.Right != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "│   "
		} else {
			newPrefix += "    "
		}
		output(node.Right, newPrefix, false, str)
	}
	*str += prefix
	if isTail {
		*str += "└── "
	} else {
		*str += "┌── "
	}
	*str += node.String() + "\n"
	if node.Left != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "    "
		} else {
			newPrefix += "│   "
		}
		output(node.Left, newPrefix, true, str)
	}
}

func (tree *RBTree) lookup(key interface{}) *RBNode {
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node
		case compare < 0:
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	return nil
}

func (node *RBNode) grandparent() *RBNode {
	if node != nil && node.Parent != nil {
		return node.Parent.Parent
	}
	return nil
}

func (node *RBNode) uncle() *RBNode {
	if node == nil || node.Parent == nil || node.Parent.Parent == nil {
		return nil
	}
	return node.Parent.sibling()
}

func (node *RBNode) sibling() *RBNode {
	if node == nil || node.Parent == nil {
		return nil
	}
	if node == node.Parent.Left {
		return node.Parent.Right
	}
	return node.Parent.Left
}

func (tree *RBTree) rotateLeft(node *RBNode) {
	right := node.Right
	tree.replaceRBNode(node, right)
	node.Right = right.Left
	if right.Left != nil {
		right.Left.Parent = node
	}
	right.Left = node
	node.Parent = right
}

func (tree *RBTree) rotateRight(node *RBNode) {
	left := node.Left
	tree.replaceRBNode(node, left)
	node.Left = left.Right
	if left.Right != nil {
		left.Right.Parent = node
	}
	left.Right = node
	node.Parent = left
}

func (tree *RBTree) replaceRBNode(old *RBNode, new *RBNode) {
	if old.Parent == nil {
		tree.Root = new
	} else {
		if old == old.Parent.Left {
			old.Parent.Left = new
		} else {
			old.Parent.Right = new
		}
	}
	if new != nil {
		new.Parent = old.Parent
	}
}

func (tree *RBTree) insertCase1(node *RBNode) {
	if node.Parent == nil {
		node.color = black
	} else {
		tree.insertCase2(node)
	}
}

func (tree *RBTree) insertCase2(node *RBNode) {
	if nodeColor(node.Parent) == black {
		return
	}
	tree.insertCase3(node)
}

func (tree *RBTree) insertCase3(node *RBNode) {
	uncle := node.uncle()
	if nodeColor(uncle) == red {
		node.Parent.color = black
		uncle.color = black
		node.grandparent().color = red
		tree.insertCase1(node.grandparent())
	} else {
		tree.insertCase4(node)
	}
}

func (tree *RBTree) insertCase4(node *RBNode) {
	grandparent := node.grandparent()
	if node == node.Parent.Right && node.Parent == grandparent.Left {
		tree.rotateLeft(node.Parent)
		node = node.Left
	} else if node == node.Parent.Left && node.Parent == grandparent.Right {
		tree.rotateRight(node.Parent)
		node = node.Right
	}
	tree.insertCase5(node)
}

func (tree *RBTree) insertCase5(node *RBNode) {
	node.Parent.color = black
	grandparent := node.grandparent()
	grandparent.color = red
	if node == node.Parent.Left && node.Parent == grandparent.Left {
		tree.rotateRight(grandparent)
	} else if node == node.Parent.Right && node.Parent == grandparent.Right {
		tree.rotateLeft(grandparent)
	}
}

func (node *RBNode) maximumRBNode() *RBNode {
	if node == nil {
		return nil
	}
	for node.Right != nil {
		node = node.Right
	}
	return node
}

func (tree *RBTree) deleteCase1(node *RBNode) {
	if node.Parent == nil {
		return
	}
	tree.deleteCase2(node)
}

func (tree *RBTree) deleteCase2(node *RBNode) {
	sibling := node.sibling()
	if nodeColor(sibling) == red {
		node.Parent.color = red
		sibling.color = black
		if node == node.Parent.Left {
			tree.rotateLeft(node.Parent)
		} else {
			tree.rotateRight(node.Parent)
		}
	}
	tree.deleteCase3(node)
}

func (tree *RBTree) deleteCase3(node *RBNode) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == black &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		tree.deleteCase1(node.Parent)
	} else {
		tree.deleteCase4(node)
	}
}

func (tree *RBTree) deleteCase4(node *RBNode) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == red &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		node.Parent.color = black
	} else {
		tree.deleteCase5(node)
	}
}

func (tree *RBTree) deleteCase5(node *RBNode) {
	sibling := node.sibling()
	if node == node.Parent.Left &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == red &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		sibling.Left.color = black
		tree.rotateRight(sibling)
	} else if node == node.Parent.Right &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Right) == red &&
		nodeColor(sibling.Left) == black {
		sibling.color = red
		sibling.Right.color = black
		tree.rotateLeft(sibling)
	}
	tree.deleteCase6(node)
}

func (tree *RBTree) deleteCase6(node *RBNode) {
	sibling := node.sibling()
	sibling.color = nodeColor(node.Parent)
	node.Parent.color = black
	if node == node.Parent.Left && nodeColor(sibling.Right) == red {
		sibling.Right.color = black
		tree.rotateLeft(node.Parent)
	} else if nodeColor(sibling.Left) == red {
		sibling.Left.color = black
		tree.rotateRight(node.Parent)
	}
}

func nodeColor(node *RBNode) color {
	if node == nil {
		return black
	}
	return node.color
}

///////// priority queue ///////////

type PriorityQueue struct {
	Data       []interface{}
	Comparator func(a, b interface{}) int
}

func NewPriorityQueue(comparator func(a, b interface{}) int) *PriorityQueue {
	res := &PriorityQueue{
		Data:       []interface{}{},
		Comparator: comparator,
	}
	heap.Init(res)
	return res
}

func (pq *PriorityQueue) Len() int {
	return len(pq.Data)
}

func (pq *PriorityQueue) Less(i, j int) bool {
	return pq.Comparator(pq.Data[i], pq.Data[j]) < 0
}

func (pq *PriorityQueue) Swap(i, j int) {
	pq.Data[i], pq.Data[j] = pq.Data[j], pq.Data[i]
}

func (pq *PriorityQueue) Push(a interface{}) {
	pq.Data = append(pq.Data, a)
}

func (pq *PriorityQueue) Pop() interface{} {
	n := len(pq.Data)
	res := pq.Data[n-1]
	pq.Data = pq.Data[0 : n-1]
	return res
}

func (pq *PriorityQueue) Put(a interface{}) {
	heap.Push(pq, a)
}

func (pq *PriorityQueue) Get() interface{} {
	return heap.Pop(pq)
}

////////////////////////////////////

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

var T, N int

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

	fmt.Fscan(in, &T)

	for tt := 1; tt <= T; tt++ {
		fmt.Fscan(in, &N)
		var a int
		var n0, n1 int
		for i := 0; i < N; i++ {
			fmt.Fscan(in, &a)
			if a%2 == 0 {
				n0++
			} else {
				n1++
			}
		}

		fmt.Println(min(n0, n1))
	}

}

package main

import "fmt"

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

	for _t := 0; _t < tc; _t++ {
		var n int
		fmt.Scanf("%d", &n)
		var ans, numberOfEven, numberOfOdd int

		for i := 0; i < n; i++ {
			var temp int
			fmt.Scanf("%d", &temp)
			if temp%2 == 0 {
				numberOfEven++
			} else {
				numberOfOdd++
			}

			ans = numberOfEven

		}
		if numberOfEven < numberOfOdd {
			ans = numberOfOdd
		}

		fmt.Printf("%d\n", n-ans)
	}
}

package main

import "fmt"

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

	for _t := 0; _t < tc; _t++ {
		var n int
		fmt.Scanf("%d", &n)
		var numberOfEven, numberOfOdd int

		var ans int
		for i := 0; i < n; i++ {
			var temp int
			fmt.Scanf("%d", &temp)
			if temp%2 == 0 {
				numberOfEven++
			} else {
				numberOfOdd++
			}

			ans = numberOfEven

		}
		if numberOfEven < numberOfOdd {
			ans = numberOfOdd
		}

		fmt.Println(n - ans)
	}
}

package main

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

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

	var testCases int
	Fscan(in, &testCases)

	for c := 0; c < testCases; c++ {
		var n int
		Fscan(in, &n)

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

		Fprintln(out, solve(nums))
	}

}

// func solve(nums []int) int {
// 	count1 := 0

// 	cur := 0
// 	for i := 1; i < len(nums); i++ {
// 		if (nums[cur]+nums[i])%2 == 0 {
// 			cur = i
// 			continue
// 		}
// 		count1++
// 	}

// 	count2 := 0

// 	cur = len(nums) - 1
// 	for i := cur - 1; i >= 0; i-- {
// 		if (nums[cur]+nums[i])%2 == 0 {
// 			cur = i
// 			continue
// 		}
// 		count2++
// 	}

// 	return min(count1, count2)
// }

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

func solve(nums []int) int {
	oddEvenPairCounts := int(0)

	for i := 1; i < len(nums); i++ {
		if isEven(nums[i-1]) != isEven(nums[i]) {
			oddEvenPairCounts++
		}
	}

	if isEven(oddEvenPairCounts) {
		return oddEvenPairCounts / 2
	}
	return (oddEvenPairCounts / 2) + 1
}

func isEven(n int) bool {
	return n%2 == 0
}

package main

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

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

	var testCases int
	Fscan(in, &testCases)

	for c := 0; c < testCases; c++ {
		var n int
		Fscan(in, &n)

		nums := make([]int64, n)
		for i := 0; i < n; i++ {
			Fscan(in, &nums[i])
		}

		Fprintln(out, solve(nums))
	}

}

// func solve(nums []int64) int {
// 	count1 := 0

// 	cur := 0
// 	for i := 1; i < len(nums); i++ {
// 		if (nums[cur]+nums[i])%2 == 0 {
// 			cur = i
// 			continue
// 		}
// 		count1++
// 	}

// 	count2 := 0

// 	cur = len(nums) - 1
// 	for i := cur - 1; i >= 0; i-- {
// 		if (nums[cur]+nums[i])%2 == 0 {
// 			cur = i
// 			continue
// 		}
// 		count2++
// 	}

// 	return min(count1, count2)
// }

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

func solve(nums []int64) int {
	oddEvenPairCounts := 0

	for i := 1; i < len(nums); i++ {
		if isEven(nums[i-1]) != isEven(nums[i]) {
			oddEvenPairCounts++
		}
	}

	return oddEvenPairCounts / 2
}

func isEven(n int64) bool {
	return n%2 == 0
}

package main

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

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

	var testCases int
	Fscan(in, &testCases)

	for c := 0; c < testCases; c++ {
		var n int
		Fscan(in, &n)

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

		Fprintln(out, solve(nums))
	}

}

func solve(nums []int) int {
	count1 := 0

	cur := 0
	for i := 1; i < len(nums); i++ {
		if (nums[cur]+nums[i])%2 == 0 {
			cur = i
			continue
		}
		count1++
	}

	count2 := 0

	cur = len(nums) - 1
	for i := cur - 1; i >= 0; i-- {
		if (nums[cur]+nums[i])%2 == 0 {
			cur = i
			continue
		}
		count2++
	}

	return min(count1, count2)
}

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1691A
Date: 4/06/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1691/A
Problem: CF1691A
**/
func (in *CF1691A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}

		sum := arr[0]
		ans := 0
		for i := 1; i < n; i++ {
			if (sum+arr[i])%2 != 0 {
				ans++
			} else {
				sum = arr[i]
			}
		}

		v2 := 1
		sum = arr[1]
		for i := 2; i < n; i++ {
			if (sum+arr[i])%2 != 0 {
				v2++
			} else {
				sum = arr[i]
			}
		}
		if v2 < ans {
			ans = v2
		}

		fmt.Println(ans)

	}
}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1691A
Date: 4/06/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1691/A
Problem: CF1691A
**/
func (in *CF1691A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		sum := 0
		ans := 0
		for i := 0; i < n; i++ {
			val := in.NextInt()
			if i == 0 {
				sum = val
			} else {
				if (sum+val)%2 != 0 {
					ans++
				} else {
					sum = val
				}
			}
		}
		fmt.Println(ans)

	}
}

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

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

package main

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

var (
	_r = bufio.NewReader(os.Stdin)
	_w = bufio.NewWriter(os.Stdout)
)

func main() {
	defer _w.Flush()
	var t int
	fmt.Fscan(_r, &t)
	for ; t > 0; t-- {
		solve()
	}
}
func solve() {
	var n int
	fmt.Fscan(_r, &n)
	cnt := make([]int, 2)
	for i := 0; i < n; i++ {
		var x int
		fmt.Fscan(_r, &x)
		if x%2 == 1 {
			cnt[1]++
		} else {
			cnt[0]++
		}
	}
	ans := 0
	for i := 0; i < 2; i++ {
		if cnt[i]%2 != 0 {
			ans++
		}
	}
	fmt.Fprintln(_w, ans)
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scanf("%d", &t)
	for ; t > 0; t-- {
		solve()
	}
}
func solve() {
	var n int
	fmt.Scanf("%d", &n)
	cnt := make([]int, 2)
	for i := 0; i < n; i++ {
		var x int
		fmt.Scanf("%d", &x)
		if x%2 == 1 {
			cnt[1]++
		} else {
			cnt[0]++
		}
	}
	ans := 0
	for i := 0; i < 2; i++ {
		if cnt[i]%2 != 0 {
			ans++
		}
	}
	fmt.Println(ans)
}


Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer ai — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of gifts. The next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the pleasantness of the gifts. The next (n - 1) lines contain two numbers each. The i-th of these lines contains integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the description of the tree's edges. It means that gifts with numbers ui and vi are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: vi hangs on ui or ui hangs on vi.  It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.

If it is possible for Chloe and Vladik to choose prizes without fighting, print single integer — the maximum possible sum of pleasantness they can get together. Otherwise print Impossible.

package main

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

func solve() {
    n := readInt()
    p := readInt64Array(n)
    a := make([][]int, n)
    for i := 0; i < n-1; i++ {
        v, u := readInt()-1, readInt()-1
        a[v] = append(a[v], u)
        a[u] = append(a[u], v)
    }
    sub, was := make([]int64, n), make([]bool, n)
    dp1, dp2, can := make([]int64, n), make([]int64, n), make([]bool, n)
    var calc func(k int)
    calc = func(k int) {
        sub[k], was[k] = p[k], true
        ch1, ch2 := Ints64{}, Ints64{}
        for _, v := range a[k] {
            if !was[v] {
                calc(v)
                sub[k] += sub[v]
                ch1 = append(ch1, dp1[v])
                if can[v] {
                    ch2 = append(ch2, dp2[v])
                }
            }
        }
        sort.Sort(sort.Reverse(ch1))
        dp1[k] = sub[k]
        if len(ch1) > 0 && ch1[0] > sub[k] {
            dp1[k] = ch1[0]
        }
        if len(ch1) > 1 {
            ch2 = append(ch2, ch1[0]+ch1[1])
        }
        sort.Sort(sort.Reverse(ch2))

        if len(ch2) > 0 {
            dp2[k] = ch2[0]
            can[k] = true
        }
    }
    calc(0)

    if can[0] {
        fmt.Println(dp2[0])
    } else {
        fmt.Println("Impossible")
    }
}

// Helpers

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

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

// Math

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

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

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

// IO

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
}

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

func readInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := 0; i < n; i++ {
		res[i] = readInt64()
	}
	return res
}

// Sort

type Ints64 []int64

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

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

const minf int64 = -2000000000000000

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

func Dfs(v int, vis []bool, price []int, dpOne, dpTwo, sum []int64, graph [][]int){
	vis[v]   = true
	sum[v]   = int64(price[v])
	dpOne[v] = minf
	dpTwo[v] = minf

	for _, x := range graph[v] {
		if vis[x] {
			continue
		}
		Dfs(x, vis, price, dpOne, dpTwo, sum, graph)
		sum[v]  += sum[x]
		dpOne[v] = Max(dpOne[v], dpOne[x])
		dpTwo[v] = Max(dpTwo[v], dpTwo[x])
	}

	second   := false
	secDpOne := minf

	for _, x :=range graph[v] {
		if dpOne[x] == dpOne[v] && !second {
			second = true
			continue
		}
		secDpOne = Max(dpOne[x], secDpOne)
	}

	dpTwo[v] = Max(dpTwo[v], dpOne[v] + secDpOne)
	dpOne[v] = Max(dpOne[v], sum[v])
}

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

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func prepare(){
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
}

func main() {
	prepare()

	var n, a, b int
	var graph   [][]int

	n = readInt()

	price     := make([]int,    n)
	dpOne     := make([]int64,  n)
	dpTwo     := make([]int64,  n)
	sum       := make([]int64,  n)
	visited   := make([]bool,   n)

	for i := 0; i < n; i++ {
		price[i] = readInt()
		graph    = append(graph, make([]int, 0))
	}

	for i := 0; i < n - 1; i++ {
		a = readInt() - 1
		b = readInt() - 1
		graph[a] = append(graph[a], b)
		graph[b] = append(graph[b], a)
	}

	Dfs(0, visited, price, dpOne, dpTwo, sum, graph)
	if dpTwo[0] * 2 < minf {
		fmt.Println("Impossible")
	} else {
		fmt.Println(dpTwo[0])
	}
}

package main

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

const MAX = 200010

const INF = int64(200000000000000)

type Edge struct {
	x, y int
}

type Node struct {
	ans, maxn, sum int64
}

var a []int64
var d []Node
var vis []bool
var c []int

var first []int
var next []int
var edges []Edge

var cnt int

func addEdge(u, v int) {
	cnt++
	edges[cnt].x = u
	edges[cnt].y = v

	next[cnt] = first[u]
	first[u] = cnt
}

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

}

func dp(root int) Node {
	if vis[root] {
		return d[root]
	}

	d[root].ans = -INF
	d[root].maxn = -INF
	d[root].sum = a[root]
	vis[root] = true

	x := -INF
	y := -INF

	for i := first[root]; i != 0; i = next[i] {
		u := edges[i].y
		if !vis[u] {
			tmp := dp(u)
			d[root].maxn = max(d[root].maxn, tmp.maxn)
			d[root].sum += tmp.sum

			d[root].ans = max(d[root].ans, tmp.ans)

			if tmp.maxn > x {
				y = x
				x = tmp.maxn
			} else if tmp.maxn > y {
				y = tmp.maxn
			}
		}
	}

	d[root].maxn = max(d[root].maxn, d[root].sum)
	if x > -INF && y > -INF {
		d[root].ans = max(d[root].ans, x+y)
	}

	return d[root]

}

func main() {

	var n int

	b, _ := ioutil.ReadAll(os.Stdin)
	r := bytes.NewReader(b)

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

	a = make([]int64, n+1)
	d = make([]Node, n+1)
	vis = make([]bool, n+1)
	c = make([]int, n+1)

	first = make([]int, n+1)
	next = make([]int, 2*n+1)
	edges = make([]Edge, 2*n+1)

	cnt = 0

	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%v ", &a[i])
	}
	fmt.Fscanf(r, "%v\n", &a[n])

	var u, v int
	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%d %d\n", &u, &v)
		c[u]++
		c[v]++

		addEdge(u, v)
		addEdge(v, u)
	}

	dp(1)
	ans := d[1].ans

	if ans <= -INF {
		fmt.Printf("Impossible\n")
	} else {
		fmt.Printf("%v\n", ans)
	}

	return

}

package main

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

const MAX = 200010

const INF = int64(200000000000000)

type Edge struct {
	x, y int
}

type Node struct {
	ans, maxn, sum int64
}

var a []int64
var d []Node
var vis []bool
var c []int

var first []int
var next []int
var edges []Edge

var cnt int

func addEdge(u, v int) {
	cnt++
	edges[cnt].x = u
	edges[cnt].y = v

	next[cnt] = first[u]
	first[u] = cnt
}

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

}

func dp(root int) Node {
	if vis[root] {
		return d[root]
	}

	d[root].ans = -INF
	d[root].maxn = -INF
	d[root].sum = a[root]
	vis[root] = true

	x := -INF
	y := -INF

	for i := first[root]; i != 0; i = next[i] {
		u := edges[i].y
		if !vis[u] {
			tmp := dp(u)
			d[root].maxn = max(d[root].maxn, tmp.maxn)
			d[root].sum += tmp.sum

			d[root].ans = max(d[root].ans, tmp.ans)

			//fmt.Printf("root1 = %d %d %d\n", root, x, y)

			if tmp.maxn > x {
				y = x
				x = tmp.maxn
			} else if tmp.maxn > y {
				y = tmp.maxn
			}

			//	fmt.Printf("root2 = %d %d %d\n", root, x, y)

		}
	}

	d[root].maxn = max(d[root].maxn, d[root].sum)
	if x > -INF && y > -INF {
		d[root].ans = max(d[root].ans, x+y)
	}

	return d[root]

}

func main() {

	var n int

	b, _ := ioutil.ReadAll(os.Stdin)
	r := bytes.NewReader(b)

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

	a = make([]int64, n+1)
	d = make([]Node, n+1)
	vis = make([]bool, n+1)
	c = make([]int, n+1)

	first = make([]int, n+1)
	next = make([]int, 2*n+1)
	edges = make([]Edge, 2*n+1)

	cnt = 0

	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%v ", &a[i])
	}
	fmt.Fscanf(r, "%v\n", &a[n])

	var u, v int
	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%d %d\n", &u, &v)
		c[u]++
		c[v]++

		addEdge(u, v)
		addEdge(v, u)
	}

	root := 1

	for c[root] == 1 {
		vis[root] = true

		for i := first[root]; i != 0; i = next[i] {
			u = edges[i].y

			if !vis[u] {
				c[u] = c[u] - 1
				root = u
				break
			}
		}
	}

	//fmt.Printf("root = %d\n", root)

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

	if ans <= -INF {
		fmt.Printf("Impossible\n")
	} else {
		fmt.Printf("%v\n", ans)
	}

	return

}

package main

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

const minf int64 = -2000000000000

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

func Dfs(v int, vis []bool, price []int, dpOne, dpTwo, sum []int64, graph [][]int){
	vis[v]   = true
	sum[v]   = int64(price[v])
	dpOne[v] = minf
	dpTwo[v] = minf

	for _, x := range graph[v] {
		if vis[x] {
			continue
		}
		Dfs(x, vis, price, dpOne, dpTwo, sum, graph)
		sum[v]  += sum[x]
		dpOne[v] = Max(dpOne[v], dpOne[x])
		dpTwo[v] = Max(dpTwo[v], dpTwo[x])
	}

	second   := false
	secDpOne := minf

	for _, x :=range graph[v] {
		if dpOne[x] == dpOne[v] && !second {
			second = true
			continue
		}
		secDpOne = Max(dpOne[x], secDpOne)
	}

	dpTwo[v] = Max(dpTwo[v], dpOne[v] + secDpOne)
	dpOne[v] = Max(dpOne[v], sum[v])
}

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

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func prepare(){
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
}

func main() {
	prepare()

	var n, a, b int
	var graph   [][]int

	n = readInt()

	price     := make([]int,    n)
	dpOne     := make([]int64,  n)
	dpTwo     := make([]int64,  n)
	sum       := make([]int64,  n)
	visited   := make([]bool,   n)

	for i := 0; i < n; i++ {
		price[i] = readInt()
		graph    = append(graph, make([]int, 0))
	}

	for i := 0; i < n - 1; i++ {
		a = readInt() - 1
		b = readInt() - 1
		graph[a] = append(graph[a], b)
		graph[b] = append(graph[b], a)
	}

	Dfs(0, visited, price, dpOne, dpTwo, sum, graph)
	if dpTwo[0] * 2 < minf {
		fmt.Println("Impossible")
	} else {
		fmt.Println(dpTwo[0])
	}
}

package main

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

const MAX = 200010

type Edge struct {
	x, y int
}

var a []int64
var d []int64
var vis []bool
var c []int

var first []int
var next []int
var edges []Edge
var fa []int

var cnt int

func addEdge(u, v int) {
	cnt++
	edges[cnt].x = u
	edges[cnt].y = v

	next[cnt] = first[u]
	first[u] = cnt
}

func judge(n int) bool {
	for i := 1; i <= n; i++ {
		if c[i] > 1 {
			return true
		}
	}

	return false

}

func dp(root int) int64 {

	if vis[root] {
		return d[root]
	}

	d[root] = a[root]
	vis[root] = true

	for i := first[root]; i != 0; i = next[i] {
		tmp := edges[i]

		if !vis[tmp.y] {
			fa[tmp.y] = root
			d[root] += dp(tmp.y)
		}

	}

	return d[root]

}

func main() {

	var n int

	b, _ := ioutil.ReadAll(os.Stdin)
	r := bytes.NewReader(b)
	fmt.Fscanf(r, "%d\n", &n)

	a = make([]int64, n+1)
	d = make([]int64, n+1)
	vis = make([]bool, n+1)
	c = make([]int, n+1)

	first = make([]int, n+1)
	next = make([]int, 2*n+1)
	edges = make([]Edge, 2*n+1)
	fa = make([]int, n+1)

	cnt = 0

	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%v ", &a[i])
	}
	fmt.Fscanf(r, "%v\n", &a[n])

	var u, v int
	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%d %d\n", &u, &v)
		c[u]++
		c[v]++

		addEdge(u, v)
		addEdge(v, u)
	}

	if !judge(n) {
		fmt.Println("Impossible")
		return
	}

	dp(1)
	/*
		for i := 1; i <= n; i++ {
			fmt.Printf("%v ", fa[i])
		}
		fmt.Printf("\n")
	*/
	res1 := a[2]
	index := 2

	for i := 3; i <= n; i++ {
		if d[i] > res1 {
			res1 = d[i]
			index = i
		}
	}

	for i := 1; i <= n; i++ {
		vis[i] = false
	}

	for i := index; i != 0; i = fa[i] {
		vis[i] = true
	}

	var res2 int64

	for i := 2; i <= n; i++ {
		if !vis[i] {
			res2 = d[i]
			break
		}
	}

	for i := 2; i <= n; i++ {
		if !vis[i] {
			if d[i] > res2 {
				res2 = d[i]
			}
		}
	}

	fmt.Printf("%v\n", res1+res2)

	return

}

package main

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

const MAX = 200010

const INF = int64(200000000000000)

type Edge struct {
	x, y int
}

type Node struct {
	ans, maxn, sum int64
}

var a []int64
var d []Node
var vis []bool
var c []int

var first []int
var next []int
var edges []Edge

var cnt int

func addEdge(u, v int) {
	cnt++
	edges[cnt].x = u
	edges[cnt].y = v

	next[cnt] = first[u]
	first[u] = cnt
}

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

}

func dp(root int) Node {
	if vis[root] {
		return d[root]
	}

	d[root].ans = -INF
	d[root].maxn = a[root]
	d[root].sum = a[root]
	vis[root] = true

	x := -INF
	y := -INF

	for i := first[root]; i != 0; i = next[i] {
		u := edges[i].y
		if !vis[u] {
			tmp := dp(u)
			d[root].maxn = max(d[root].maxn, tmp.maxn)
			d[root].sum += tmp.sum

			d[root].ans = max(d[root].ans, tmp.ans)

			//fmt.Printf("root1 = %d %d %d\n", root, x, y)

			if tmp.maxn > x {
				y = x
				x = tmp.maxn
			} else if tmp.maxn > y {
				y = tmp.maxn
			}

			//	fmt.Printf("root2 = %d %d %d\n", root, x, y)

		}
	}

	d[root].maxn = max(d[root].maxn, d[root].sum)
	if x > -INF && y > -INF {
		d[root].ans = max(d[root].ans, x+y)
	}

	return d[root]

}

func main() {

	var n int

	b, _ := ioutil.ReadAll(os.Stdin)
	r := bytes.NewReader(b)

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

	a = make([]int64, n+1)
	d = make([]Node, n+1)
	vis = make([]bool, n+1)
	c = make([]int, n+1)

	first = make([]int, n+1)
	next = make([]int, 2*n+1)
	edges = make([]Edge, 2*n+1)

	cnt = 0

	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%v ", &a[i])
	}
	fmt.Fscanf(r, "%v\n", &a[n])

	var u, v int
	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%d %d\n", &u, &v)
		c[u]++
		c[v]++

		addEdge(u, v)
		addEdge(v, u)
	}

	root := 1

	for c[root] == 1 {
		vis[root] = true

		for i := first[root]; i != 0; i = next[i] {
			u = edges[i].y

			if !vis[u] {
				c[u] = c[u] - 1
				root = u
				break
			}
		}
	}

	//fmt.Printf("root = %d\n", root)

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

	if ans <= -INF {
		fmt.Printf("Impossible\n")
	} else {
		fmt.Printf("%v\n", ans)
	}

	return

}

package main

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

const MAX = 200010

const INF = int64(2000000000000000)

type Edge struct {
	x, y int
}

type Node struct {
	value, maxn int64
}

var a []int64
var d []Node
var vis []bool
var c []int

var first []int
var next []int
var edges []Edge

var cnt int

func addEdge(u, v int) {
	cnt++
	edges[cnt].x = u
	edges[cnt].y = v

	next[cnt] = first[u]
	first[u] = cnt
}

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

}

func dp(root int) Node {

	if vis[root] {
		return d[root]
	}

	d[root].maxn = -INF
	d[root].value = a[root]
	vis[root] = true

	for i := first[root]; i != 0; i = next[i] {
		u := edges[i].y

		if !vis[u] {
			tmp := dp(u)
			d[root].value += tmp.value
			d[root].maxn = max(d[root].maxn, tmp.maxn)
		}

	}

	d[root].maxn = max(d[root].maxn, d[root].value)

	return d[root]
}

func maxRes(root int) int64 {

	var index int

	res := -INF

	for i := first[root]; i != 0; i = next[i] {
		u := edges[i].y

		if !vis[u] {
			if d[u].maxn > res {
				res = d[u].maxn
				index = u
			}
		}
	}

	vis[index] = true
	return res

}

func main() {

	var n int

	b, _ := ioutil.ReadAll(os.Stdin)
	r := bytes.NewReader(b)

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

	a = make([]int64, n+1)
	d = make([]Node, n+1)
	vis = make([]bool, n+1)
	c = make([]int, n+1)

	first = make([]int, n+1)
	next = make([]int, 2*n+1)
	edges = make([]Edge, 2*n+1)

	cnt = 0

	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%v ", &a[i])
	}
	fmt.Fscanf(r, "%v\n", &a[n])

	var u, v int
	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%d %d\n", &u, &v)
		c[u]++
		c[v]++

		addEdge(u, v)
		addEdge(v, u)
	}

	dp(1)

	for i := 1; i <= n; i++ {
		vis[i] = false
	}

	root := 1

	for c[root] == 1 {
		vis[root] = true
		for i := first[root]; i != 0; i = next[i] {
			tmp := edges[i]

			if !vis[tmp.y] {
				c[tmp.y] = c[tmp.y] - 1
				root = tmp.y
				break
			}
		}
	}

	vis[root] = true

	ans := maxRes(root) + maxRes(root)

	if ans <= -INF {
		fmt.Printf("Impossible\n")
	} else {
		fmt.Printf("%v\n", ans)
	}

	return

}

package main

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

const MAX = 200010

const INF = int64(200000000000000)

type Edge struct {
	x, y int
}

type Node struct {
	value, maxn int64
}

var a []int64
var d []Node
var vis []bool
var c []int

var first []int
var next []int
var edges []Edge

var cnt int

func addEdge(u, v int) {
	cnt++
	edges[cnt].x = u
	edges[cnt].y = v

	next[cnt] = first[u]
	first[u] = cnt
}

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

}

func dp(root int) Node {

	if vis[root] {
		return d[root]
	}

	d[root].maxn = -INF
	d[root].value = a[root]
	vis[root] = true

	for i := first[root]; i != 0; i = next[i] {
		u := edges[i].y

		if !vis[u] {
			tmp := dp(u)
			d[root].value += tmp.value
			d[root].maxn = max(d[root].maxn, tmp.maxn)
		}

	}

	d[root].maxn = max(d[root].maxn, d[root].value)

	return d[root]
}

func maxRes(root int) int64 {

	var index int

	res := -INF

	for i := first[root]; i != 0; i = next[i] {
		u := edges[i].y

		if !vis[u] {
			if d[u].maxn > res {
				res = d[u].maxn
				index = u
			}
		}
	}

	vis[index] = true
	return res

}

func main() {

	var n int

	b, _ := ioutil.ReadAll(os.Stdin)
	r := bytes.NewReader(b)

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

	a = make([]int64, n+1)
	d = make([]Node, n+1)
	vis = make([]bool, n+1)
	c = make([]int, n+1)

	first = make([]int, n+1)
	next = make([]int, 2*n+1)
	edges = make([]Edge, 2*n+1)

	cnt = 0

	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%v ", &a[i])
	}
	fmt.Fscanf(r, "%v\n", &a[n])

	var u, v int
	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%d %d\n", &u, &v)
		c[u]++
		c[v]++

		addEdge(u, v)
		addEdge(v, u)
	}

	dp(1)

	for i := 1; i <= n; i++ {
		vis[i] = false
	}

	root := 1

	for c[root] == 1 {
		vis[root] = true
		for i := first[root]; i != 0; i = next[i] {
			tmp := edges[i]

			if !vis[tmp.y] {
				c[tmp.y] = c[tmp.y] - 1
				root = tmp.y
				break
			}
		}
	}

	vis[root] = true

	ans := maxRes(root) + maxRes(root)

	if ans <= -INF {
		fmt.Printf("Impossible\n")
	} else {
		fmt.Printf("%v\n", ans)
	}

	return

}

package main

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

const MAX = 200010

const INF = int64(200000000000000)

type Edge struct {
	x, y int
}

var a []int64
var d []int64
var vis []bool
var c []int

var first []int
var next []int
var edges []Edge
var fa []int

var cnt int

func addEdge(u, v int) {
	cnt++
	edges[cnt].x = u
	edges[cnt].y = v

	next[cnt] = first[u]
	first[u] = cnt
}

func judge(n int) bool {
	for i := 1; i <= n; i++ {
		if c[i] > 1 {
			return true
		}
	}

	return false

}

func dp(root int) int64 {

	if vis[root] {
		return d[root]
	}

	d[root] = a[root]
	vis[root] = true

	for i := first[root]; i != 0; i = next[i] {
		tmp := edges[i]

		if !vis[tmp.y] {
			fa[tmp.y] = root
			d[root] += dp(tmp.y)
		}

	}

	return d[root]

}

func main() {

	var n int

	b, _ := ioutil.ReadAll(os.Stdin)
	r := bytes.NewReader(b)
	fmt.Fscanf(r, "%d\n", &n)

	a = make([]int64, n+1)
	d = make([]int64, n+1)
	vis = make([]bool, n+1)
	c = make([]int, n+1)

	first = make([]int, n+1)
	next = make([]int, 2*n+1)
	edges = make([]Edge, 2*n+1)
	fa = make([]int, n+1)

	cnt = 0

	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%v ", &a[i])
	}
	fmt.Fscanf(r, "%v\n", &a[n])

	var u, v int
	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%d %d\n", &u, &v)
		c[u]++
		c[v]++

		addEdge(u, v)
		addEdge(v, u)
	}

	if !judge(n) {
		fmt.Println("Impossible")
		return
	}

	//fmt.Printf("root = %d\n", root)

	dp(1)

	for i := 1; i <= n; i++ {
		vis[i] = false
	}

	root := 1

	for c[root] == 1 {
		vis[root] = true
		for i := first[root]; i != 0; i = next[i] {
			tmp := edges[i]

			if !vis[tmp.y] {
				c[tmp.y] = c[tmp.y] - 1
				root = tmp.y
				//fmt.Printf("root = %d\n", root)
				break
			}
		}
	}

	vis[root] = true

	res1 := -INF

	var index int

	for i := 1; i <= n; i++ {
		if !vis[i] {
			if d[i] > res1 {
				res1 = d[i]
				index = i
			}
		}
	}

	for i := index; i != 0; i = fa[i] {
		vis[i] = true
	}

	res2 := -INF

	for i := 1; i <= n; i++ {
		if !vis[i] {
			if d[i] > res2 {
				res2 = d[i]
			}
		}
	}

	fmt.Printf("%v\n", res1+res2)

	return

}


Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.

Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.

NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example:  In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.

package main

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

var in = bufio.NewReaderSize(os.Stdin, 2<<16)

type elem struct {
	r, c, dist int
}

func main() {
	var n, m, p int
	fmt.Fscan(in, &n, &m, &p)
	speed := make([]int, p)
	for i := range speed {
		fmt.Fscan(in, &speed[i])
	}
	grid := make([][]byte, n)
	for i := range grid {
		var s string
		fmt.Fscan(in, &s)
		grid[i] = []byte(s)
	}

	ans := make([]int, p)
	queues := make([][]elem, p)
	for i := range grid {
		for j := range grid[i] {
			pl := grid[i][j] - '1'
			if pl < 0 || pl > 9 {
				continue
			}
			queues[pl] = append(queues[pl], elem{i, j, 0})
			ans[pl]++
		}
	}

	moved := true
	for round := 1; moved; round++ {
		moved = false
		for pl, q := range queues {
			for len(q) > 0 && q[0].dist < round*speed[pl] {
				v := q[0]
				q = q[1:]
				move := func(r, c int) {
					if grid[r][c] == '.' {
						grid[r][c] = byte(pl) + '1'
						ans[pl]++
						q = append(q, elem{r, c, v.dist + 1})
						moved = true
					}
				}
				if v.r > 0 {
					move(v.r-1, v.c)
				}
				if v.r+1 < n {
					move(v.r+1, v.c)
				}
				if v.c > 0 {
					move(v.r, v.c-1)
				}
				if v.c+1 < m {
					move(v.r, v.c+1)
				}
			}
			queues[pl] = q
		}
	}
	for i := range ans[1:] {
		fmt.Print(ans[i], " ")
	}
	fmt.Println(ans[p-1])
}

package main

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

type pInfo struct {
	step     int
	boundary map[[2]int]struct{}
	land     int
}

func expandCell(pi *pInfo, grids [][]rune, x, y, xp, yp int, f *bool, b map[[2]int]struct{}) {
	pi.land++
	grids[x][y] = rune('#')
	b[[2]int{x, y}] = struct{}{}
	*f = true
}

func expand(pi *pInfo, grids [][]rune, n, m int) (c bool) {
	for i := 0; i < pi.step; i++ {
		if len(pi.boundary) == 0 {
			return
		}
		nb := make(map[[2]int]struct{})
		for k := range pi.boundary {
			if k[0]+1 < n && grids[k[0]+1][k[1]] == rune('.') {
				expandCell(pi, grids, k[0]+1, k[1], k[0], k[1], &c, nb)
			}
			if k[0]-1 >= 0 && grids[k[0]-1][k[1]] == rune('.') {
				expandCell(pi, grids, k[0]-1, k[1], k[0], k[1], &c, nb)
			}
			if k[1]+1 < m && grids[k[0]][k[1]+1] == rune('.') {
				expandCell(pi, grids, k[0], k[1]+1, k[0], k[1], &c, nb)
			}
			if k[1]-1 >= 0 && grids[k[0]][k[1]-1] == rune('.') {
				expandCell(pi, grids, k[0], k[1]-1, k[0], k[1], &c, nb)
			}
		}
		pi.boundary = nb
	}
	return
}

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

	var n, m, p int
	fmt.Fscanln(reader, &n, &m, &p)
	ps := make([]*pInfo, p)
	grids := make([][]rune, n)

	line, err := reader.ReadString('\n')
	if err != nil {
		fmt.Println("read 1 error", err)
		return
	}
	strs := strings.Split(line[:len(line)-2], " ")
	for i, str := range strs {
		ps[i] = &pInfo{boundary: make(map[[2]int]struct{})}
		if ps[i].step, err = strconv.Atoi(str); err != nil {
			fmt.Println("read 2 error", err)
			return
		}
	}

	for i := 0; i < n; i++ {
		line, err = reader.ReadString('\n')
		if err != nil {
			fmt.Println("read 3 error", err)
			return
		}
		grids[i] = []rune(line[:len(line)-2])
		for j := 0; j < m; j++ {
			if grids[i][j] != rune('#') && grids[i][j] != rune('.') {
				pn := int(grids[i][j]) - 48
				ps[pn-1].boundary[[2]int{i, j}] = struct{}{}
				ps[pn-1].land++
			}
		}
	}

	for {
		canExpand := false
		for _, pi := range ps {
			r := expand(pi, grids, n, m)
			if r {
				canExpand = true
			}
		}
		if !canExpand {
			break
		}
	}

	res := []int{}
	for _, pi := range ps {
		res = append(res, pi.land)
	}
	fmt.Println(strings.Trim(strings.Join(strings.Fields(fmt.Sprint(res)), " "), "[]") + " ")
}

package main

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

type Point struct {
	x     int
	y     int
	color int
	step  int
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, m, p := 0, 0, 0
	fmt.Fscanf(in, "%d %d %d\n", &n, &m, &p)
	speed := make([]int, p)
	s := make([][]byte, n)
	for i := 0; i < p; i++ {
		fmt.Fscanf(in, "%d", &speed[i])
	}
	fmt.Fscanf(in, "\n")
	for i := 0; i < n; i++ {
		str := ""
		fmt.Fscanf(in, "%s\n", &str)
		s[i] = []byte(str)
		//fmt.Println(s[i])
	}
	potentials := make([][]Point, p)
	for i := 0; i < p; i++ {
		potentials[i] = make([]Point, 0)
	}
	for i := 0; i < p; i++ {
		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				if s[j][k] == '1'+byte(i) {
					newP := Point{j, k, i + 1, speed[i]}
					potentials[i] = append(potentials[i], newP)
				}
			}
		}
	}
	dx := []int{0, 1, 0, -1}
	dy := []int{1, 0, -1, 0}
	for true {
		end := true
		for i := 0; i < p; i++ {
			st := potentials[i]
			if len(st) != 0 {
				end = false
			}
			potentials[i] = make([]Point, 0)
			for len(st) > 0 {
				if st[0].step == 0 {
					potentials[i] = append(potentials[i], Point{st[0].x, st[0].y, st[0].color, speed[i]})
				} else {
					for j := 0; j < 4; j++ {
						nx := st[0].x + dx[j]
						ny := st[0].y + dy[j]
						if nx >= 0 && nx < n && ny >= 0 && ny < m && s[nx][ny] == '.' {
							s[nx][ny] = '1' + byte(i)
							st = append(st, Point{nx, ny, i, st[0].step - 1})
						}
					}
				}
				st = st[1:]
			}
		}
		if end {
			break
		}
	}
	ans := make([]int, p)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if s[i][j] >= '0' && s[i][j] <= '9' {
				ans[s[i][j]-'1']++
			}
		}
	}
	fmt.Fprintf(out, "%d", ans[0])
	for i := 1; i < p; i++ {
		fmt.Fprintf(out, " %d", ans[i])
	}
	fmt.Fprintf(out, "\n")
	return
}

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

package main

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

type pInfo struct {
	step     int
	boundary map[[2]int]struct{}
	land     int
}

func expandCell(pi *pInfo, grids [][]rune, x, y, xp, yp int, f *bool, b map[[2]int]struct{}) {
	pi.land++
	grids[x][y] = rune('#')
	b[[2]int{x, y}] = struct{}{}
	*f = true
}

func expand(pi *pInfo, grids [][]rune, n, m int) (c bool) {
	for i := 0; i < pi.step; i++ {
		if len(pi.boundary) == 0 {
			return
		}
		nb := make(map[[2]int]struct{})
		for k := range pi.boundary {
			if k[0]+1 < n && grids[k[0]+1][k[1]] == rune('.') {
				expandCell(pi, grids, k[0]+1, k[1], k[0], k[1], &c, nb)
			}
			if k[0]-1 >= 0 && grids[k[0]-1][k[1]] == rune('.') {
				expandCell(pi, grids, k[0]-1, k[1], k[0], k[1], &c, nb)
			}
			if k[1]+1 < m && grids[k[0]][k[1]+1] == rune('.') {
				expandCell(pi, grids, k[0], k[1]+1, k[0], k[1], &c, nb)
			}
			if k[1]-1 >= 0 && grids[k[0]][k[1]-1] == rune('.') {
				expandCell(pi, grids, k[0], k[1]-1, k[0], k[1], &c, nb)
			}
		}
		pi.boundary = nb
	}
	return
}

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

	var n, m, p int
	fmt.Fscanln(reader, &n, &m, &p)
	ps := make([]*pInfo, p)
	grids := make([][]rune, n)

	line, err := reader.ReadString('\n')
	if err != nil {
		return
	}
	strs := strings.Split(line[:len(line)-1], " ")
	for i, str := range strs {
		ps[i] = &pInfo{boundary: make(map[[2]int]struct{})}
		if ps[i].step, err = strconv.Atoi(str); err != nil {
			return
		}
	}

	for i := 0; i < n; i++ {
		line, err = reader.ReadString('\n')
		if err != nil {
			return
		}
		grids[i] = []rune(line[:len(line)-1])
		for j := 0; j < m; j++ {
			if grids[i][j] != rune('#') && grids[i][j] != rune('.') {
				pn := int(grids[i][j]) - 48
				ps[pn-1].boundary[[2]int{i, j}] = struct{}{}
				ps[pn-1].land++
			}
		}
	}

	for {
		canExpand := false
		for _, pi := range ps {
			r := expand(pi, grids, n, m)
			if r {
				canExpand = true
			}
		}
		if !canExpand {
			break
		}
	}

	res := []int{}
	for _, pi := range ps {
		res = append(res, pi.land)
	}
	fmt.Println(strings.Trim(strings.Join(strings.Fields(fmt.Sprint(res)), " "), "[]") + " ")
}

package main

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

type pInfo struct {
	step     int
	boundary map[[2]int]struct{}
	land     int
}

func expandCell(pi *pInfo, grids [][]rune, x, y, xp, yp int, f *bool, b map[[2]int]struct{}) {
	pi.land++
	grids[x][y] = rune('#')
	b[[2]int{x, y}] = struct{}{}
	*f = true
}

func expand(pi *pInfo, grids [][]rune, n, m int) (c bool) {
	for i := 0; i < pi.step; i++ {
		if len(pi.boundary) == 0 {
			return
		}
		nb := make(map[[2]int]struct{})
		for k := range pi.boundary {
			if k[0]+1 < n && grids[k[0]+1][k[1]] == rune('.') {
				expandCell(pi, grids, k[0]+1, k[1], k[0], k[1], &c, nb)
			}
			if k[0]-1 >= 0 && grids[k[0]-1][k[1]] == rune('.') {
				expandCell(pi, grids, k[0]-1, k[1], k[0], k[1], &c, nb)
			}
			if k[1]+1 < m && grids[k[0]][k[1]+1] == rune('.') {
				expandCell(pi, grids, k[0], k[1]+1, k[0], k[1], &c, nb)
			}
			if k[1]-1 >= 0 && grids[k[0]][k[1]-1] == rune('.') {
				expandCell(pi, grids, k[0], k[1]-1, k[0], k[1], &c, nb)
			}
		}
		pi.boundary = nb
	}
	return
}

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

	var n, m, p int
	fmt.Fscanln(reader, &n, &m, &p)
	ps := make([]*pInfo, p)
	grids := make([][]rune, n)

	line, err := reader.ReadString('\n')
	if err != nil {
		return
	}
	strs := strings.Split(line[:len(line)-1], " ")
	for i, str := range strs {
		ps[i] = &pInfo{boundary: make(map[[2]int]struct{})}
		if ps[i].step, err = strconv.Atoi(str); err != nil {
			return
		}
	}

	for i := 0; i < n; i++ {
		line, err = reader.ReadString('\n')
		if err != nil {
			return
		}
		grids[i] = []rune(line[:len(line)-1])
		for j := 0; j < m; j++ {
			if grids[i][j] != rune('#') && grids[i][j] != rune('.') {
				pn := int(grids[i][j]) - 48
				ps[pn-1].boundary[[2]int{i, j}] = struct{}{}
				ps[pn-1].land++
			}
		}
	}

	for {
		canExpand := false
		for _, pi := range ps {
			r := expand(pi, grids, n, m)
			if r {
				canExpand = true
			}
		}
		if !canExpand {
			break
		}
	}

	res := []int{}
	for _, pi := range ps {
		res = append(res, pi.land)
	}
	fmt.Println(strings.Trim(strings.Join(strings.Fields(fmt.Sprint(res)), " "), "[]"))
}

package main

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

type pInfo struct {
	step     int
	boundary map[[2]int]struct{}
	land     int
}

func expandCell(pi *pInfo, grids [][]rune, x, y, xp, yp int, f *bool, b map[[2]int]struct{}) {
	pi.land++
	grids[x][y] = rune('#')
	b[[2]int{x, y}] = struct{}{}
	*f = true
}

func expand(pi *pInfo, grids [][]rune, n, m int) (c bool) {
	for i := 0; i < pi.step; i++ {
		if len(pi.boundary) == 0 {
			return
		}
		nb := make(map[[2]int]struct{})
		for k := range pi.boundary {
			if k[0]+1 < n && grids[k[0]+1][k[1]] == rune('.') {
				expandCell(pi, grids, k[0]+1, k[1], k[0], k[1], &c, nb)
			}
			if k[0]-1 >= 0 && grids[k[0]-1][k[1]] == rune('.') {
				expandCell(pi, grids, k[0]-1, k[1], k[0], k[1], &c, nb)
			}
			if k[1]+1 < m && grids[k[0]][k[1]+1] == rune('.') {
				expandCell(pi, grids, k[0], k[1]+1, k[0], k[1], &c, nb)
			}
			if k[1]-1 >= 0 && grids[k[0]][k[1]-1] == rune('.') {
				expandCell(pi, grids, k[0], k[1]-1, k[0], k[1], &c, nb)
			}
		}
		pi.boundary = nb
	}
	return
}

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

	var n, m, p int
	fmt.Fscanln(reader, &n, &m, &p)
	ps := make([]*pInfo, p)
	grids := make([][]rune, n)

	line, err := reader.ReadString('\n')
	if err != nil {
		return
	}
	strs := strings.Split(line[:len(line)-1], " ")
	for i, str := range strs {
		ps[i] = &pInfo{boundary: make(map[[2]int]struct{})}
		if ps[i].step, err = strconv.Atoi(str); err != nil {
			return
		}
	}

	for i := 0; i < n; i++ {
		line, err = reader.ReadString('\n')
		if err != nil {
			return
		}
		grids[i] = []rune(line[:len(line)-1])
		for j := 0; j < m; j++ {
			if grids[i][j] != rune('#') && grids[i][j] != rune('.') {
				pn := int(grids[i][j]) - 48
				ps[pn-1].boundary[[2]int{i, j}] = struct{}{}
				ps[pn-1].land++
			}
		}
	}

	for {
		canExpand := false
		for _, pi := range ps {
			r := expand(pi, grids, n, m)
			if r {
				canExpand = true
			}
		}
		if !canExpand {
			break
		}
	}

	res := []int{}
	for _, pi := range ps {
		res = append(res, pi.land)
	}
	fmt.Printf("#%s#", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(res)), " "), "[]")+" ")
}


Allen is hosting a formal dinner party. $$$2n$$$ people come to the event in $$$n$$$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $$$2n$$$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic.Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$), the number of pairs of people. The second line contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$. For each $$$i$$$ with $$$1 \le i \le n$$$, $$$i$$$ appears exactly twice. If $$$a_j = a_k = i$$$, that means that the $$$j$$$-th and $$$k$$$-th people in the line form a couple.

Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions.

NoteIn the first sample case, we can transform $$$1 1 2 3 3 2 4 4 \rightarrow 1 1 2 3 2 3 4 4 \rightarrow 1 1 2 2 3 3 4 4$$$ in two steps. Note that the sequence $$$1 1 2 3 3 2 4 4 \rightarrow 1 1 3 2 3 2 4 4 \rightarrow 1 1 3 3 2 2 4 4$$$ also works in the same number of steps.The second sample case already satisfies the constraints; therefore we need $$$0$$$ swaps.

package main

import (
	"fmt"
)

func main() {
	var n int
	var arr [202]int

	fmt.Scan(&n)
	for i := 1; i <= 2*n; i++ {
		fmt.Scan(&arr[i])
	}

	cnt := 0
	for i := 1; i <= 2*n; i += 2 {
		for j := i + 1; j <= 2*n; j++ {

			if arr[i] == arr[j] {
				for l := j; l > i + 1; l-- {
					arr[l], arr[l - 1] = arr[l - 1], arr[l]
					cnt++
				}

				break
			}
		}
	}

	fmt.Println(cnt)

}


The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception.Vasily knows that the best present is (no, it's not a contest) money. He's put n empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided to put ai coins to the i-th wallet from the left.Vasily is a very busy man, so the money are sorted into the bags by his robot. Initially, the robot stands by the leftmost wallet in the row. The robot can follow instructions of three types: go to the wallet that is to the left of the current one (if such wallet exists), go to the wallet that is to the right of the current one (if such wallet exists), put a coin to the current wallet. Due to some technical malfunctions the robot cannot follow two "put a coin" instructions in a row.Vasily doesn't want to wait for long, so he wants to write a program for the robot that contains at most 106 operations (not necessarily minimum in length) the robot can use to put coins into the wallets. Help him.

The first line contains integer n (2 ≤ n ≤ 300) — the number of wallets. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 300). It is guaranteed that at least one ai is positive.

Print the sequence that consists of k (1 ≤ k ≤ 106) characters, each of them equals: "L", "R" or "P". Each character of the sequence is an instruction to the robot. Character "L" orders to move to the left, character "R" orders to move to the right, character "P" orders the robot to put a coin in the wallet. The robot is not allowed to go beyond the wallet line. In other words, you cannot give instructions "L" if the robot is at wallet 1, or "R" at wallet n. As a result of the performed operations, the i-th wallet from the left must contain exactly ai coins. If there are multiple answers, you can print any of them.

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	ans := make([]byte, 0, 1e6)
	a := make([]int, n)
	for i := range a {
		fmt.Scan(&a[i])
	}
	for i := range a[1:] {
		if i > 0 {
			ans = append(ans, 'R')
		}
		for a[i] > 0 {
			ans = append(ans, 'P')
			a[i]--
			if a[i] != 0 {
				if a[i+1] != 0 {
					ans = append(ans, 'R', 'P', 'L')
					a[i+1]--
				} else {
					ans = append(ans, 'R', 'L')
				}
			}
		}
	}
	for a[n-1] != 0 {
		ans = append(ans, 'R', 'P', 'L')
		a[n-1]--
	}
	fmt.Printf("%s\n", ans)
}

package main

import (
	"bytes"
	"fmt"
)

func DistributeCoins(numWallet int, coinsQtyPerWallet []int) {
	actions := make([]string, numWallet)
	i := 0
	for {
		if coinsQtyPerWallet[i] != 0 {
			actions = append(actions, "P")
			coinsQtyPerWallet[i] -= 1
		}
		if coinsQtyPerWallet[i] != 0 {
			if i == (numWallet - 1) {
				actions = append(actions, "LR")
			} else {
				actions = append(actions, "RL")
			}
		} else if coinsQtyPerWallet[i] == 0 {
			if i < (numWallet - 1) {
				actions = append(actions, "R")
				i++
			} else {
				break
			}
		}
	}
	var buffer bytes.Buffer
	for i := 0; i < len(actions); i++ {
		buffer.WriteString(actions[i])
	}
	fmt.Println(buffer.String())
}

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

	coinsQtyPerWallet := make([]int, numWallets)
	for i := 0; i < numWallets; i++ {
		fmt.Scan(&coinsQtyPerWallet[i])
	}

	DistributeCoins(numWallets, coinsQtyPerWallet)
}

package main
import (
	"fmt"
	"bufio"
	"os"
)
func main() {
	var n,nw int
	sum:=0
	fmt.Scan(&n)
	m := make([]int,500)
	out := bufio.NewWriter(os.Stdout)

	for i:=0;i<n;i++ {
		fmt.Scan(&m[i])
		sum += m[i]
	}
	for  {
		if m[nw]!=0 {
			out.WriteRune('P')
			m[nw]--
			sum--
			if sum==0 {
				break
			}
		}
		if nw==(n-1) || nw !=0 && m[nw-1]!=0 {
			out.WriteRune('L')
			nw--
		} else {
			out.WriteRune('R')
			nw++
		}
	}
	out.Flush()
	fmt.Println()
}

package main

import "fmt"

func main() {
    var n int
    var a [305]int
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        fmt.Scan(&a[i])
    }
    pos, length := 0, n-1
    for pos < length {
        if a[pos] > 0 {
            fmt.Print("P")
            a[pos]--
        }
        fmt.Print("R")
        if a[pos+1] > 0 {
            fmt.Print("P")
            a[pos+1]--
        }
        fmt.Print("L")
        for a[pos] == 0 {
            fmt.Print("R")
            pos++
            if pos == length { break }
        }
    }
    for a[length] > 0 {
        fmt.Print("P")
        a[length]--
        if a[length] > 0 { fmt.Print("LR") }
    }
    fmt.Println()
}

package main

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

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &a[i])
	}
	ch := true
	put := func(s string) {
		fmt.Fprint(writer, s)
	}
	step := func(i int) {
		if a[i] > 0 {
			a[i]--
			put("P")
			ch = true
		}
	}
	for ch {
		ch = false
		for i := 0; i < n-1; i++ {
			step(i)
			put("R")
		}
		for i := n-1; i > 0; i-- {
			step(i)
			put("L")
		}
	}
	fmt.Fprintln(writer)
}

package main

import (
	"fmt"
)

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

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

	var f int = 0
	var p int = 0
	var b bool = true

	for f < n {
		var c byte
		switch {
		case p < f:
			c = 'R'
			p += 1
			b = true
		case p == f:
			if a[p] == 0 {
				f += 1
			}
			if b && a[p] > 0 {
				c = 'P'
				a[p] -= 1
				b = false
				if a[p] == 0 {
					f += 1
				}
			} else {
				if p != n - 1 {
					c = 'R'
					p += 1
				} else {
					c = 'L'
					p -= 1
				}
				b = true
			}
		case p > f:
			if b && a[p] > 0 {
				c = 'P'
				a[p] -= 1
				b = false
			} else {
				if p != 0 {
					c = 'L'
					p -= 1
				} else {
					// never reach
					c = 'R'
					p += 1
				}
				b = true
			}
		}
		fmt.Printf("%c", c)
	}
	fmt.Println("")
}

package main
import (
	"fmt"
)
func main() {
	var n int
	fmt.Scan(&n)
	fmt.Println((n*n+1)/2)
	for i:=0;i<n;i++ {
		for j:=0;j<n;j++ {
			if (i+j)%2==0 {
				fmt.Print(".")
			}else {fmt.Print("C")
			}

		}
		fmt.Println()
	}
}

package main
import (
	"fmt"
)
func main() {
	var n int
	fmt.Scan(&n)
	fmt.Println((n*n+1)/2)
	for i:=0;i<n;i++ {
		for j:=0;j<n;j++ {
			if (i+j)%2==0 {
				fmt.Print(".")
			}else {fmt.Print("C")
			}
			fmt.Println()
		}
	}
}

package main

import "fmt"

func main() {
    var n int
    var a [305]int
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        fmt.Scan(&a[i])
    }
    l, r, pos, dir := 0, n-1, 0, 1
    for l < r {
        if a[pos] > 0 {
            fmt.Print("P")
            a[pos]--
        } else if pos == l {
            l++
        } else if pos == r {
            r--
        }

        if dir == 1 { fmt.Print("R") } else { fmt.Print("L") }
        pos += dir
        if (pos == l) {
            dir = 1
        } else if (pos == r) {
            dir = -1
        }
    }
    fmt.Println()
}

package main

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

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &a[i])
	}
	ans := ""
	ch := true
	put := func(s string) {
		fmt.Fprint(writer, s)
	}
	step := func(i int) {
		if a[i] > 0 {
			a[i]--
			put("P")
			ch = true
		}
	}
	for ch {
		ch = false
		for i := 0; i < n-1; i++ {
			step(i)
			put("R")
		}
		for i := n-1; i > 0; i-- {
			step(i)
			put("L")
		}
	}
	fmt.Println(ans)
}