A palindrome is a string $$$t$$$ which reads the same backward as forward (formally, $$$t[i] = t[|t| + 1 - i]$$$ for all $$$i \in [1, |t|]$$$). Here $$$|t|$$$ denotes the length of a string $$$t$$$. For example, the strings 010, 1001 and 0 are palindromes.You have $$$n$$$ binary strings $$$s_1, s_2, \dots, s_n$$$ (each $$$s_i$$$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you:  choose four integer numbers $$$x, a, y, b$$$ such that $$$1 \le x, y \le n$$$ and $$$1 \le a \le |s_x|$$$ and $$$1 \le b \le |s_y|$$$ (where $$$x$$$ and $$$y$$$ are string indices and $$$a$$$ and $$$b$$$ are positions in strings $$$s_x$$$ and $$$s_y$$$ respectively),  swap (exchange) the characters $$$s_x[a]$$$ and $$$s_y[b]$$$. What is the maximum number of strings you can make palindromic simultaneously?

The first line contains single integer $$$Q$$$ ($$$1 \le Q \le 50$$$) — the number of test cases. The first line on each test case contains single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of binary strings you have. Next $$$n$$$ lines contains binary strings $$$s_1, s_2, \dots, s_n$$$ — one per line. It's guaranteed that $$$1 \le |s_i| \le 50$$$ and all strings constist of zeroes and/or ones.

Print $$$Q$$$ integers — one per test case. The $$$i$$$-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the $$$i$$$-th test case.

NoteIn the first test case, $$$s_1$$$ is palindrome, so the answer is $$$1$$$.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make $$$s_1 = \text{0110}$$$, $$$s_2 = \text{111111}$$$ and $$$s_3 = \text{010000}$$$.In the third test case we can make both strings palindromic. For example, $$$s_1 = \text{11011}$$$ and $$$s_2 = \text{100001}$$$.In the last test case $$$s_2$$$ is palindrome and you can make $$$s_1$$$ palindrome, for example, by swapping $$$s_1[2]$$$ and $$$s_1[3]$$$.

package main

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

/* solution */

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

func solveOne() {
	n := readInt()
	var zero, one, cap int
	for i := 0; i < n; i++ {
		s := read()
		if (len(s))%2 == 1 {
			cap++
		}
		for j := 0; j < len(s); j++ {
			if s[j] == '0' {
				zero = 1 - zero
			} else {
				one = 1 - one
			}
		}
	}

	cap -= zero + one
	if cap >= 0 {
		cap = 0
	} else {
		cap = -1
	}

	printInt(n + cap)

}

/* stubs */

func main() {

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

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

	reader = bufio.NewScanner(f)

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

	reader.Split(bufio.ScanLines)

	solve()

}

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

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

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

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

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

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

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	q := 0
	fmt.Fscanf(in, "%d\n", &q)
	res := make([]int, q)
	var wg sync.WaitGroup
	wg.Add(q)
	for i := 0; i < q; i++ {
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		strs := make([][]byte, n)
		allEven := true
		zeros, ones := 0, 0
		for _, s := range strs {
			s, _ = in.ReadBytes('\n')
			if len(s)%2 == 1 {
				allEven = false
			}
			for _, c := range s {
				if c == '0' {
					zeros++
				}
				if c == '1' {
					ones++
				}
			}
		}
		go func(id int, z, o int, ae bool, en int) {
		  	defer wg.Done()
			if ae && z%2 == 1 {
				res[id] = en - 1
			} else {
				res[id] = en
			}
		}(i, zeros, ones, allEven, n)
	}
	wg.Wait()
	for _, s := range res {
		fmt.Println(s)
	}
}

package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

	return s
}

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

var q int
var n int
var S [][]rune

func main() {
	q = ReadInt()

	for i := 0; i < q; i++ {
		n = ReadInt()
		S = [][]rune{}
		for j := 0; j < n; j++ {
			S = append(S, ReadRuneSlice())
		}

		one, zero := 0, 0
		for j := 0; j < n; j++ {
			for k := 0; k < len(S[j]); k++ {
				if S[j][k] == '1' {
					one++
				} else {
					zero++
				}
			}
		}

		evens := []int{}
		odds := []int{}
		for j := 0; j < n; j++ {
			if len(S[j])%2 == 0 {
				evens = append(evens, len(S[j]))
			} else {
				odds = append(odds, len(S[j]))
			}
		}
		sort.Sort(sort.IntSlice(evens))
		sort.Sort(sort.IntSlice(odds))

		ans := solve(evens, odds, one, zero)
		fmt.Println(ans)
	}
}

func solve(evens, odds []int, one, zero int) int {
	ans := 0

	// 偶数から
	for i := 0; i < len(evens); i++ {
		enum := evens[i]
		for enum > 0 {
			if one < 2 && zero < 2 {
				break
			}

			enum -= 2
			if one > zero {
				one -= 2
			} else {
				zero -= 2
			}
		}

		if enum == 0 {
			ans++
		}
	}

	// 次に奇数
	for i := 0; i < len(odds); i++ {
		onum := odds[i]
		if one == 0 && zero == 0 {
			break
		}
		onum--
		if one%2 == 1 {
			one--
		} else {
			zero--
		}

		// onumは偶数が確定
		for onum > 0 {
			if one < 2 && zero < 2 {
				break
			}

			onum -= 2
			if one > zero {
				one -= 2
			} else {
				zero -= 2
			}
		}

		if onum == 0 {
			ans++
		}
	}

	return ans
}

func sub(L []int, one, zero int) int {
	ans := 0
	for j := 0; j < len(L); j++ {
		l := L[j]

		for l > 0 {
			if l >= 2 {
				l -= 2
				if one > zero {
					if one-2 < 0 {
						return ans
					}
					one -= 2
				} else {
					if zero-2 < 0 {
						return ans
					}
					zero -= 2
				}
			} else {
				l--
				if one > zero {
					if one-1 < 0 {
						return ans
					}
					one--
				} else {
					if zero-1 < 0 {
						return ans
					}
					zero--
				}
			}
		}

		ans++
	}

	return ans
}

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

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

package main

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

type point struct {
	x, y int
}

var ans int64

const (
	mod = int(1e9 + 7)
)

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

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()
	tt := 1
	fmt.Fscanf(in, "%d\n", &tt)
	for ii := 0; ii < tt; ii++ {
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		s := ""
		a := make([]int, n)
		c1 := 0
		c0 := 0
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%s\n", &s)
			a[i] = len(s)
			for j := 0; j < a[i]; j++ {
				if s[j] == '0' {
					c0++
				} else {
					c1++
				}
			}
		}
		sort.Ints(a)
		d0 := c0 / 2
		d1 := c1 / 2
		d := d0 + d1
		ans := 0
		for i := 0; i < n; i++ {
			if a[i]%2 == 0 {
				if d >= a[i]/2 {
					ans++
				}
				d -= a[i] / 2
			} else {
				ans++
			}
		}
		fmt.Fprintf(out, "%d\n", ans)
	}
	return
}

func help(i int, n int, total int, t []int, g []int, cur int, c1, c2, c3 int, remaining int) {
	//fmt.Println(i, cur)
	if i == n {
		if cur == total {
			cal(c1, c2, c3)
		}
		return
	}
	if cur > total {
		return
	}
	if cur+remaining < total {
		return
	}
	switch g[i] {
	case 1:
		help(i+1, n, total, t, g, cur+t[i], c1+1, c2, c3, remaining-t[i])
	case 2:
		help(i+1, n, total, t, g, cur+t[i], c1, c2+1, c3, remaining-t[i])
	case 3:
		help(i+1, n, total, t, g, cur+t[i], c1, c2, c3+1, remaining-t[i])
	}
	help(i+1, n, total, t, g, cur, c1, c2, c3, remaining-t[i])
}

func cal(c1, c2, c3 int) {
	a := []int{c1, c2, c3}
	sort.Ints(a)
	tmp := int64(try(c1, c2, c3, 0))
	tmp %= int64(mod)
	for i := 1; i <= c1; i++ {
		tmp *= int64(i)
		tmp %= int64(mod)
	}
	for i := 1; i <= c2; i++ {
		tmp *= int64(i)
		tmp %= int64(mod)
	}
	for i := 1; i <= c3; i++ {
		tmp *= int64(i)
		tmp %= int64(mod)
	}
	ans += tmp
	ans %= int64(mod)
}

func try(a, b, c int, last int) int64 {
	if a == 0 && b == 0 && c == 0 {
		return 1
	}
	if a < 0 || b < 0 || c < 0 {
		return 0
	}
	if last == 0 {
		return try(a-1, b, c, 1) + try(a, b-1, c, 2) + try(a, b, c-1, 3)
	}
	if last == 1 {
		return try(a, b-1, c, 2) + try(a, b, c-1, 3)
	}
	if last == 2 {
		return try(a-1, b, c, 1) + try(a, b, c-1, 3)
	}
	return try(a-1, b, c, 1) + try(a, b-1, c, 2)
}

package main

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

func GetReaderWriter() (*bufio.Reader, *bufio.Writer) {
	l := os.Getenv("LOCAL_DEBUG")
	reader := io.Reader(os.Stdin)
	writer := io.Writer(os.Stdout)
	if l != "" {
		bs, _ := ioutil.ReadFile("in.txt")
		reader = bytes.NewBuffer(bs)
	}
	return bufio.NewReader(reader), bufio.NewWriter(writer)
}

func main() {
	reader, writer := GetReaderWriter()
	defer writer.Flush()
	var i, q, n, j int64
	_, _ = Fscanf(reader, "%d\n", &q)

	for q > 0 {
		q--
		_, _ = Fscanf(reader, "%d\n", &n)
		s := make([]string, n)
		ll := make([]int64, n)
		s0 := int64(0)
		s1 := int64(0)
		te := int64(0)
		to := int64(0)
		for i = 0; i < n; i++ {
			_, _ = Fscanf(reader, "%s\n", &s[i])
			ll[i] = int64(len(s[i]))
			for j = 0; j < int64(len(s[i])); j++ {
				if s[i][j] == '0' {
					s0++
				} else {
					s1++
				}
			}
			if len(s[i])%2 == 0 {
				te++
			} else {
				to++
			}
		}
		// sort.Slice(ll, func(i, j int) bool { return ll[i] < ll[j] })
		if to == 0 {
			if 1 == s0%2 {
				n--
			}
		}
		_, _ = Fprintf(writer, "%d\n", n)
	}
}

package main

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

type WordScanner struct {
	*bufio.Scanner
}

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

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

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

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

func main() {
	ws := NewWordScanner()
	Q := ws.NextInt()
	for ; Q > 0; Q-- {
		n := ws.NextInt()
		s := []string{}
		for ; n > 0; n-- {
			s = append(s, ws.NextString())
		}
		fmt.Println(sol(s))
	}
}

func sol(sl []string) int {
	nOnes := 0
	nZeroes := 0
	toFill := 0
	for _, s := range sl {
		if len(s)%2 == 0 {
			toFill += len(s)
		}
		for _, r := range s {
			if r == '1' {
				nOnes++
			} else {
				nZeroes++
			}
		}
	}
	totalFill := (nOnes / 2 * 2) + (nZeroes / 2 * 2)
	if totalFill >= toFill {
		return len(sl)
	}
	return len(sl) - 1
}

package main

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

const INFINITY = math.MaxInt32/2 - 1

func exec(stdin *Stdin, stdout *Stdout) {
	for q := stdin.ReadInt(); q > 0; q-- {
		s := []string{}
		for n := stdin.ReadInt(); n > 0; n-- {
			s = append(s, stdin.Read())
		}

		allEven := true
		for _, c := range s {
			if len(c)%2 != 0 {
				allEven = false
			}
		}

		zero := 0
		one := 0
		for _, c := range s {
			for _, d := range c {
				if d == '0' {
					zero++
				} else {
					one++
				}
			}
		}

		if allEven && zero%2 != 0 && one%2 != 0 {
			stdout.Println(len(s) - 1)
		} else {
			stdout.Println(len(s))
		}
	}
}

func main() {
	stdout := NewStdout()
	defer stdout.Flush()
	exec(NewStdin(bufio.ScanWords), stdout)
}

type Stdin struct {
	stdin *bufio.Scanner
}

func NewStdin(split bufio.SplitFunc) *Stdin {
	s := Stdin{bufio.NewScanner(os.Stdin)}
	s.stdin.Split(split)
	s.stdin.Buffer(make([]byte, bufio.MaxScanTokenSize), INFINITY)
	return &s
}

func (s *Stdin) Read() string {
	s.stdin.Scan()
	return s.stdin.Text()
}

func (s *Stdin) ReadInt() int {
	n, _ := strconv.Atoi(s.Read())
	return n
}

func (s *Stdin) ReadInt64() int64 {
	n, _ := strconv.ParseInt(s.Read(), 10, 64)
	return n
}

func (s *Stdin) ReadFloat64() float64 {
	n, _ := strconv.ParseFloat(s.Read(), 64)
	return n
}

func (s *Stdin) ReadIntSlice(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadInt()
	}
	return a
}

func (s *Stdin) ReadStringSlice(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = s.Read()
	}
	return a
}

func (s *Stdin) ReadFloat64Slice(n int) []float64 {
	a := make([]float64, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadFloat64()
	}
	return a
}

func (s *Stdin) ReadInt64Slice(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadInt64()
	}
	return a
}

type Stdout struct {
	stdout *bufio.Writer
}

func NewStdout() *Stdout {
	return &Stdout{bufio.NewWriter(os.Stdout)}
}

func (s *Stdout) Flush() {
	s.stdout.Flush()
}

func (s *Stdout) Println(a ...interface{}) {
	fmt.Fprintln(s.stdout, a...)
}

func Min(a int, b ...int) int {
	for _, v := range b {
		if v < a {
			a = v
		}
	}
	return a
}

func Max(a int, b ...int) int {
	for _, v := range b {
		if a < v {
			a = v
		}
	}
	return a
}

func Abs(x int) int {
	if x > 0 {
		return x
	} else {
		return x * -1
	}
}

func Pow(x, y int) int {
	z := 1
	for y > 0 {
		if y%2 == 0 {
			x *= x
			y /= 2
		} else {
			z *= x
			y -= 1
		}
	}
	return z
}

func IsPrime(x int) bool {
	if x < 2 {
		return false
	}

	for i := 2; i*i <= x; i++ {
		if x%i == 0 {
			return false
		}
	}
	return true
}

func Gcd(x, y int) int {
	if x < y {
		x, y = y, x
	}

	for y > 0 {
		x, y = y, x%y
	}

	return x
}

func Lcm(x, y int) int {
	return x * y / Gcd(x, y)
}

func CeilDiv(x, y int) int {
	if x%y == 0 {
		return x / y
	} else {
		return x/y + 1
	}
}

func LCS(s, t string) string {
	n := len(s)
	m := len(t)
	dp := make([][]int, n+1)
	for i := 0; i <= n; i++ {
		dp[i] = make([]int, m+1)
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			if s[i-1] == t[j-1] {
				dp[i][j] = dp[i-1][j-1] + 1
			} else {
				dp[i][j] = Max(dp[i-1][j], dp[i][j-1])
			}
		}
	}

	x := n
	y := m
	u := make([]byte, dp[n][m])
	i := dp[n][m] - 1
	for x > 0 && y > 0 {
		if dp[x][y] == dp[x-1][y] {
			x--
		} else if dp[x][y] == dp[x][y-1] {
			y--
		} else {
			x--
			y--
			u[i] = s[x]
			i--
		}
	}

	return string(u)
}

// [0..n) から r個選んだ組合せを生成する。
// r < 0 の場合はすべての組合せを生成する。
func Combinations(n int, r int) [][]int {
	a := [][]int{}
	for i := uint(0); i < (1 << uint(n)); i++ {
		b := []int{}
		for j := uint(0); j < uint(n); j++ {
			if i&(uint(1)<<j) != 0 {
				b = append(b, int(j))
			}
		}

		if r < 0 || len(b) == r {
			a = append(a, b)
		}
	}
	return a
}

// [0..n)の順列を生成する。
func Permutations(n int) [][]int {
	type e struct {
		bit uint
		a   []int
	}

	q := []*e{}
	for i := 0; i < n; i++ {
		q = append(q, &e{bit: 1 << uint(i), a: []int{i}})
	}

	p := [][]int{}
	for x := 0; x < len(q); x++ {
		cur := q[x]
		if cur.bit == (1<<uint(n) - 1) {
			p = append(p, cur.a)
			continue
		}

		for i := 0; i < n; i++ {
			if cur.bit&(1<<uint(i)) != 0 {
				continue
			}

			m := len(cur.a) + 1
			b := make([]int, m)
			copy(b, cur.a)
			b[m-1] = i
			q = append(q, &e{bit: cur.bit | (1 << uint(i)), a: b})
		}
	}
	return p
}

func ReverseSlice(v interface{}) {
	if reflect.TypeOf(v).Kind() == reflect.Slice {
		slice := reflect.ValueOf(v)
		for i1, n := 0, slice.Len(); i1 < n/2; i1++ {
			i2 := n - i1 - 1
			v1 := reflect.ValueOf(slice.Index(i1).Interface())
			slice.Index(i1).Set(slice.Index(i2))
			slice.Index(i2).Set(v1)
		}
	}
}

func ReverseString(s string) string {
	t := []rune(s)
	ReverseSlice(t)
	return string(t)
}

func ToStringSlice(slice interface{}) []string {
	// 本来はerrを返却すべき。 利用する側(=自分)は引数がsliceであることを知っている。
	if reflect.TypeOf(slice).Kind() != reflect.Slice {
		panic(fmt.Sprintf("%v is not slice", slice))
	}

	src := reflect.ValueOf(slice)
	n := src.Len()
	dst := make([]string, n)
	for i := 0; i < n; i++ {
		dst[i] = fmt.Sprintf("%v", src.Index(i))
	}
	return dst
}

func CreateMatrix(x, y int) [][]int {
	matrix := make([][]int, x)
	for i := 0; i < x; i++ {
		matrix[i] = make([]int, y)
	}
	return matrix
}

func Min64(a int64, b ...int64) int64 {
	for _, v := range b {
		if v < a {
			a = v
		}
	}
	return a
}

func Max64(a int64, b ...int64) int64 {
	for _, v := range b {
		if a < v {
			a = v
		}
	}
	return a
}

func Abs64(x int64) int64 {
	if x > 0 {
		return x
	} else {
		return x * -1
	}
}

func Pow64(x, y int64) int64 {
	z := int64(1)
	for y > 0 {
		if y%2 == 0 {
			x *= x
			y /= 2
		} else {
			z *= x
			y--
		}
	}
	return z
}

func IsPrime64(x int64) bool {
	if x < 2 {
		return false
	}

	for i := int64(2); i*i <= x; i++ {
		if x%i == 0 {
			return false
		}
	}
	return true
}

func Gcd64(x, y int64) int64 {
	if x < y {
		x, y = y, x
	}

	for y > 0 {
		x, y = y, x%y
	}

	return x
}

func Lcm64(x, y int64) int64 {
	return x * y / Gcd64(x, y)
}

func CeilDiv64(x, y int64) int64 {
	if x%y == 0 {
		return x / y
	} else {
		return x/y + 1
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	q := 0
	fmt.Fscanf(in, "%d\n", &q)
	res := make([]int, q)
	var wg sync.WaitGroup
	wg.Add(q)
	for i := 0; i < q; i++ {
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		strs := make([][]byte, n)
		allEven := true
		zeros, ones := 0, 0
		for _, s := range strs {
			s, _ = in.ReadBytes('\n')
			if len(s)%2 == 0 {
				allEven = false
			}
			for _, c := range s {
				if c == '0' {
					zeros++
				}
				if c == '1' {
					ones++
				}
			}
		}
		go func(id int, zeros, ones int, allEven bool, n int) {
			defer wg.Done()
			if allEven && zeros%2 == 1 {
				res[id] = n - 1
			} else {
				res[id] = n
			}
		}(i, zeros, ones, allEven, n)
	}
	wg.Wait()
	for _, s := range res {
		fmt.Println(s)
	}
}

package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

	return s
}

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

var q int
var n int
var S [][]rune

func main() {
	q = ReadInt()

	for i := 0; i < q; i++ {
		n = ReadInt()
		S = [][]rune{}
		for j := 0; j < n; j++ {
			S = append(S, ReadRuneSlice())
		}

		one, zero := 0, 0
		L := []int{}
		for j := 0; j < n; j++ {
			for k := 0; k < len(S[j]); k++ {
				if S[j][k] == '1' {
					one++
				} else {
					zero++
				}
			}
		}

		for j := 0; j < n; j++ {
			L = append(L, len(S[j]))
		}
		// sort.Sort(sort.IntSlice(L))
		sort.Sort(sort.Reverse(sort.IntSlice(L)))

		ans := sub(L, one, zero)
		fmt.Println(ans)
	}
}

func sub(L []int, one, zero int) int {
	ans := 0
	for j := 0; j < len(L); j++ {
		l := L[j]

		for l > 0 {
			if l >= 2 {
				l -= 2
				if one > zero {
					if one-2 < 0 {
						return ans
					}
					one -= 2
				} else {
					if zero-2 < 0 {
						return ans
					}
					zero -= 2
				}
			} else {
				l--
				if one > zero {
					if one-1 < 0 {
						return ans
					}
					one--
				} else {
					if zero-1 < 0 {
						return ans
					}
					zero--
				}
			}
		}

		ans++
	}

	return ans
}

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

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

package main

import (
	"bufio"
	"bytes"
	. "fmt"
	"io"
	"io/ioutil"
	"os"
	"sort"
)

func GetReaderWriter() (*bufio.Reader, *bufio.Writer) {
	l := os.Getenv("LOCAL_DEBUG")
	reader := io.Reader(os.Stdin)
	writer := io.Writer(os.Stdout)
	if l != "" {
		bs, _ := ioutil.ReadFile("in.txt")
		reader = bytes.NewBuffer(bs)
	}
	return bufio.NewReader(reader), bufio.NewWriter(writer)
}

func main() {
	reader, writer := GetReaderWriter()
	defer writer.Flush()
	var i, q, n, j int64
	_, _ = Fscanf(reader, "%d\n", &q)

	for q > 0 {
		q--
		_, _ = Fscanf(reader, "%d\n", &n)
		s := make([]string, n)
		ll := make([]int64, n)
		s0 := int64(0)
		s1 := int64(0)
		te := int64(0)
		to := int64(0)
		for i = 0; i < n; i++ {
			_, _ = Fscanf(reader, "%s\n", &s[i])
			ll[i] = int64(len(s[i]))
			for j = 0; j < int64(len(s[i])); j++ {
				if s[i][j] == '0' {
					s0++
				} else {
					s1++
				}
			}
			if len(s[i])%2 == 0 {
				te++
			} else {
				to++
			}
		}
		sort.Slice(ll, func(i, j int) bool { return ll[i] < ll[j] })
		if te%2 == 1 && to%2 == 0 {
			if 1 == s0%2 {
				n--
			}
		}
		_, _ = Fprintf(writer, "%d\n", n)
	}
}

package main

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

func GetReaderWriter() (*bufio.Reader, *bufio.Writer) {
	l := os.Getenv("LOCAL_DEBUG")
	reader := io.Reader(os.Stdin)
	writer := io.Writer(os.Stdout)
	if l != "" {
		bs, _ := ioutil.ReadFile("in.txt")
		reader = bytes.NewBuffer(bs)
	}
	return bufio.NewReader(reader), bufio.NewWriter(writer)
}

func main() {
	reader, writer := GetReaderWriter()
	defer writer.Flush()
	var i, q, n, j int64
	_, _ = Fscanf(reader, "%d\n", &q)

	for q > 0 {
		q--
		_, _ = Fscanf(reader, "%d\n", &n)
		s := make([]string, n)
		ll := make([]int64, n)
		s0 := int64(0)
		s1 := int64(0)
		te := int64(0)
		to := int64(0)
		for i = 0; i < n; i++ {
			_, _ = Fscanf(reader, "%s\n", &s[i])
			ll[i] = int64(len(s[i]))
			for j = 0; j < int64(len(s[i])); j++ {
				if s[i][j] == '0' {
					s0++
				} else {
					s1++
				}
			}
			if len(s[i])%2 == 0 {
				te++
			} else {
				to++
			}
		}
		// sort.Slice(ll, func(i, j int) bool { return ll[i] < ll[j] })
		if to%2 == 0 {
			if 1 == s0%2 {
				n--
			}
		}
		_, _ = Fprintf(writer, "%d\n", n)
	}
}


After you have read all the problems, probably, you think Alex is genius person. That's true! One day he came up with the following task.Given a sequence of integer numbers a1, a2, ..., an. You are to find a longest sequence b1, b2, ..., b4m, that satisfies the following conditions:  b4k + 1 = b4k + 3 for all valid integer k;  b4k + 2 = b4k + 4 for all valid integer k;  sequence b is subsequence of a (not necessarily contiguous subsequence). And finally... Alex had given this complicated task to George, and George gave it to you. Help George to cope with the task.

The first line contains a single integer n (1 ≤ n ≤ 5·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).

In the first line print a single integer 4m — the maximal possible length of required sequence b. In the second line print 4m integers b1, b2, ..., b4m, that is required sequence. If there are multiple optimal answers you may print any of them.

package main

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

var in = bufio.NewScanner(os.Stdin)

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

type qua struct {
	a, b    int
	prev, l int
}

func main() {
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := readInt()
	var b []int
	pos := make(map[int][]int)
	a := make([]int, n)
	seg := newSegmentTree(n)
	last := -1
	for i := range a {
		a[i] = readInt()
		s := append(pos[a[i]], i)
		pos[a[i]] = s
		switch l := len(s); {
		case l >= 4 && s[l-4] > last:
			b = append(b, a[i], a[i], a[i], a[i])
			last = i
		case l >= 2 && s[l-2] > last:
			if s[l-2] > last+1 {
				if from, _, ok := seg.get(s[l-2]); ok {
					b = append(b, a[from], a[i], a[from], a[i])
					last = i
				}
			}
			seg.insert(s[l-2], i)
		}
	}

	fmt.Fprintln(out, len(b))
	for i := range b {
		fmt.Fprint(out, b[i])
		if i+1 == len(b) {
			out.WriteRune('\n')
		} else {
			out.WriteRune(' ')
		}
	}
}

type segmentTree struct {
	size int
	tree [][][2]int
}

func newSegmentTree(n int) segmentTree {
	sz := 0
	for x := n; x > 1; x -= x / 2 {
		sz = sz*2 + 2
	}
	return segmentTree{n, make([][][2]int, sz+1)}
}

func (t segmentTree) insert(from, to int) {
	var ins func(id, l, r int)
	ins = func(id, l, r int) {
		if from <= l && to >= r {
			t.tree[id] = append(t.tree[id], [2]int{from, to})
			return
		}
		m := (l + r) / 2
		if from < m {
			ins(id*2+1, l, m)
		}
		if to > m {
			ins(id*2+2, m, r)
		}
	}
	ins(0, 0, t.size)
}

func (t segmentTree) get(p int) (from, to int, ok bool) {
	id, l, r := 0, 0, t.size
	for {
		if len(t.tree[id]) > 0 {
			return t.tree[id][0][0], t.tree[id][0][1], true
		}
		m := (l + r) / 2
		if m == l {
			return 0, 0, false
		}
		if p < m {
			id = id*2 + 1
			r = m
		} else {
			id = id*2 + 2
			l = m
		}
	}
	panic("get")
}


An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code $$$091$$$), a colon (ASCII code $$$058$$$), some (possibly zero) vertical line characters (ASCII code $$$124$$$), another colon, and a closing bracket (ASCII code $$$093$$$). The length of the accordion is the number of characters in it.For example, [::], [:||:] and [:|||:] are accordions having length $$$4$$$, $$$6$$$ and $$$7$$$. (:|:), {:||:}, [:], ]:||:[ are not accordions. You are given a string $$$s$$$. You want to transform it into an accordion by removing some (possibly zero) characters from it. Note that you may not insert new characters or reorder existing ones. Is it possible to obtain an accordion by removing characters from $$$s$$$, and if so, what is the maximum possible length of the result?

The only line contains one string $$$s$$$ ($$$1 \le |s| \le 500000$$$). It consists of lowercase Latin letters and characters [, ], : and |.

If it is not possible to obtain an accordion by removing some characters from $$$s$$$, print $$$-1$$$. Otherwise print maximum possible length of the resulting accordion.

package main

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

type caseInput struct {
	BayanStr string
}

func readCaseInput(scanner *bufio.Scanner) caseInput {
	return caseInput{readString(scanner)}
}

type caseOutput struct {
	BayanLen int32
}

func writeCaseOutput(writer *bufio.Writer, out caseOutput) {
	writef(writer, "%d\n", out.BayanLen)
}

func solveCase(in caseInput) caseOutput {
	opened := false
	firstColonSeen := false
	closingColonSeen := false
	closed := false

	pipesTotal := uint32(0)
	pipesCloseable := uint32(0)
	pipesPendingClose := uint32(0)

	for _, c := range []rune(in.BayanStr) {
		if !opened {
			if c == '[' {
				opened = true
			}
			continue
		}

		if opened && !firstColonSeen {
			if c == ':' {
				firstColonSeen = true
			}
			continue
		}

		if opened && firstColonSeen {
			if c == '|' {
				pipesPendingClose += 1
			} else if c == ':' {
				pipesCloseable += pipesPendingClose
				pipesPendingClose = 0
				closingColonSeen = true
			} else if c == ']' {
				if closingColonSeen {
					closed = true
					pipesTotal = pipesCloseable
				}
			}
		}

	}

	if closed {
		return caseOutput{int32(4 + pipesTotal)}
	}
	return caseOutput{int32(-1)}
}

func solveSequential(scanner *bufio.Scanner, writer *bufio.Writer) {
	writeCaseOutput(writer, solveCase(readCaseInput(scanner)))
}

func main() {
	var scanner *bufio.Scanner
	if len(os.Args) > 1 {
		reader, err := os.Open(os.Args[1])
		if err != nil {
			panic(err)
		}
		defer reader.Close()
		scanner = bufio.NewScanner(reader)
	} else {
		scanner = bufio.NewScanner(os.Stdin)
	}
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)

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

	solveSequential(scanner, writer)
}

func readString(sc *bufio.Scanner) string {
	if !sc.Scan() {
		panic("failed to scan next token")
	}

	return sc.Text()
}

func writef(writer *bufio.Writer, formatStr string, values ...interface{}) {
	out := fmt.Sprintf(formatStr, values...)
	_, err := writer.WriteString(out)
	if err != nil {
		panic(err)
	}
}

// Codeforces 1101 B Accordion train
package main

import (
	"bufio"
	"fmt"
	"strings"
	"strconv"
	"os"
)
var in *bufio.Reader

func readFive() (int,int,int,int,int) {
	var a [5]int
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("first read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for i:=0; i<len(ss); i++ {
		a[i], err = strconv.Atoi(ss[i])
		if err != nil {
			fmt.Println("n atoi failure", err)
			panic(err)
		}
	}
	return a[0],a[1],a[2],a[3],a[4]
}

func readLineNumbs(n int) []int {
	a := make([]int, n)
	delim := byte(' ')
	for i:=0; i<n; i++ {
		if i==(n-1) {
			delim = byte('\n')
		}
		s, err := in.ReadString(delim)
		s = strings.Trim(s, " \n\r")
		if err != nil {
			fmt.Println("read failure", err)
			panic(err)
		}
		aa,err := strconv.Atoi(s)
		if err != nil {
			fmt.Println("aa conv failed", err)
			panic(err)
		}
		a[i] = aa
	}
	return a
}

var n int
var s string
var alen int

type State int
const (
	LeftNone = 0
	OpenBrack = 1
	FirstColon = 2
	VertLine = 3
	SecondColon = 4
	CloseBrack = 5
	RightNone = 6
)

func readData() {
	in = bufio.NewReader(os.Stdin)
	delim := byte('\n')
	ss, err := in.ReadString(delim)
	s = strings.Trim(ss, " \n\r")
	n = len(s)
	// fmt.Println("N=", n)
	if err != nil {
		fmt.Println("read failure", err)
		panic(err)
	}
}

func solve() {
	var inBeg,inEnd,nVert int
	state := LeftNone
	for i := 0; i<n; i++ {
		c := s[i]
		if state==LeftNone && c=='[' {
			state = OpenBrack
		} else if state==OpenBrack && c==':' {
			state = FirstColon
			inBeg = i+1
			break
		}
	}
	state = RightNone
	for i:=n-1; i>=0; i-- {
		c := s[i]
		if state==RightNone && c==']' {
			state = CloseBrack
		} else if state==CloseBrack && c==':' {
			state = SecondColon
			inEnd = i
			break
		}
	}
	// fmt.Println("inBeg,inEnd=", inBeg,inEnd)
	if inBeg==0 || inEnd==0 || inEnd <inBeg {
		alen = -1
		return
	}
	for i:=inBeg; i<inEnd; i++ {
		c := s[i]
		if c=='|' {
			nVert++;
		}
	}
	alen = 4 + nVert
}

func printRes() {
	fmt.Println(alen)
}

func main() {
	readData()
	solve()
	printRes()
}

// Codeforces 1101 B Accordion train
package main

import (
	"bufio"
	"fmt"
	"strings"
	"strconv"
	"os"
)
var in *bufio.Reader

func readFive() (int,int,int,int,int) {
	var a [5]int
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("first read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for i:=0; i<len(ss); i++ {
		a[i], err = strconv.Atoi(ss[i])
		if err != nil {
			fmt.Println("n atoi failure", err)
			panic(err)
		}
	}
	return a[0],a[1],a[2],a[3],a[4]
}

func readLineNumbs(n int) []int {
	a := make([]int, n)
	delim := byte(' ')
	for i:=0; i<n; i++ {
		if i==(n-1) {
			delim = byte('\n')
		}
		s, err := in.ReadString(delim)
		s = strings.Trim(s, " \n\r")
		if err != nil {
			fmt.Println("read failure", err)
			panic(err)
		}
		aa,err := strconv.Atoi(s)
		if err != nil {
			fmt.Println("aa conv failed", err)
			panic(err)
		}
		a[i] = aa
	}
	return a
}

var n int
var s string
var alen int

type State int
const (
	LeftNone = 0
	OpenBrack = 1
	FirstColon = 2
	VertLine = 3
	SecondColon = 4
	CloseBrack = 5
	RightNone = 6
)

func readData() {
	in = bufio.NewReader(os.Stdin)
	delim := byte('\n')
	ss, err := in.ReadString(delim)
	s = strings.Trim(ss, " \n\r")
	n = len(s)
	// fmt.Println("N=", n)
	if err != nil {
		fmt.Println("read failure", err)
		panic(err)
	}
}

func solve() {
	var inBeg,inEnd,nVert int
	state := LeftNone
	for i := 0; i<n; i++ {
		c := s[i]
		if state==LeftNone && c=='[' {
			state = OpenBrack
		} else if state==OpenBrack && c==':' {
			state = FirstColon
			inBeg = i+1
			break
		}
	}
	state = RightNone
	for i:=n-1; i>=0; i-- {
		c := s[i]
		if state==RightNone && c==']' {
			state = CloseBrack
		} else if state==CloseBrack && c==':' {
			state = SecondColon
			inEnd = i
			break
		}
	}
	// fmt.Println("inBeg,inEnd=", inBeg,inEnd)
	if inEnd <inBeg {
		alen = -1
		return
	}
	for i:=inBeg; i<inEnd; i++ {
		c := s[i]
		if c=='|' {
			nVert++;
		}
	}
	alen = 4 + nVert
}

func printRes() {
	fmt.Println(alen)
}

func main() {
	readData()
	solve()
	printRes()
}

// Codeforces 1101 B Accordion train
package main

import (
	"bufio"
	"fmt"
	"strings"
	"strconv"
	"os"
)
var in *bufio.Reader

func readFive() (int,int,int,int,int) {
	var a [5]int
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("first read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for i:=0; i<len(ss); i++ {
		a[i], err = strconv.Atoi(ss[i])
		if err != nil {
			fmt.Println("n atoi failure", err)
			panic(err)
		}
	}
	return a[0],a[1],a[2],a[3],a[4]
}

func readLineNumbs(n int) []int {
	a := make([]int, n)
	delim := byte(' ')
	for i:=0; i<n; i++ {
		if i==(n-1) {
			delim = byte('\n')
		}
		s, err := in.ReadString(delim)
		s = strings.Trim(s, " \n\r")
		if err != nil {
			fmt.Println("read failure", err)
			panic(err)
		}
		aa,err := strconv.Atoi(s)
		if err != nil {
			fmt.Println("aa conv failed", err)
			panic(err)
		}
		a[i] = aa
	}
	return a
}

var n int
var s string
var alen int

type State int
const (
	LeftNone = 0
	OpenBrack = 1
	FirstColon = 2
	VertLine = 3
	SecondColon = 4
	CloseBrack = 5
	RightNone = 6
)

func readData() {
	in = bufio.NewReader(os.Stdin)
	delim := byte('\n')
	ss, err := in.ReadString(delim)
	s = strings.Trim(ss, " \n\r")
	n = len(s)
	// fmt.Println("N=", n)
	if err != nil {
		fmt.Println("read failure", err)
		panic(err)
	}
}

func solve() {
	var inBeg,inEnd,nVert int
	state := LeftNone
	for i := 0; i<n; i++ {
		c := s[i]
		if state==LeftNone && c=='[' {
			state = OpenBrack
		} else if state==OpenBrack && c==':' {
			state = FirstColon
			inBeg = i+1
			break
		}
	}
	state = RightNone
	for i:=n-1; i>=0; i-- {
		c := s[i]
		if state==RightNone && c==']' {
			state = CloseBrack
		} else if state==CloseBrack && c==':' {
			state = SecondColon
			inEnd = i
			break
		}
	}
	if inEnd <=inBeg {
		alen = -1
		return
	}
	for i:=inBeg; i<inEnd; i++ {
		c := s[i]
		if c=='|' {
			nVert++;
		}
	}
	alen = 4 + nVert
}

func printRes() {
	fmt.Println(alen)
}

func main() {
	readData()
	solve()
	printRes()
}


Pak Chanek is playing one of his favourite board games. In the game, there is a directed graph with $$$N$$$ vertices and $$$M$$$ edges. In the graph, edge $$$i$$$ connects two different vertices $$$U_i$$$ and $$$V_i$$$ with a length of $$$W_i$$$. By using the $$$i$$$-th edge, something can move from $$$U_i$$$ to $$$V_i$$$, but not from $$$V_i$$$ to $$$U_i$$$.To play this game, initially Pak Chanek must place both of his hands onto two different vertices. In one move, he can move one of his hands to another vertex using an edge. To move a hand from vertex $$$U_i$$$ to vertex $$$V_i$$$, Pak Chanek needs a time of $$$W_i$$$ seconds. Note that Pak Chanek can only move one hand at a time. This game ends when both of Pak Chanek's hands are on the same vertex.Pak Chanek has several questions. For each $$$p$$$ satisfying $$$2 \leq p \leq N$$$, you need to find the minimum time in seconds needed for Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $$$1$$$ and vertex $$$p$$$, or report if it is impossible.

The first line contains two integers $$$N$$$ and $$$M$$$ ($$$2 \leq N \leq 10^5$$$, $$$0 \leq M \leq 2 \cdot 10^5$$$) — the number of vertices and edges in the graph. The $$$i$$$-th of the next $$$M$$$ lines contains three integers $$$U_i$$$, $$$V_i$$$, and $$$W_i$$$ ($$$1 \le U_i, V_i \le N$$$, $$$U_i \neq V_i$$$, $$$1 \le W_i \le 10^9$$$) — a directed edge that connects two different vertices $$$U_i$$$ and $$$V_i$$$ with a length of $$$W_i$$$. There is no pair of different edges $$$i$$$ and $$$j$$$ such that $$$U_i = U_j$$$ and $$$V_i = V_j$$$.

Output a line containing $$$N-1$$$ integers. The $$$j$$$-th integer represents the minimum time in seconds needed by Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $$$1$$$ and vertex $$$j+1$$$, or $$$-1$$$ if it is impossible.

NoteIf initially Pak Chanek's left hand is on vertex $$$1$$$ and his right hand is on vertex $$$5$$$, Pak Chanek can do the following moves:   Move his right hand to vertex $$$4$$$ in $$$1$$$ second.  Move his left hand to vertex $$$2$$$ in $$$2$$$ seconds.  Move his left hand to vertex $$$4$$$ in $$$1$$$ second. In total it needs $$$1+2+1=4$$$ seconds. It can be proven that there is no other way that is faster.

package main

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

type edge struct {
	from   int
	to     int
	weight int
}

type minHeap struct {
	size          int
	vals          []int
	lookup        []int
	reverseLookup []int
}

func (h *minHeap) heapify(i int) {
	for i > 0 {
		parent := (i - 1) / 2
		if h.vals[i] < h.vals[parent] {
			h.swap(i, parent)
			i = parent
		} else {
			return
		}
	}
}

func (h *minHeap) pop() {
	h.swap(0, h.size-1)
	h.size--
	i := 0
	for {
		better := i
		if i*2+1 < h.size && h.vals[i*2+1] < h.vals[better] {
			better = i*2 + 1
		}
		if i*2+2 < h.size && h.vals[i*2+2] < h.vals[better] {
			better = i*2 + 2
		}
		if better != i {
			h.swap(i, better)
			i = better
		} else {
			break
		}
	}
}

func (h *minHeap) swap(i int, j int) {
	t := h.vals[i]
	h.vals[i] = h.vals[j]
	h.vals[j] = t

	ri := h.reverseLookup[i]
	rj := h.reverseLookup[j]

	h.lookup[ri] = j
	h.lookup[rj] = i

	t = h.reverseLookup[i]
	h.reverseLookup[i] = h.reverseLookup[j]
	h.reverseLookup[j] = t
}

const inf = 9223372036854775807

// https://codeforces.com/problemset/problem/1727/M
func P1727m(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

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

	var incoming = make([][]edge, n+1)
	var outgoing = make([][]edge, n+1)

	for i := 0; i <= n; i++ {
		incoming[i] = make([]edge, 0)
		outgoing[i] = make([]edge, 0)
	}

	for i := 0; i < m; i++ {
		var from int
		var to int
		var weight int
		fmt.Fscan(in, &from)
		fmt.Fscan(in, &to)
		fmt.Fscan(in, &weight)

		var e = edge{from: from, to: to, weight: weight}
		outgoing[from] = append(outgoing[from], e)
		incoming[to] = append(incoming[to], e)
	}

	dist1 := make([]int, n+1)
	lookup1 := make([]int, n+1)
	reverseLookup1 := make([]int, n+1)
	vals1 := make([]int, n+1)
	for i := range dist1 {
		dist1[i] = inf
		vals1[i] = inf
		lookup1[i] = i
		reverseLookup1[i] = i
	}
	vals1[1] = 0
	heap1 := minHeap{
		size:          n + 1,
		vals:          vals1,
		lookup:        lookup1,
		reverseLookup: reverseLookup1,
	}
	heap1.heapify(1)

	for heap1.size > 0 {
		if heap1.vals[0] >= inf {
			break
		}
		topVal := heap1.vals[0]
		topV := heap1.reverseLookup[0]
		dist1[topV] = topVal
		heap1.pop()
		for _, e := range outgoing[topV] {
			neww := dist1[topV] + e.weight
			topos := heap1.lookup[e.to]
			if neww < heap1.vals[topos] {
				heap1.vals[topos] = neww
				heap1.heapify(topos)
			}
		}
	}

	distR := make([]int, n+1)
	lookupR := make([]int, n+1)
	reverseLookupR := make([]int, n+1)
	valsR := make([]int, n+1)
	for i := range distR {
		distR[i] = dist1[i]
		valsR[i] = dist1[i]
		lookupR[i] = i
		reverseLookupR[i] = i
	}
	heapR := minHeap{
		size:          n + 1,
		vals:          valsR,
		lookup:        lookupR,
		reverseLookup: reverseLookupR,
	}
	for i := 0; i <= n; i++ {
		heapR.heapify(i)
	}
	for heapR.size > 0 {
		if heapR.vals[0] >= inf {
			break
		}
		topVal := heapR.vals[0]
		topV := heapR.reverseLookup[0]
		distR[topV] = topVal
		heapR.pop()
		for _, e := range incoming[topV] {
			neww := distR[topV] + e.weight
			frompos := heapR.lookup[e.from]
			if neww < heapR.vals[frompos] {
				heapR.vals[frompos] = neww
				heapR.heapify(frompos)
			}
		}
	}
	var resToJoin []string
	for _, x := range distR[2:] {
		if x < inf {
			resToJoin = append(resToJoin, strconv.Itoa(x))

		} else {
			resToJoin = append(resToJoin, "-1")

		}
	}
	result := strings.Join(resToJoin, " ")
	fmt.Fprintf(out, result)
}

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

package main

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

type edge struct {
	from   int
	to     int
	weight int
}

type minHeap struct {
	size          int
	vals          []int
	lookup        []int
	reverseLookup []int
}

func (h *minHeap) heapify(i int) {
	for i > 0 {
		parent := (i - 1) / 2
		if h.vals[i] < h.vals[parent] {
			h.swap(i, parent)
			i = parent
		} else {
			return
		}
	}
}

func (h *minHeap) pop() {
	h.swap(0, h.size-1)
	h.size--
	i := 0
	for {
		better := i
		if i*2+1 < h.size && h.vals[i*2+1] < h.vals[better] {
			better = i*2 + 1
		}
		if i*2+2 < h.size && h.vals[i*2+2] < h.vals[better] {
			better = i*2 + 2
		}
		if better != i {
			h.swap(i, better)
			i = better
		} else {
			break
		}
	}
}

func (h *minHeap) swap(i int, j int) {
	// fmt.Printf("### Swapping %d and %d\n", i, j)
	t := h.vals[i]
	h.vals[i] = h.vals[j]
	h.vals[j] = t

	ri := h.reverseLookup[i]
	rj := h.reverseLookup[j]

	// fmt.Printf("### Lookup %d <-> %d, reverse: %d <-> %d\n", h.lookup[ri], h.lookup[rj], ri, rj)

	// t = h.lookup[ri]
	// h.lookup[ri] = h.lookup[rj]
	// h.lookup[rj] = t
	h.lookup[ri] = j
	h.lookup[rj] = i

	t = h.reverseLookup[i]
	h.reverseLookup[i] = h.reverseLookup[j]
	h.reverseLookup[j] = t

}

const inf = 9223372036854775807

// https://codeforces.com/problemset/problem/1727/M
func P1727m(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

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

	var incoming = make([][]edge, n+1)
	var outgoing = make([][]edge, n+1)

	for i := 0; i <= n; i++ {
		incoming[i] = make([]edge, 0)
		outgoing[i] = make([]edge, 0)
	}

	for i := 0; i < m; i++ {
		var from int
		var to int
		var weight int
		fmt.Fscan(in, &from)
		fmt.Fscan(in, &to)
		fmt.Fscan(in, &weight)

		var e = edge{from: from, to: to, weight: weight}
		outgoing[from] = append(outgoing[from], e)
		incoming[to] = append(incoming[to], e)
	}

	dist1 := make([]int, n+1)
	lookup1 := make([]int, n+1)
	reverseLookup1 := make([]int, n+1)
	vals1 := make([]int, n+1)
	for i := range dist1 {
		dist1[i] = inf
		vals1[i] = inf
		lookup1[i] = i
		reverseLookup1[i] = i
	}
	vals1[1] = 0
	heap1 := minHeap{
		size:          n + 1,
		vals:          vals1,
		lookup:        lookup1,
		reverseLookup: reverseLookup1,
	}
	heap1.heapify(1)

	for heap1.size > 0 {
		if heap1.vals[0] >= inf {
			break
		}
		// fmt.Printf("### Iteration, vals: %v\n", vals1)
		// fmt.Printf("### Iteration, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### Iteration, reverse lookup: %v\n", heap1.reverseLookup)
		topVal := heap1.vals[0]
		topV := heap1.reverseLookup[0]
		// fmt.Printf("### Top v: %d, val: %d\n", topV, topVal)
		dist1[topV] = topVal
		heap1.pop()
		// fmt.Printf("### After pop, vals: %v\n", vals1)
		// fmt.Printf("### After pop, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### After pop, reverse lookup: %v\n", heap1.reverseLookup)

		for _, e := range outgoing[topV] {
			neww := dist1[topV] + e.weight
			topos := heap1.lookup[e.to]
			if neww < heap1.vals[topos] {
				// fmt.Printf("### Found improvement. v=%d, neww=%d, topos=%d\n", e.to, neww, topos)
				heap1.vals[topos] = neww
				heap1.heapify(topos)
				// fmt.Printf("### After improvement, vals: %v\n", vals1)
				// fmt.Printf("### After improvement, lookup: %v\n", heap1.lookup)
			}
		}
	}

	// fmt.Printf("### Dist1: %v\n", dist1)

	distR := make([]int, n+1)
	lookupR := make([]int, n+1)
	reverseLookupR := make([]int, n+1)
	valsR := make([]int, n+1)
	for i := range distR {
		distR[i] = dist1[i]
		valsR[i] = dist1[i]
		lookupR[i] = i
		reverseLookupR[i] = i
	}
	heapR := minHeap{
		size:          n + 1,
		vals:          valsR,
		lookup:        lookupR,
		reverseLookup: reverseLookupR,
	}
	// fmt.Printf("### DistR pre heapify: %v\n", distR)
	for i := 0; i <= n; i++ {
		heapR.heapify(i)
	}
	// for i := n - 1; i > 0; i-- {
	// 	heapR.heapify(i)
	// }
	// fmt.Printf("### DistR post heapify: %v\n", distR)

	for heapR.size > 0 {
		//fmt.Printf("### Iteration, vals: %v\n", valsR)
		if heapR.vals[0] >= inf {
			break
		}
		// fmt.Printf("### Iteration, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### Iteration, reverse lookup: %v\n", heap1.reverseLookup)
		topVal := heapR.vals[0]
		topV := heapR.reverseLookup[0]
		//fmt.Printf("### Top v: %d, val: %d\n", topV, topVal)
		distR[topV] = topVal
		heapR.pop()
		// fmt.Printf("### After pop, vals: %v\n", vals1)
		// fmt.Printf("### After pop, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### After pop, reverse lookup: %v\n", heap1.reverseLookup)

		for _, e := range incoming[topV] {
			neww := distR[topV] + e.weight
			frompos := heapR.lookup[e.from]
			if neww < heapR.vals[frompos] {
				//fmt.Printf("### Found improvement. v=%d, neww=%d, frompos=%d\n", e.to, neww, frompos)
				heapR.vals[frompos] = neww
				heapR.heapify(frompos)
				// fmt.Printf("### After improvement, vals: %v\n", vals1)
				// fmt.Printf("### After improvement, lookup: %v\n", heap1.lookup)
			}
		}
	}
	//fmt.Printf("### DistsR: %v\n", distR)
	var resToJoin []string
	for _, x := range distR[2:] {
		if x < inf {
			resToJoin = append(resToJoin, strconv.Itoa(x))

		} else {
			resToJoin = append(resToJoin, "-1")

		}
	}
	result := strings.Join(resToJoin, " ")
	fmt.Fprintf(out, result)
}

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

package main

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

type Neighbor struct {
	label int
	cost int
}

type NodeHeap []Neighbor

func (h NodeHeap) Len() int           { return len(h) }
func (h NodeHeap) Less(i, j int) bool { return h[i].cost < h[j].cost }
func (h NodeHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *NodeHeap) Push(x any) {
	*h = append(*h, x.(Neighbor))
}

func (h *NodeHeap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

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

	var n, m, u, v, wt int
	fmt.Fscan(r, &n, &m)

	adj := make([][]Neighbor, 2*n)

	for i := 0; i < m; i++ {
		fmt.Fscan(r, &u, &v, &wt)
		adj[u - 1] = append(adj[u - 1], Neighbor{v - 1, wt})
		adj[n + v - 1] = append(adj[n + v - 1], Neighbor{n + u - 1, wt})
	}

	for i := 0; i < n; i++ {
		adj[i] = append(adj[i], Neighbor{n + i, 0})
	}

	visited := make(map[int]bool)
	distance := make(map[int]int)
	distance[0] = 0

	h := &NodeHeap{}
	heap.Init(h)
	heap.Push(h, Neighbor{0, 0})

	for h.Len() > 0 {
		node := heap.Pop(h).(Neighbor)
		label := node.label
		if visited[label] {
			continue
		}
		visited[label] = true

		for _, nbr := range adj[label] {
			cost, prs := distance[nbr.label]
			cost_through_node := distance[label] + nbr.cost
			if !prs || cost_through_node < cost {
				distance[nbr.label] = cost_through_node
				heap.Push(h, Neighbor{nbr.label, cost_through_node})
			}
		}
	}

	for i := n + 1; i < 2*n; i++ {
		cost, prs := distance[i]
		if !prs {
			cost = -1
		}
		fmt.Fprintf(w, "%d ", cost)
	}
	fmt.Fprint(w, "\n")

}

package main

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

type Neighbor struct {
	label int
	cost int
}

type NodeHeap []Neighbor

func (h NodeHeap) Len() int           { return len(h) }
func (h NodeHeap) Less(i, j int) bool { return h[i].cost < h[j].cost }
func (h NodeHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *NodeHeap) Push(x any) {
	*h = append(*h, x.(Neighbor))
}

func (h *NodeHeap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

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

	var n, m, u, v, wt int
	fmt.Fscan(r, &n, &m)

	adj := make([][]Neighbor, 2*n)

	for i := 0; i < m; i++ {
		fmt.Fscan(r, &u, &v, &wt)
		adj[u - 1] = append(adj[u - 1], Neighbor{v - 1, wt})
		adj[n + v - 1] = append(adj[n + v - 1], Neighbor{n + u - 1, wt})
	}

	for i := 0; i < n; i++ {
		adj[i] = append(adj[i], Neighbor{n + i, 0})
	}

	visited := make(map[int]bool)
	distance := make(map[int]int)
	distance[0] = 0

	h := &NodeHeap{}
	heap.Init(h)
	heap.Push(h, Neighbor{0, 0})

	for h.Len() > 0 {
		node := heap.Pop(h).(Neighbor)
		label := node.label
		// fmt.Fprintln(w, "+++++++++ ", label)
		if visited[label] {
			continue
		}
		visited[label] = true

		for _, nbr := range adj[label] {
			cost, prs := distance[nbr.label]
			cost_through_node := distance[label] + nbr.cost
			if !prs || cost_through_node < cost {
				distance[nbr.label] = cost_through_node
				heap.Push(h, Neighbor{nbr.label, cost_through_node})
				// fmt.Fprintln(w, "********* ", nbr.label, cost_through_node)
			}
		}
	}

	for i := n + 1; i < 2*n; i++ {
		cost, prs := distance[i]
		if !prs {
			cost = -1
		}
		fmt.Fprintf(w, "%d ", cost)
	}
	fmt.Fprint(w, "\n")

}

package main

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

type edge struct {
	from   int
	to     int
	weight int
}

type minHeap struct {
	size          int
	vals          []int
	lookup        []int
	reverseLookup []int
}

func (h *minHeap) heapify(i int) {
	for i > 0 {
		parent := (i - 1) / 2
		if h.vals[i] < h.vals[parent] {
			h.swap(i, parent)
			i = parent
		} else {
			return
		}
	}
}

func (h *minHeap) pop() {
	h.swap(0, h.size-1)
	h.size--
	i := 0
	for {
		better := i
		if i*2+1 < h.size && h.vals[i*2+1] < h.vals[better] {
			better = i*2 + 1
		}
		if i*2+2 < h.size && h.vals[i*2+2] < h.vals[better] {
			better = i*2 + 2
		}
		if better != i {
			h.swap(i, better)
			i = better
		} else {
			break
		}
	}
}

func (h *minHeap) swap(i int, j int) {
	// fmt.Printf("### Swapping %d and %d\n", i, j)
	t := h.vals[i]
	h.vals[i] = h.vals[j]
	h.vals[j] = t

	ri := h.reverseLookup[i]
	rj := h.reverseLookup[j]

	// fmt.Printf("### Lookup %d <-> %d, reverse: %d <-> %d\n", h.lookup[ri], h.lookup[rj], ri, rj)

	// t = h.lookup[ri]
	// h.lookup[ri] = h.lookup[rj]
	// h.lookup[rj] = t
	h.lookup[ri] = j
	h.lookup[rj] = i

	t = h.reverseLookup[i]
	h.reverseLookup[i] = h.reverseLookup[j]
	h.reverseLookup[j] = t

}

const inf = 9223372036854775807

// https://codeforces.com/problemset/problem/1727/M
func P1727m(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

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

	var incoming = make([][]edge, n+1)
	var outgoing = make([][]edge, n+1)

	for i := 0; i <= n; i++ {
		incoming[i] = make([]edge, 0)
		outgoing[i] = make([]edge, 0)
	}

	for i := 0; i < m; i++ {
		var from int
		var to int
		var weight int
		fmt.Fscan(in, &from)
		fmt.Fscan(in, &to)
		fmt.Fscan(in, &weight)

		var e = edge{from: from, to: to, weight: weight}
		outgoing[from] = append(outgoing[from], e)
		incoming[to] = append(incoming[to], e)
	}

	dist1 := make([]int, n+1)
	lookup1 := make([]int, n+1)
	reverseLookup1 := make([]int, n+1)
	vals1 := make([]int, n+1)
	for i := range dist1 {
		dist1[i] = inf
		vals1[i] = inf
		lookup1[i] = i
		reverseLookup1[i] = i
	}
	vals1[1] = 0
	heap1 := minHeap{
		size:          n + 1,
		vals:          vals1,
		lookup:        lookup1,
		reverseLookup: reverseLookup1,
	}
	heap1.heapify(1)

	for heap1.size > 0 {
		if heap1.vals[0] >= inf {
			break
		}
		// fmt.Printf("### Iteration, vals: %v\n", vals1)
		// fmt.Printf("### Iteration, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### Iteration, reverse lookup: %v\n", heap1.reverseLookup)
		topVal := heap1.vals[0]
		topV := heap1.reverseLookup[0]
		// fmt.Printf("### Top v: %d, val: %d\n", topV, topVal)
		dist1[topV] = topVal
		heap1.pop()
		// fmt.Printf("### After pop, vals: %v\n", vals1)
		// fmt.Printf("### After pop, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### After pop, reverse lookup: %v\n", heap1.reverseLookup)

		for _, e := range outgoing[topV] {
			neww := dist1[topV] + e.weight
			topos := heap1.lookup[e.to]
			if neww < heap1.vals[topos] {
				// fmt.Printf("### Found improvement. v=%d, neww=%d, topos=%d\n", e.to, neww, topos)
				heap1.vals[topos] = neww
				heap1.heapify(topos)
				// fmt.Printf("### After improvement, vals: %v\n", vals1)
				// fmt.Printf("### After improvement, lookup: %v\n", heap1.lookup)
			}
		}
	}

	// fmt.Printf("### Dist1: %v\n", dist1)

	distR := make([]int, n+1)
	lookupR := make([]int, n+1)
	reverseLookupR := make([]int, n+1)
	valsR := make([]int, n+1)
	for i := range distR {
		distR[i] = dist1[i]
		valsR[i] = dist1[i]
		lookupR[i] = i
		reverseLookupR[i] = i
	}
	valsR[1] = 0
	heapR := minHeap{
		size:          n + 1,
		vals:          valsR,
		lookup:        lookupR,
		reverseLookup: reverseLookupR,
	}
	// fmt.Printf("### DistR pre heapify: %v\n", distR)
	for i := n - 1; i > 0; i-- {
		heapR.heapify(i)
	}
	// fmt.Printf("### DistR post heapify: %v\n", distR)

	for heapR.size > 0 {
		//fmt.Printf("### Iteration, vals: %v\n", valsR)
		if heapR.vals[0] >= inf {
			break
		}
		// fmt.Printf("### Iteration, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### Iteration, reverse lookup: %v\n", heap1.reverseLookup)
		topVal := heapR.vals[0]
		topV := heapR.reverseLookup[0]
		//fmt.Printf("### Top v: %d, val: %d\n", topV, topVal)
		distR[topV] = topVal
		heapR.pop()
		// fmt.Printf("### After pop, vals: %v\n", vals1)
		// fmt.Printf("### After pop, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### After pop, reverse lookup: %v\n", heap1.reverseLookup)

		for _, e := range incoming[topV] {
			neww := distR[topV] + e.weight
			frompos := heapR.lookup[e.from]
			if neww < heapR.vals[frompos] {
				//fmt.Printf("### Found improvement. v=%d, neww=%d, frompos=%d\n", e.to, neww, frompos)
				heapR.vals[frompos] = neww
				heapR.heapify(frompos)
				// fmt.Printf("### After improvement, vals: %v\n", vals1)
				// fmt.Printf("### After improvement, lookup: %v\n", heap1.lookup)
			}
		}
	}
	//fmt.Printf("### DistsR: %v\n", distR)
	var resToJoin []string
	for _, x := range distR[2:] {
		if x < inf {
			resToJoin = append(resToJoin, strconv.Itoa(x))

		} else {
			resToJoin = append(resToJoin, "-1")

		}
	}
	result := strings.Join(resToJoin, " ")
	fmt.Fprintf(out, result)
}

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

package main

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

type edge struct {
	from   int
	to     int
	weight int
}

type minHeap struct {
	size          int
	vals          []int
	lookup        []int
	reverseLookup []int
}

func (h *minHeap) heapify(i int) {
	for i > 0 {
		parent := i / 2
		if h.vals[i] < h.vals[parent] {
			h.swap(i, parent)
			i = parent
		} else {
			return
		}
	}
}

func (h *minHeap) pop() {
	h.swap(0, h.size-1)
	h.size--
	i := 0
	for {
		better := i
		if i*2+1 < h.size && h.vals[i*2+1] < h.vals[better] {
			better = i*2 + 1
		}
		if i*2+2 < h.size && h.vals[i*2+2] < h.vals[better] {
			better = i*2 + 2
		}
		if better != i {
			h.swap(i, better)
			i = better
		} else {
			break
		}
	}
}

func (h *minHeap) swap(i int, j int) {
	// fmt.Printf("### Swapping %d and %d\n", i, j)
	t := h.vals[i]
	h.vals[i] = h.vals[j]
	h.vals[j] = t

	ri := h.reverseLookup[i]
	rj := h.reverseLookup[j]

	// fmt.Printf("### Lookup %d <-> %d, reverse: %d <-> %d\n", h.lookup[ri], h.lookup[rj], ri, rj)

	// t = h.lookup[ri]
	// h.lookup[ri] = h.lookup[rj]
	// h.lookup[rj] = t
	h.lookup[ri] = j
	h.lookup[rj] = i

	t = h.reverseLookup[i]
	h.reverseLookup[i] = h.reverseLookup[j]
	h.reverseLookup[j] = t

}

const inf = 9223372036854775807

// https://codeforces.com/problemset/problem/1727/M
func P1727m(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

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

	var incoming = make([][]edge, n+1)
	var outgoing = make([][]edge, n+1)

	for i := 0; i <= n; i++ {
		incoming[i] = make([]edge, 0)
		outgoing[i] = make([]edge, 0)
	}

	for i := 0; i < m; i++ {
		var from int
		var to int
		var weight int
		fmt.Fscan(in, &from)
		fmt.Fscan(in, &to)
		fmt.Fscan(in, &weight)

		var e = edge{from: from, to: to, weight: weight}
		outgoing[from] = append(outgoing[from], e)
		incoming[to] = append(incoming[to], e)
	}

	dist1 := make([]int, n+1)
	lookup1 := make([]int, n+1)
	reverseLookup1 := make([]int, n+1)
	vals1 := make([]int, n+1)
	for i := range dist1 {
		dist1[i] = inf
		vals1[i] = inf
		lookup1[i] = i
		reverseLookup1[i] = i
	}
	vals1[1] = 0
	heap1 := minHeap{
		size:          n + 1,
		vals:          vals1,
		lookup:        lookup1,
		reverseLookup: reverseLookup1,
	}
	heap1.heapify(1)

	for heap1.size > 0 {
		if heap1.vals[0] >= inf {
			break
		}
		// fmt.Printf("### Iteration, vals: %v\n", vals1)
		// fmt.Printf("### Iteration, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### Iteration, reverse lookup: %v\n", heap1.reverseLookup)
		topVal := heap1.vals[0]
		topV := heap1.reverseLookup[0]
		// fmt.Printf("### Top v: %d, val: %d\n", topV, topVal)
		dist1[topV] = topVal
		heap1.pop()
		// fmt.Printf("### After pop, vals: %v\n", vals1)
		// fmt.Printf("### After pop, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### After pop, reverse lookup: %v\n", heap1.reverseLookup)

		for _, e := range outgoing[topV] {
			neww := dist1[topV] + e.weight
			topos := heap1.lookup[e.to]
			if neww < heap1.vals[topos] {
				// fmt.Printf("### Found improvement. v=%d, neww=%d, topos=%d\n", e.to, neww, topos)
				heap1.vals[topos] = neww
				heap1.heapify(topos)
				// fmt.Printf("### After improvement, vals: %v\n", vals1)
				// fmt.Printf("### After improvement, lookup: %v\n", heap1.lookup)
			}
		}
	}

	// fmt.Printf("### Dist1: %v\n", dist1)

	distR := make([]int, n+1)
	lookupR := make([]int, n+1)
	reverseLookupR := make([]int, n+1)
	valsR := make([]int, n+1)
	for i := range distR {
		distR[i] = dist1[i]
		valsR[i] = dist1[i]
		lookupR[i] = i
		reverseLookupR[i] = i
	}
	valsR[1] = 0
	heapR := minHeap{
		size:          n + 1,
		vals:          valsR,
		lookup:        lookupR,
		reverseLookup: reverseLookupR,
	}
	// fmt.Printf("### DistR pre heapify: %v\n", distR)
	for i := n - 1; i > 0; i-- {
		heapR.heapify(i)
	}
	// fmt.Printf("### DistR post heapify: %v\n", distR)

	for heapR.size > 0 {
		//fmt.Printf("### Iteration, vals: %v\n", valsR)
		if heapR.vals[0] >= inf {
			break
		}
		// fmt.Printf("### Iteration, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### Iteration, reverse lookup: %v\n", heap1.reverseLookup)
		topVal := heapR.vals[0]
		topV := heapR.reverseLookup[0]
		//fmt.Printf("### Top v: %d, val: %d\n", topV, topVal)
		distR[topV] = topVal
		heapR.pop()
		// fmt.Printf("### After pop, vals: %v\n", vals1)
		// fmt.Printf("### After pop, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### After pop, reverse lookup: %v\n", heap1.reverseLookup)

		for _, e := range incoming[topV] {
			neww := distR[topV] + e.weight
			frompos := heapR.lookup[e.from]
			if neww < heapR.vals[frompos] {
				//fmt.Printf("### Found improvement. v=%d, neww=%d, frompos=%d\n", e.to, neww, frompos)
				heapR.vals[frompos] = neww
				heapR.heapify(frompos)
				// fmt.Printf("### After improvement, vals: %v\n", vals1)
				// fmt.Printf("### After improvement, lookup: %v\n", heap1.lookup)
			}
		}
	}
	//fmt.Printf("### DistsR: %v\n", distR)
	var resToJoin []string
	for _, x := range distR[2:] {
		if x < inf {
			resToJoin = append(resToJoin, strconv.Itoa(x))

		} else {
			resToJoin = append(resToJoin, "-1")

		}
	}
	result := strings.Join(resToJoin, " ")
	fmt.Fprintf(out, result)
}

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

package main

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

type edge struct {
	from   int
	to     int
	weight int
}

type minHeap struct {
	size          int
	vals          []int
	lookup        []int
	reverseLookup []int
}

func (h *minHeap) heapify(i int) {
	for i > 0 {
		parent := i / 2
		if h.vals[i] < h.vals[parent] {
			h.swap(i, parent)
			i = parent
		} else {
			return
		}
	}
}

func (h *minHeap) pop() {
	h.swap(0, h.size-1)
	h.size--
	i := 0
	for {
		better := i
		if i*2+1 < h.size && h.vals[i*2+1] < h.vals[better] {
			better = i*2 + 1
		}
		if i*2+2 < h.size && h.vals[i*2+2] < h.vals[better] {
			better = i*2 + 2
		}
		if better != i {
			h.swap(i, better)
			i = better
		} else {
			break
		}
	}
}

func (h *minHeap) swap(i int, j int) {
	// fmt.Printf("### Swapping %d and %d\n", i, j)
	t := h.vals[i]
	h.vals[i] = h.vals[j]
	h.vals[j] = t

	ri := h.reverseLookup[i]
	rj := h.reverseLookup[j]

	// fmt.Printf("### Lookup %d <-> %d, reverse: %d <-> %d\n", h.lookup[ri], h.lookup[rj], ri, rj)

	// t = h.lookup[ri]
	// h.lookup[ri] = h.lookup[rj]
	// h.lookup[rj] = t
	h.lookup[ri] = j
	h.lookup[rj] = i

	t = h.reverseLookup[i]
	h.reverseLookup[i] = h.reverseLookup[j]
	h.reverseLookup[j] = t

}

const inf = 9223372036854775807

// https://codeforces.com/problemset/problem/1727/M
func P1727m(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

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

	var incoming = make([][]edge, n+1)
	var outgoing = make([][]edge, n+1)

	for i := 0; i <= n; i++ {
		incoming[i] = make([]edge, 0)
		outgoing[i] = make([]edge, 0)
	}

	for i := 0; i < m; i++ {
		var from int
		var to int
		var weight int
		fmt.Fscan(in, &from)
		fmt.Fscan(in, &to)
		fmt.Fscan(in, &weight)

		var e = edge{from: from, to: to, weight: weight}
		outgoing[from] = append(outgoing[from], e)
		incoming[to] = append(incoming[to], e)
	}

	dist1 := make([]int, n+1)
	lookup1 := make([]int, n+1)
	reverseLookup1 := make([]int, n+1)
	vals1 := make([]int, n+1)
	for i := range dist1 {
		dist1[i] = inf
		vals1[i] = inf
		lookup1[i] = i
		reverseLookup1[i] = i
	}
	vals1[1] = 0
	heap1 := minHeap{
		size:          n + 1,
		vals:          vals1,
		lookup:        lookup1,
		reverseLookup: reverseLookup1,
	}
	heap1.heapify(1)

	for heap1.size > 0 {
		if heap1.vals[0] >= inf {
			break
		}
		// fmt.Printf("### Iteration, vals: %v\n", vals1)
		// fmt.Printf("### Iteration, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### Iteration, reverse lookup: %v\n", heap1.reverseLookup)
		topVal := heap1.vals[0]
		topV := heap1.reverseLookup[0]
		// fmt.Printf("### Top v: %d, val: %d\n", topV, topVal)
		dist1[topV] = topVal
		heap1.pop()
		// fmt.Printf("### After pop, vals: %v\n", vals1)
		// fmt.Printf("### After pop, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### After pop, reverse lookup: %v\n", heap1.reverseLookup)

		for _, e := range outgoing[topV] {
			neww := dist1[topV] + e.weight
			topos := heap1.lookup[e.to]
			if neww < heap1.vals[topos] {
				// fmt.Printf("### Found improvement. v=%d, neww=%d, topos=%d\n", e.to, neww, topos)
				heap1.vals[topos] = neww
				heap1.heapify(topos)
				// fmt.Printf("### After improvement, vals: %v\n", vals1)
				// fmt.Printf("### After improvement, lookup: %v\n", heap1.lookup)
			}
		}
	}

	fmt.Printf("### Dist1: %v\n", dist1)

	distR := make([]int, n+1)
	lookupR := make([]int, n+1)
	reverseLookupR := make([]int, n+1)
	valsR := make([]int, n+1)
	for i := range distR {
		distR[i] = dist1[i]
		valsR[i] = dist1[i]
		lookupR[i] = i
		reverseLookupR[i] = i
	}
	valsR[1] = 0
	heapR := minHeap{
		size:          n + 1,
		vals:          valsR,
		lookup:        lookupR,
		reverseLookup: reverseLookupR,
	}
	// fmt.Printf("### DistR pre heapify: %v\n", distR)
	for i := n - 1; i > 0; i-- {
		heapR.heapify(i)
	}
	// fmt.Printf("### DistR post heapify: %v\n", distR)

	for heapR.size > 0 {
		//fmt.Printf("### Iteration, vals: %v\n", valsR)
		if heapR.vals[0] >= inf {
			break
		}
		// fmt.Printf("### Iteration, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### Iteration, reverse lookup: %v\n", heap1.reverseLookup)
		topVal := heapR.vals[0]
		topV := heapR.reverseLookup[0]
		//fmt.Printf("### Top v: %d, val: %d\n", topV, topVal)
		distR[topV] = topVal
		heapR.pop()
		// fmt.Printf("### After pop, vals: %v\n", vals1)
		// fmt.Printf("### After pop, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### After pop, reverse lookup: %v\n", heap1.reverseLookup)

		for _, e := range incoming[topV] {
			neww := distR[topV] + e.weight
			frompos := heapR.lookup[e.from]
			if neww < heapR.vals[frompos] {
				//fmt.Printf("### Found improvement. v=%d, neww=%d, frompos=%d\n", e.to, neww, frompos)
				heapR.vals[frompos] = neww
				heapR.heapify(frompos)
				// fmt.Printf("### After improvement, vals: %v\n", vals1)
				// fmt.Printf("### After improvement, lookup: %v\n", heap1.lookup)
			}
		}
	}
	//fmt.Printf("### DistsR: %v\n", distR)
	var resToJoin []string
	for _, x := range distR[2:] {
		if x < inf {
			resToJoin = append(resToJoin, strconv.Itoa(x))

		} else {
			resToJoin = append(resToJoin, "-1")

		}
	}
	result := strings.Join(resToJoin, " ")
	fmt.Fprintf(out, result)
}

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

package main

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

type edge struct {
	from   int
	to     int
	weight int
}

type minHeap struct {
	size          int
	vals          []int
	lookup        []int
	reverseLookup []int
}

func (h *minHeap) heapify(i int) {
	for i > 0 {
		parent := i / 2
		if h.vals[i] < h.vals[parent] {
			h.swap(i, parent)
			i = parent
		} else {
			return
		}
	}
}

func (h *minHeap) pop() {
	h.swap(0, h.size-1)
	h.size--
	i := 0
	for {
		better := i
		if i*2 < h.size && h.vals[i*2] < h.vals[better] {
			better = i * 2
		}
		if i*2+1 < h.size && h.vals[i*2+1] < h.vals[better] {
			better = i*2 + 1
		}
		if better != i {
			h.swap(i, better)
			i = better
		} else {
			break
		}
	}
}

func (h *minHeap) swap(i int, j int) {
	// fmt.Printf("### Swapping %d and %d\n", i, j)
	t := h.vals[i]
	h.vals[i] = h.vals[j]
	h.vals[j] = t

	ri := h.reverseLookup[i]
	rj := h.reverseLookup[j]

	// fmt.Printf("### Lookup %d <-> %d, reverse: %d <-> %d\n", h.lookup[ri], h.lookup[rj], ri, rj)

	// t = h.lookup[ri]
	// h.lookup[ri] = h.lookup[rj]
	// h.lookup[rj] = t
	h.lookup[ri] = j
	h.lookup[rj] = i

	t = h.reverseLookup[i]
	h.reverseLookup[i] = h.reverseLookup[j]
	h.reverseLookup[j] = t

}

const inf = 9223372036854775807

// https://codeforces.com/problemset/problem/1727/M
func P1727m(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

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

	var incoming = make([][]edge, n+1)
	var outgoing = make([][]edge, n+1)

	for i := 0; i <= n; i++ {
		incoming[i] = make([]edge, 0)
		outgoing[i] = make([]edge, 0)
	}

	for i := 0; i < m; i++ {
		var from int
		var to int
		var weight int
		fmt.Fscan(in, &from)
		fmt.Fscan(in, &to)
		fmt.Fscan(in, &weight)

		var e = edge{from: from, to: to, weight: weight}
		outgoing[from] = append(outgoing[from], e)
		incoming[to] = append(incoming[to], e)
	}

	dist1 := make([]int, n+1)
	lookup1 := make([]int, n+1)
	reverseLookup1 := make([]int, n+1)
	vals1 := make([]int, n+1)
	for i := range dist1 {
		dist1[i] = inf
		vals1[i] = inf
		lookup1[i] = i
		reverseLookup1[i] = i
	}
	vals1[1] = 0
	heap1 := minHeap{
		size:          n + 1,
		vals:          vals1,
		lookup:        lookup1,
		reverseLookup: reverseLookup1,
	}
	heap1.heapify(1)

	for heap1.size > 0 {
		if heap1.vals[0] >= inf {
			break
		}
		// fmt.Printf("### Iteration, vals: %v\n", vals1)
		// fmt.Printf("### Iteration, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### Iteration, reverse lookup: %v\n", heap1.reverseLookup)
		topVal := heap1.vals[0]
		topV := heap1.reverseLookup[0]
		// fmt.Printf("### Top v: %d, val: %d\n", topV, topVal)
		dist1[topV] = topVal
		heap1.pop()
		// fmt.Printf("### After pop, vals: %v\n", vals1)
		// fmt.Printf("### After pop, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### After pop, reverse lookup: %v\n", heap1.reverseLookup)

		for _, e := range outgoing[topV] {
			neww := dist1[topV] + e.weight
			topos := heap1.lookup[e.to]
			if neww < heap1.vals[topos] {
				// fmt.Printf("### Found improvement. v=%d, neww=%d, topos=%d\n", e.to, neww, topos)
				heap1.vals[topos] = neww
				heap1.heapify(topos)
				// fmt.Printf("### After improvement, vals: %v\n", vals1)
				// fmt.Printf("### After improvement, lookup: %v\n", heap1.lookup)
			}
		}
	}

	// fmt.Printf("### Dists: %v\n", dist1)

	distR := make([]int, n+1)
	lookupR := make([]int, n+1)
	reverseLookupR := make([]int, n+1)
	valsR := make([]int, n+1)
	for i := range distR {
		distR[i] = dist1[i]
		valsR[i] = dist1[i]
		lookupR[i] = i
		reverseLookupR[i] = i
	}
	valsR[1] = 0
	heapR := minHeap{
		size:          n + 1,
		vals:          valsR,
		lookup:        lookupR,
		reverseLookup: reverseLookupR,
	}
	// fmt.Printf("### DistR pre heapify: %v\n", distR)
	for i := n - 1; i > 0; i-- {
		heapR.heapify(i)
	}
	// fmt.Printf("### DistR post heapify: %v\n", distR)

	for heapR.size > 0 {
		if heapR.vals[0] >= inf {
			break
		}
		// fmt.Printf("### Iteration, vals: %v\n", valsR)
		// fmt.Printf("### Iteration, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### Iteration, reverse lookup: %v\n", heap1.reverseLookup)
		topVal := heapR.vals[0]
		topV := heapR.reverseLookup[0]
		// fmt.Printf("### Top v: %d, val: %d\n", topV, topVal)
		distR[topV] = topVal
		heapR.pop()
		// fmt.Printf("### After pop, vals: %v\n", vals1)
		// fmt.Printf("### After pop, lookup: %v\n", heap1.lookup)
		// fmt.Printf("### After pop, reverse lookup: %v\n", heap1.reverseLookup)

		for _, e := range incoming[topV] {
			neww := distR[topV] + e.weight
			frompos := heapR.lookup[e.from]
			if neww < heapR.vals[frompos] {
				// fmt.Printf("### Found improvement. v=%d, neww=%d, frompos=%d\n", e.to, neww, frompos)
				heapR.vals[frompos] = neww
				heapR.heapify(frompos)
				// fmt.Printf("### After improvement, vals: %v\n", vals1)
				// fmt.Printf("### After improvement, lookup: %v\n", heap1.lookup)
			}
		}
	}
	// fmt.Printf("### DistsR: %v\n", distR)
	var resToJoin []string
	for _, x := range distR[2:] {
		if x < inf {
			resToJoin = append(resToJoin, strconv.Itoa(x))

		} else {
			resToJoin = append(resToJoin, "-1")

		}
	}
	result := strings.Join(resToJoin, " ")
	fmt.Fprintf(out, result)
}

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


You've got two rectangular tables with sizes na × ma and nb × mb cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the i-th row and the j-th column, as ai, j; we will define the element of the second table, located at the intersection of the i-th row and the j-th column, as bi, j. We will call the pair of integers (x, y) a shift of the second table relative to the first one. We'll call the overlap factor of the shift (x, y) value:where the variables i, j take only such values, in which the expression ai, j·bi + x, j + y makes sense. More formally, inequalities 1 ≤ i ≤ na, 1 ≤ j ≤ ma, 1 ≤ i + x ≤ nb, 1 ≤ j + y ≤ mb must hold. If there are no values of variables i, j, that satisfy the given inequalities, the value of the sum is considered equal to 0. Your task is to find the shift with the maximum overlap factor among all possible shifts.

The first line contains two space-separated integers na, ma (1 ≤ na, ma ≤ 50) — the number of rows and columns in the first table. Then na lines contain ma characters each — the elements of the first table. Each character is either a "0", or a "1". The next line contains two space-separated integers nb, mb (1 ≤ nb, mb ≤ 50) — the number of rows and columns in the second table. Then follow the elements of the second table in the format, similar to the first table. It is guaranteed that the first table has at least one number "1". It is guaranteed that the second table has at least one number "1".

Print two space-separated integers x, y (|x|, |y| ≤ 109) — a shift with maximum overlap factor. If there are multiple solutions, print any of them.

package main

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

var scanner *bufio.Scanner
var writer *bufio.Writer

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

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

  nA, mA := getI(), getI()
  a := make([][]int, nA)
  for r := range a {
    s := getS()
    a[r] = make([]int, mA)
    for c := range a[r] {
      a[r][c] = int(s[c]-'0')
    }
  }
  nB, mB := getI(), getI()
  b := make([][]int, nB)
  for r := range b {
    s := getS()
    b[r] = make([]int, mB)
    for c := range b[r] {
      b[r][c] = int(s[c]-'0')
    }
  }
  bestTotal, bestX, bestY := 0, 0, 0
  for x := -nA+1; x <= nB-1; x++ {
    for y := -mA+1; y <= mB-1; y++ {
      total := 0
      for r := 0; r < nA; r++ {
        R := r+x
        if R >= 0 && R < nB {
          for c := 0; c < mA; c++ {
            C := c+y
            if C >= 0 && C < mB {
              total += a[r][c]*b[R][C]
            }
          }
        }
      }
      if total > bestTotal {
        bestTotal = total
        bestX = x
        bestY = y
      }
    }
  }
  writer.WriteString(fmt.Sprintf("%d %d\n", bestX, bestY))
}


You are given a tree (an undirected connected acyclic graph) consisting of $$$n$$$ vertices and $$$n - 1$$$ edges. A number is written on each edge, each number is either $$$0$$$ (let's call such edges $$$0$$$-edges) or $$$1$$$ (those are $$$1$$$-edges).Let's call an ordered pair of vertices $$$(x, y)$$$ ($$$x \ne y$$$) valid if, while traversing the simple path from $$$x$$$ to $$$y$$$, we never go through a $$$0$$$-edge after going through a $$$1$$$-edge. Your task is to calculate the number of valid pairs in the tree.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 200000$$$) — the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each denoting an edge of the tree. Each edge is represented by three integers $$$x_i$$$, $$$y_i$$$ and $$$c_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$0 \le c_i \le 1$$$, $$$x_i \ne y_i$$$) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree.

Print one integer — the number of valid pairs of vertices.

NoteThe picture corresponding to the first example:

package main

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

func solve(j Jam) {
	n := uint32(j.Int())
	zeroClusters, oneClusters := UnionFindNew(n), UnionFindNew(n)
	for l := uint32(1); l < n; l++ {
		x, y, c := uint32(j.Int())-1, uint32(j.Int()-1), j.Int() > 0
		if c {
			oneClusters.Union(x, y)
		} else {
			zeroClusters.Union(x, y)
		}
	}
	validPairs := int64(0)
	countedZeroComponents, countedOneComponents := make(map[uint32]bool, n), make(map[uint32]bool, n)
	for v := uint32(0); v < n; v++ {
		zeroClusterSize, oneClusterSize := zeroClusters.Size(v), oneClusters.Size(v)
		zeroClusterRoot, oneClusterRoot := zeroClusters.Find(v), oneClusters.Find(v)
		if zeroClusterSize > 1 && !countedZeroComponents[zeroClusterRoot] {
			validPairs += int64(zeroClusterSize) * int64(zeroClusterSize-1)
			countedZeroComponents[zeroClusterRoot] = true
		}
		if oneClusterSize > 1 && !countedOneComponents[oneClusterRoot] {
			validPairs += int64(oneClusterSize) * int64(oneClusterSize-1)
			countedOneComponents[oneClusterRoot] = true
		}
		if zeroClusterSize > 1 && oneClusterSize > 1 {
			validPairs += int64(zeroClusterSize-1) * int64(oneClusterSize-1)
		}
	}
	j.P("%d\n", validPairs)
}

func main() {
	jam, closeFunc := JamNew()
	defer closeFunc()
	solve(jam)
}

type Jam interface {
	Scanner() *bufio.Scanner
	Writer() *bufio.Writer
	Close()

	Str() string
	Int() int64
	Float() float64

	P(format string, values ...interface{})
	PF(format string, values ...interface{})
}

func JamNew() (Jam, func()) {
	if len(os.Args) > 1 {
		panic("running with input file path is not supported")
	}

	var scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)

	var writer = bufio.NewWriter(os.Stdout)
	jam := &jam{scanner, writer}
	return jam, jam.Close
}

type jam struct {
	sc *bufio.Scanner
	wr *bufio.Writer
}

func (j *jam) Close() {
	if err := j.wr.Flush(); err != nil {
		panic(err)
	}
}

func (j *jam) Scanner() *bufio.Scanner {
	return j.sc
}

func (j *jam) Writer() *bufio.Writer {
	return j.wr
}

func (j *jam) Str() string {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	return j.sc.Text()
}

func (j *jam) Int() int64 {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	res, err := strconv.ParseInt(j.sc.Text(), 10, 64)
	if err != nil {
		panic(err)
	}

	return res
}

func (j *jam) Float() float64 {
	j.sc.Scan()
	res, err := strconv.ParseFloat(j.sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

func (j *jam) P(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
}

func (j *jam) PF(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
	if err = j.wr.Flush(); err != nil {
		panic(err)
	}
}

type UnionFind struct {
	parent []uint32
	size   []uint32
	count  uint32
}

func UnionFindNew(count uint32) *UnionFind {
	parent := make([]uint32, count, count)
	size := make([]uint32, count, count)
	lim := count
	for i := uint32(0); i < lim; i++ {
		parent[i], size[i] = i, 1
	}
	return &UnionFind{parent, size, lim}
}

func (ufp *UnionFind) Reset() {
	lim := uint32(len(ufp.parent))
	for i := uint32(0); i < lim; i++ {
		ufp.parent[i], ufp.size[i] = i, 1
	}
	ufp.count = lim
}

func (ufp *UnionFind) validate(p uint32) {
	n := uint32(len(ufp.parent))
	if p >= n {
		panic(fmt.Sprintf("index %d is not between 0 and %d", p, n - 1))
	}
}

func (ufp *UnionFind) Count() uint32 {
	return ufp.count
}

func (ufp *UnionFind) Find(p uint32) uint32 {
	ufp.validate(p)

	root := p
	for root != ufp.parent[root] {
		root = ufp.parent[root]
	}
	for p != root {
		newp := ufp.parent[p]
		ufp.parent[p] = root
		p = newp
	}

	return root
}

func (ufp *UnionFind) Size(p uint32) uint32 {
	return ufp.size[ufp.Find(p)]
}

func (ufp *UnionFind) Connected(p, q uint32) bool {
	return ufp.Find(p) == ufp.Find(q)
}

func (ufp *UnionFind) Union(p, q uint32) {
	rootP := ufp.Find(p)
	rootQ := ufp.Find(q)

	if rootP == rootQ {
		return
	}

	if ufp.size[rootP] < ufp.size[rootQ] {
		ufp.parent[rootP] = rootQ
		ufp.size[rootQ] += ufp.size[rootP]
	} else {
		ufp.parent[rootQ] = rootP
		ufp.size[rootP] += ufp.size[rootQ]
	}

	ufp.count -= 1
}

package main

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

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

func print(a ...interface{}) { fmt.Fprint(writer, a...) }
func scan(a ...interface{})  { fmt.Fscan(reader, a...) }

const (
	N int = 2e5+1
)

var (
	n int
	tree [N][][2]int
	adj [N][]int
	vis [N][2]bool
	cnt [2*N]int
)

func dfs(u int, p int, c int, id int) {
	if vis[u][c] { return }
	vis[u][c] = true
	cnt[id] += 1
	adj[u] = append(adj[u], id)
	for _,e := range tree[u] {
		v,t := e[0],e[1]
		if v!=p && t==c {
			dfs(v,u,c,id)
		}
	}
}

func main() {
	// code GOes here

	scan(&n)
	for i:=1; i<n; i++ {
		var a,b,c int
		scan(&a,&b,&c)
		tree[a] = append(tree[a], [2]int{b,c})
		tree[b] = append(tree[b], [2]int{a,c})
	}

	ans := int64(0)
	id := 0
	for i:=1; i<=n; i++ {
		for c:=0; c<2; c++ {
			dfs(i,0,c,id)
			ans += int64(cnt[id])*int64(cnt[id]-1)
			id++
		}
	}

	for i:=1; i<=n; i++ {
		a,b := adj[i][0], adj[i][1]
		ans += int64(cnt[a]-1)*int64(cnt[b]-1)
	}

	print(ans, "\n")
	writer.Flush()
	return
}

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol1156D(reader io.Reader, writer io.Writer) {
	var find func([]int, int) int
	find = func(fa []int, i int) int {
		if fa[i] != i {
			fa[i] = find(fa, fa[i])
		}
		return fa[i]
	}
	merge := func(fa []int, size []int, from, to int) {
		from, to = find(fa, from), find(fa, to)
		if from != to {
			fa[from] = to
			size[to] += size[from]
		}
	}

	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	fa := [2][]int{}
	size := [2][]int{}
	for i := range fa {
		fa[i] = make([]int, n)
		for j := range fa[i] {
			fa[i][j] = j
		}
		size[i] = make([]int, n)
		for j := range size[i] {
			size[i][j] = 1
		}
	}
	for m := n - 1; m > 0; m-- {
		var v, w, c int
		Fscan(in, &v, &w, &c)
		merge(fa[c], size[c], v-1, w-1)
	}

	ans := int64(0)
	for i := range fa[0] {
		ans += int64(size[0][find(fa[0], i)])*int64(size[1][find(fa[1], i)]) - 1
	}
	Fprint(out, ans)
}

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

package main

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

const (
    N   int = 2e5 + 1
    mod int = 1e9 + 7
)

type pair struct {
    child, wt int
}

var adj [N][]pair
var dp [N][2][2]int64
var ans int64

func dfs(node, par, col int) {
    for _, v := range adj[node] {
        if v.child == par {
            continue
        }
        dfs(v.child, node, v.wt)
        ans += dp[v.child][v.wt][v.wt ^ 1] + 2 * dp[v.child][v.wt][v.wt]
        ans += 2 * dp[node][v.wt][v.wt] * dp[v.child][v.wt][v.wt]
        ans += dp[node][v.wt][v.wt] * dp[v.child][v.wt][v.wt ^ 1]
        ans += dp[node][v.wt][v.wt ^ 1] * dp[v.child][v.wt][v.wt]
        ans += dp[node][v.wt ^ 1][v.wt ^ 1] * dp[v.child][v.wt][v.wt]
        for i := 0; i < 2; i++ {
            dp[node][v.wt][i] += dp[v.child][v.wt][i]
        }
    }
    dp[node][col][col ^ 1] += dp[node][col ^ 1][col ^ 1]
    dp[node][col ^ 1][col] = 0
    dp[node][col ^ 1][col ^ 1] = 0
    dp[node][col][col]++
}

func main() {
    in := bufio.NewReader(os.Stdin)
    var n int
    fmt.Fscan(in, &n)
    for i := 1; i < n; i++ {
        var u, v, c int
        fmt.Fscan(in, &u, &v, &c)
        adj[u] = append(adj[u], pair{v, c})
        adj[v] = append(adj[v], pair{u, c})
    }
    dfs(1, 0, 0)
    fmt.Println(ans)
}

package main

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

const (
    N   int = 2e5
    mod int = 1e9 + 7
)

type pair struct {
    child, wt int
}

var adj [N][]pair
var dp [N][2][2]int64
var ans int64

func dfs(node, par, col int) {
    for _, v := range adj[node] {
        if v.child == par {
            continue
        }
        dfs(v.child, node, v.wt)
        ans += dp[v.child][v.wt][v.wt ^ 1] + 2 * dp[v.child][v.wt][v.wt]
        ans += 2 * dp[node][v.wt][v.wt] * dp[v.child][v.wt][v.wt]
        ans += dp[node][v.wt][v.wt] * dp[v.child][v.wt][v.wt ^ 1]
        ans += dp[node][v.wt ^ 1][v.wt ^ 1] * dp[v.child][v.wt][v.wt]
        for i := 0; i < 2; i++ {
            dp[node][v.wt][i] += dp[v.child][v.wt][i]
        }
    }
    dp[node][col][col ^ 1] += dp[node][col ^ 1][col ^ 1]
    dp[node][col ^ 1][col] = 0
    dp[node][col ^ 1][col ^ 1] = 0
    dp[node][col][col]++
}

func main() {
    in := bufio.NewReader(os.Stdin)
    var n int
    fmt.Fscan(in, &n)
    for i := 1; i < n; i++ {
        var u, v, c int
        fmt.Fscan(in, &u, &v, &c)
        adj[u] = append(adj[u], pair{v, c})
        adj[v] = append(adj[v], pair{u, c})
    }
    dfs(1, 0, 0)
    fmt.Println(ans)
}

package main

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

const (
    N   int = 2e5 + 1
    mod int = 1e9 + 7
)

type pair struct {
    child, wt int
}

var adj [N][]pair
var dp [N][2][2]int64
var ans int64

func dfs(node, par, col int) {
    for _, v := range adj[node] {
        if v.child == par {
            continue
        }
        dfs(v.child, node, v.wt)
        v.wt = 0
        ans += dp[v.child][v.wt][v.wt ^ 1] + 2 * dp[v.child][v.wt][v.wt]
        ans += 2 * dp[node][v.wt][v.wt] * dp[v.child][v.wt][v.wt]
        ans += dp[node][v.wt][v.wt] * dp[v.child][v.wt][v.wt ^ 1]
        ans += dp[node][v.wt ^ 1][v.wt ^ 1] * dp[v.child][v.wt][v.wt]
        for i := 0; i < 2; i++ {
            dp[node][v.wt][i] += dp[v.child][v.wt][i]
        }
        v.wt = 1
        ans += dp[v.child][v.wt][v.wt ^ 1] + 2 * dp[v.child][v.wt][v.wt]
        ans += 2 * dp[node][v.wt][v.wt] * dp[v.child][v.wt][v.wt]
        ans += dp[node][v.wt][v.wt] * dp[v.child][v.wt][v.wt ^ 1]
        ans += dp[node][v.wt ^ 1][v.wt ^ 1] * dp[v.child][v.wt][v.wt]
        for i := 0; i < 2; i++ {
            dp[node][v.wt][i] += dp[v.child][v.wt][i]
        }
    }
    dp[node][col][col ^ 1] += dp[node][col ^ 1][col ^ 1]
    dp[node][col ^ 1][col] = 0
    dp[node][col ^ 1][col ^ 1] = 0
    dp[node][col][col]++
}

func main() {
    in := bufio.NewReader(os.Stdin)
    var n int
    fmt.Fscan(in, &n)
    for i := 1; i < n; i++ {
        var u, v, c int
        fmt.Fscan(in, &u, &v, &c)
        adj[u] = append(adj[u], pair{v, c})
        adj[v] = append(adj[v], pair{u, c})
    }
    dfs(1, 0, 0)
    fmt.Println(ans)
}