Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k ≥ 0) units. A magical box v can be put inside a magical box u, if side length of v is strictly less than the side length of u. In particular, Emuskald can put 4 boxes of side length 2k - 1 into one box of side length 2k, or as in the following figure:  Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes.

The first line of input contains an integer n (1 ≤ n ≤ 105), the number of different sizes of boxes Emuskald has. Each of following n lines contains two integers ki and ai (0 ≤ ki ≤ 109, 1 ≤ ai ≤ 109), which means that Emuskald has ai boxes with side length 2ki. It is guaranteed that all of ki are distinct.

Output a single integer p, such that the smallest magical box that can contain all of Emuskald’s boxes has side length 2p.

NotePicture explanation. If we have 3 boxes with side length 2 and 5 boxes with side length 1, then we can put all these boxes inside a box with side length 4, for example, as shown in the picture.In the second test case, we can put all four small boxes into a box with side length 2.

package main

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

func main(){
	var n int
	var k, a int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	max := 0
	for i:=0; i<n; i++ {
		s := 0
		r.Scan()
		k, _ = strconv.Atoi(r.Text())
		r.Scan()
		a, _ = strconv.Atoi(r.Text())
		s = k
		if a == 1 {
			s += 1
		} else {
			for a>1 {
				a = (a+3)/4
				s += 1
			}
		}
		if s > max {
			max = s
		}
	}
	w.WriteString(strconv.Itoa(max)+"\n")
	w.Flush()
}

// 269A
package main

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

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

func main() {
	var i, n, a, k, ans, r, x int64
	ans = 0
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in, &n)
	for i = 0; i < n; i++ {
		fmt.Fscan(in, &k, &a)
		r = k
		if a == 1 {
			r++
		} else {
			x = 1
			for x < a {
				x *= 4
				r++
			}
		}
		ans = max(ans, r)
	}
	fmt.Fprint(out, ans)
	out.Flush()
}

// 269A-mic
package main

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

func main() {
	var n, a, b, i, h, s int
	z := bufio.NewReader(os.Stdin)
	max := 0
	fmt.Scan(&n)
	for i = 0; i < n; i++ {
		fmt.Fscan(z, &a, &b)
		temp := int(math.Sqrt(float64(b)))
		if temp*temp != b {
			temp = temp + 1
		}

		h = 0
		n1 := 1
		for n1 < temp {
			n1 *= 2
			h++
		}
		h = h + a
		if h >= max {
			max = h
			s = temp
		}
	}
	if s == 1 {
		fmt.Println(max + 1)
	} else {
		fmt.Println(max)
	}
}

// 269A
package main

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

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

func main() {
	var i, n, a, k, ans, r, x int64
	ans = 0
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdin)
	fmt.Fscan(in, &n)
	for i = 0; i < n; i++ {
		fmt.Fscan(in, &k, &a)
		r = k
		if a == 1 {
			r++
		} else {
			x = 1
			for x < a {
				x *= 4
				r++
			}
		}
		ans = max(ans, r)
	}
	fmt.Fprint(out, ans)
	out.Flush()
}

// 269A
package main

import (
	"fmt"
)

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

func main() {
	var i, n, a, k, ans, r, x int64
	ans = 0
	fmt.Scan(&n)
	for i = 0; i < n; i++ {
		fmt.Scan(&k, &a)
		r = k
		if a == 1 {
			r++
		} else {
			x = 1
			for x < a {
				x *= 4
				r++
			}
		}
		ans = max(ans, r)
	}
	fmt.Print(ans)
}

// 269A-mic
package main

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

func main() {
	var n, a, b, i, h int
	z := bufio.NewReader(os.Stdin)
	var s float64
	max := 0
	fmt.Scan(&n)
	for i = 0; i < n; i++ {
		fmt.Fscan(z, &a, &b)
		temp := math.Sqrt(float64(b))
		if int(temp*temp) != b {
			temp = temp + 1
		}

		h = 0
		n1 := 1
		for n1 < int(temp) {
			n1 *= 2
			h++
		}
		h = h + a
		if h >= max {
			max = h
			s = temp
		}
	}
	if s == 1 {
		fmt.Println(max + 1)
	} else {
		fmt.Println(max)
	}
}

// 269A-mic
package main

import (
	"fmt"
	"math"
)

func main() {
	var n, a, b, i, h int
	var s float64
	max := 0
	fmt.Scan(&n)
	for i = 0; i < n; i++ {
		fmt.Scan(&a, &b)
		temp := math.Sqrt(float64(b))
		if temp*temp != float64(b) {
			temp = temp + 1
		}

		h = 0
		n1 := 1
		for float64(n1) < temp {
			n1 *= 2
			h++
		}
		h = h + a
		if h >= max {
			max = h
			s = temp
		}
	}
	if s == 1 {
		fmt.Println(max + 1)
	} else {
		fmt.Println(max)
	}
}

// 269A-mic
package main

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

func main() {
	var n, a, b, i, h int
	z := bufio.NewReader(os.Stdin)
	var s float64
	max := 0
	fmt.Scan(&n)
	for i = 0; i < n; i++ {
		fmt.Fscan(z, &a, &b)
		temp := math.Sqrt(float64(b))
		if int(temp*temp) != b {
			temp = temp + 1
		}

		h = 0
		n1 := 1
		for float64(n1) < temp {
			n1 *= 2
			h++
		}
		h = h + a
		if h >= max {
			max = h
			s = temp
		}
	}
	if s == 1 {
		fmt.Println(max + 1)
	} else {
		fmt.Println(max)
	}
}

// 269A-mic
package main

import (
	"fmt"
	"math"
)

func main() {
	var n, a, b, i, h int
	var s float64
	max := 0
	fmt.Scan(&n)
	for i = 0; i < n; i++ {
		fmt.Scan(&a, &b)
		temp := math.Sqrt(float64(b))
		if temp*temp != float64(b) {
			temp = temp + 1
		}

		h = 0
		n1 := 1
		for n1 < int(temp) {
			n1 *= 2
			h++
		}
		h = h + a
		if h >= max {
			max = h
			s = temp
		}
	}
	if s == 1 {
		fmt.Println(max + 1)
	} else {
		fmt.Println(max)
	}
}


Ksenia has an array $$$a$$$ consisting of $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$. In one operation she can do the following:   choose three distinct indices $$$i$$$, $$$j$$$, $$$k$$$, and then  change all of $$$a_i, a_j, a_k$$$ to $$$a_i \oplus a_j \oplus a_k$$$ simultaneously, where $$$\oplus$$$ denotes the bitwise XOR operation. She wants to make all $$$a_i$$$ equal in at most $$$n$$$ operations, or to determine that it is impossible to do so. She wouldn't ask for your help, but please, help her!

The first line contains one integer $$$n$$$ ($$$3 \leq n \leq 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of $$$a$$$.

Print YES or NO in the first line depending on whether it is possible to make all elements equal in at most $$$n$$$ operations. If it is possible, print an integer $$$m$$$ ($$$0 \leq m \leq n$$$), which denotes the number of operations you do. In each of the next $$$m$$$ lines, print three distinct integers $$$i, j, k$$$, representing one operation.  If there are many such operation sequences possible, print any. Note that you do not have to minimize the number of operations.

NoteIn the first example, the array becomes $$$[4 \oplus 1 \oplus 7, 2, 4 \oplus 1 \oplus 7, 4 \oplus 1 \oplus 7, 2] = [2, 2, 2, 2, 2]$$$.

package main

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

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

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

func solveA() {
	n := 0
	scanf("%d\n", &n)
	for i := 0; i < n; i++ {
		printf("1 ")
	}
	printf("\n")
}

func solveB() {
	n := 0
	scanf("%d\n", &n)
	d := make(map[int]int)
	ans := "NO"
	for k, i := 0, 0; i < n; i++ {
		if i + 1 == n {
			scanf("%d\n", &k)
		} else {
			scanf("%d ", &k)
		}
		d[k]++
		if d[k] > 1 {
			ans = "YES"
		}
	}
	printf(ans + "\n")
}

func solveC() {
	n, m := 0, 0
	scanf("%d %d\n", &n, &m)
	g := make([][]int, n)
	for i := 0; i < n; i++ {
		g[i] = make([]int, m)
	}
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if j + 1 == m {
				scanf("%d\n", &g[i][j])
			} else {
				scanf("%d ", &g[i][j])
			}
			if g[i][j] % 2 != (i + j) % 2 {
				g[i][j]++
			}
		}
	}
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			printf("%d ", g[i][j])
		}
		printf("\n")
	}
}

func solveD() {
	n := 0
	scanf("%d\n", &n)
	v := make([]int, n)
	X := 0
	for i := 0; i < n; i++ {
		if i + 1 == n {
			scanf("%d\n", &v[i])
		} else {
			scanf("%d ", &v[i])
		}
		X ^= v[i]
	}
	if n % 2 == 0 && X != 0 {
		printf("NO\n")
		return
	}
	m := (n - 1) / 2 * 2 + 1
	f1 := make([]int, 0)
	f2 := make([]int, 0)
	f3 := make([]int, 0)
	for i := m - 1; i - 2 >= 0; i -= 2 {
		f1 = append(f1, i)
		f2 = append(f2, i - 1)
		f3 = append(f3, i - 2)
		t := v[i] ^ v[i - 1] ^ v[i - 2]
		v[i], v[i - 1], v[i - 2] = t, t, t
	}
	for i := 1; i < m; i += 2 {
		f1 = append(f1, 0)
		f2 = append(f2, i)
		f3 = append(f3, i + 1)
		t := v[0] ^ v[i] ^ v[i + 1]
		v[0], v[i], v[i + 1] = t, t, t
	}
	printf("YES\n")
	printf("%d\n", len(f1))
	for i := 0; i < len(f1); i++ {
		printf("%d %d %d\n", f1[i] + 1, f2[i] + 1, f3[i] + 1)
	}
}

func main() {
	defer writer.Flush()
	var t = 1
	//scanf("%d\n", &t)
	for ; t > 0; t-- {
		solveD()
	}
}

package main

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

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

	var n int
	Fscan(in, &n)
	s := 0
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
		s ^= a[i]
	}

	ans := [][3]int{}
	if n&1 == 0 {
		if s > 0 {
			Fprintln(out, "NO")
			return
		}
		n--
	}
	for i := 2; i < n; i += 2 {
		ans = append(ans, [3]int{i - 2, i - 1, i})
	}
	for i := 0; i+3 < n; i += 2 {
		ans = append(ans, [3]int{i, i + 1, n - 1})
	}
	Fprintln(out, "YES")
	Fprintln(out, len(ans))
	for _, p := range ans {
		Fprintln(out, p[0]+1, p[1]+1, p[2]+1)
	}
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var n int
	fmt.Fscan(reader, &n)

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

	if n%2 == 1 {
		fmt.Println("YES")
		fmt.Println(n - 1)
		for i := 0; i < n-1; i += 2 {
			fmt.Printf("%d %d %d\n", i+1, i+2, n)
		}
		for i := 0; i < n-1; i += 2 {
			fmt.Printf("%d %d %d\n", i+1, i+2, n)
		}
	} else {
		var xorAll int
		for i := 0; i < n; i++ {
			xorAll ^= a[i]
		}

		if xorAll != 0 {
			fmt.Println("NO")
		} else {
			fmt.Println("YES")
			fmt.Println(n - 2)
			for i := 0; i < n-2; i += 2 {
				fmt.Printf("%d %d %d\n", i+1, i+2, n)
			}
			for i := 0; i < n-2; i += 2 {
				fmt.Printf("%d %d %d\n", i+1, i+2, n)
			}
		}
	}
}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

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

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

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

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	n := sint64()
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	sol(a)
}

func sol(a []int64) {
	if len(a)&1 == 0 {
		tmp := int64(0)
		for _, d := range a {
			tmp ^= d
		}
		if tmp != 0 {
			printf("NO\n")
			return
		}
	}

	printf("YES\n")
	printf("%d\n", (len(a)-1)/2*2)
	for i := 1; i <= len(a)-2; i += 2 {
		printf("%d %d %d\n", i, i+1, len(a))
	}
	for i := 1; i <= len(a)-2; i += 2 {
		printf("%d %d %d\n", i, i+1, len(a))
	}
}

package main

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

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

	var n int
	Fscan(in, &n)
	s := 0
	a := make([]int, n)
	same := true
	for i := range a {
		Fscan(in, &a[i])
		if a[i] != a[0] {
			same = false
		}
		s ^= a[i]
	}
	if same {
		Fprintln(out, "YES")
		Fprintln(out, 0)
		return
	}
	if n&1 == 0 {
		Fprintln(out, "NO")
		return
	}

	ans := [][3]int{}

	for i := 2; i < n; i += 2 {
		ans = append(ans, [3]int{i-2, i-1, i})
	}
	for i := 0; i+3 < n; i+=2 {
		ans = append(ans, [3]int{i,i+1,n-1})
	}

	Fprintln(out, "YES")
	Fprintln(out, len(ans))
	for _, p := range ans {
		Fprintln(out, p[0]+1, p[1]+1, p[2]+1)
	}
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var n int
	fmt.Fscan(reader, &n)

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

	if n%2 == 1 {
		fmt.Println("YES")
		fmt.Println(n/2 + 1)
		for i := 0; i < n-1; i += 2 {
			fmt.Printf("%d %d %d\n", i+1, i+2, n)
		}
		fmt.Printf("%d %d %d\n", 1, 2, n)
	} else {
		var xorAll int
		for i := 0; i < n; i++ {
			xorAll ^= a[i]
		}

		if xorAll != 0 {
			fmt.Println("NO")
		} else {
			fmt.Println("YES")
			for i := 0; i < n-2; i += 2 {
				fmt.Printf("%d %d %d\n", i+1, i+2, n)
			}
			fmt.Printf("%d %d %d\n", n-2, n-1, n)
			fmt.Printf("%d %d %d\n", 1, 2, n)
		}
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var n int
	fmt.Fscan(reader, &n)

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

	if n%2 == 1 {
		fmt.Println("YES")
		fmt.Println(n/2 + 1)
		for i := 0; i < n-1; i += 2 {
			fmt.Printf("%d %d %d\n", i+1, i+2, n)
		}
		fmt.Printf("%d %d %d\n", 1, 2, n)
	} else {
		var xorAll int
		for i := 0; i < n; i++ {
			xorAll ^= a[i]
		}

		if xorAll != 0 {
			fmt.Println("NO")
		} else {
			fmt.Println("YES")
			fmt.Println(n / 2)
			for i := 0; i < n-2; i += 2 {
				fmt.Printf("%d %d %d\n", i+1, i+2, n)
			}
			fmt.Printf("%d %d %d\n", 1, 2, n)
		}
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var n int
	fmt.Fscan(reader, &n)

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

	if n%2 == 1 {
		fmt.Println("YES")
		fmt.Println(n/2 + 1)
		for i := 0; i < n-1; i += 2 {
			fmt.Printf("%d %d %d\n", i+1, i+2, n)
		}
		fmt.Printf("%d %d %d\n", 1, 2, n)
	} else {
		var xorAll int
		for i := 0; i < n; i++ {
			xorAll ^= a[i]
		}

		if xorAll != 0 {
			fmt.Println("NO")
		} else {
			fmt.Println("YES")
			fmt.Println(n/2 + 1)
			for i := 0; i < n-2; i += 2 {
				fmt.Printf("%d %d %d\n", i+1, i+2, n)
			}
			fmt.Printf("%d %d %d\n", n-2, n-1, n)
			fmt.Printf("%d %d %d\n", 1, 2, n)
		}
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var n int
	fmt.Fscan(reader, &n)

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

	if n%2 == 1 {
		fmt.Println("YES")
		fmt.Println(n - 1)
		for i := 0; i < n-1; i += 2 {
			fmt.Printf("%d %d %d\n", i+1, i+2, n)
		}
		for i := 0; i < n-1; i += 2 {
			fmt.Printf("%d %d %d\n", i+1, i+2, n)
		}
	} else {
		var xorAll int
		for i := 0; i < n; i++ {
			xorAll ^= a[i]
		}

		if xorAll != 0 {
			fmt.Println("NO")
		} else {
			fmt.Println("YES")
			fmt.Println(n - 1)
			for i := 0; i < n-2; i += 2 {
				fmt.Printf("%d %d %d\n", i+1, i+2, n)
			}
			for i := 0; i < n-2; i += 2 {
				fmt.Printf("%d %d %d\n", i+1, i+2, n)
			}
		}
	}
}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

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

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

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

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	n := sint64()
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	sol(a)
}

func sol(a []int64) {
	if len(a)&1 == 0 {
		tmp := int64(0)
		for _, d := range a {
			tmp ^= d
		}
		if tmp != 0 {
			printf("NO\n")
			return
		}
	}

	printf("YES\n")
	printf("%d\n", len(a)-2)
	for i := 1; i <= len(a)-2; i += 2 {
		printf("%d %d %d\n", i, i+1, len(a)-1)
	}
	for i := 1; i <= len(a)-2; i += 2 {
		printf("%d %d %d\n", i, i+1, len(a)-1)
	}
}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

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

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

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

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	n := sint64()
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	sol(a)
}

func sol(a []int64) {
	if len(a)&1 == 0 {
		tmp := int64(0)
		for _, d := range a {
			tmp ^= d
		}
		if tmp != 0 {
			printf("NO\n")
			return
		}
		printf("%d\n", len(a)-2)
		for i := 1; i <= len(a)-2; i++ {
			printf("%d %d %d\n", i, i+1, i+2)
		}
		return
	}

	printf("%d\n", len(a)-2)
	for i := 1; i <= len(a)-2; i += 2 {
		for j := i; j >= 1; j -= 2 {
			printf("%d %d %d\n", j, j+1, j+2)
		}
	}
}


Bob came to a cash & carry store, put n items into his trolley, and went to the checkout counter to pay. Each item is described by its price ci and time ti in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. To steal one item Bob needs exactly 1 second. What is the minimum amount of money that Bob will have to pay to the checkout assistant? Remember, please, that it is Bob, who determines the order of items for the checkout assistant.

The first input line contains number n (1 ≤ n ≤ 2000). In each of the following n lines each item is described by a pair of numbers ti, ci (0 ≤ ti ≤ 2000, 1 ≤ ci ≤ 109). If ti is 0, Bob won't be able to steal anything, while the checkout assistant is occupied with item i.

Output one number — answer to the problem: what is the minimum amount of money that Bob will have to pay.

package main

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

var dp [2001][2001]uint64
var t [2001]uint64
var c [2001]uint64

func main() {
	max := uint64(100000000000000000)
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n uint64
	fmt.Fscanf(reader, "%d\r\n", &n)
	for i := uint64(1);i <= n;i ++ {
		fmt.Fscanf(reader, "%d %d\r\n", &t[i], &c[i])
		t[i] ++
	}
	for i := uint64(0);i <= n;i ++ {
		for j := uint64(0);j <= n;j ++ {
			dp[i][j] = max
		}
	}
	dp[0][0] = 0
	for i := uint64(0);i < n;i ++ {
		for j := uint64(0);j <= n;j ++ {
			if dp[i][j] < dp[i + 1][j] {
				dp[i + 1][j] = dp[i][j]
			}
			v := j + t[i + 1]
			if v > n {
				v = n
			}
			if dp[i][j] + c[i + 1] < dp[i + 1][v] {
				dp[i + 1][v] = dp[i][j] + c[i + 1]
			}
		}
	}
	fmt.Printf("%d", dp[n][n] )
}

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 display(dp map[int]int64) {
  fmt.Fprintf(os.Stderr, "{")
  first := true
  for key, value := range dp {
    if first {
      first = false
    } else {
      fmt.Fprintf(os.Stderr, ", ")
    }
    fmt.Fprintf(os.Stderr, "%d: %d", key, value)
  }
  fmt.Fprintf(os.Stderr, " }\n")
}

type Item struct {
  Time int
  Cost int64
}

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

  n := getI()
  best := int64(2000) * 1000 * 1000 * 1000
  dp := map[int]int64{ n: 0 }
  items := make([]*Item, n + 1)
  for i := range items {
    items[i] = &Item{}
  }

  for i := 0; i < n; i++ {
    duration, value := getI(), getI64()
    //display(dp)
    num_items := 0
    for time, cost := range dp {
      items[num_items].Time, items[num_items].Cost = time, cost
      num_items++
    }
    for i := 0; i < num_items; i++ {
      time, cost := items[i].Time, items[i].Cost
      time -= 1 + duration
      cost += value
      if time <= 0 {
        if cost < best {
          best = cost
        }
      } else {
        existing_cost, found := dp[time]
        if !found || cost < existing_cost {
          dp[time] = cost
        }
      }
    }
  }

  //display(dp)
  writer.WriteString(fmt.Sprintf("%d\n", best))
}


According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.

The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.

Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 512*1024), 512*1024)
	sc.Split(bufio.ScanWords)
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())
	sold := make([]int, n)
	sc.Scan()
	dif, _ := strconv.Atoi(sc.Text())

	for i := 0; sc.Scan(); i++ {
		sold[i], _ = strconv.Atoi(sc.Text())
	}
	ans := 0
	for i := 0; i < n-1; i++ {
		for j := i + 1; j < n; j++ {
			if sold[i]-sold[j] <= dif && sold[i]-sold[j] >= -1*dif {
				ans += 2
			}
		}
	}
	fmt.Print(ans)
}

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())
	sold := make([]int, n)
	sc.Scan()
	dif, _ := strconv.Atoi(sc.Text())

	for i := 0; sc.Scan(); i++ {
		sold[i], _ = strconv.Atoi(sc.Text())
	}
	ans := 0
	for i := 0; i < n-1; i++ {
		for j := i + 1; j < n; j++ {
			if sold[i]-sold[j] <= dif && sold[i]-sold[j] >= -dif {
				ans += 2
			}
		}
	}
	fmt.Print(ans)
}

package main

import "fmt"

func main() {
	var n, ans, dif int
	fmt.Scanf("%d %d\n", &n, &dif)
	s := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &s[i])
	}
	for i := 0; i < n-1; i++ {
		for j := i + 1; j < n; j++ {
			if s[i]-s[j] <= dif && s[i]-s[j] >= -dif {
				ans += 2
			}
		}
	}
	fmt.Print(ans)

}

//5 10
//10 20 50 60 65

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 512*1024), 512*1024)
	sc.Split(bufio.ScanWords)
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())
	sold := make([]int, n)
	sc.Scan()
	dif, _ := strconv.Atoi(sc.Text())

	for i := 0; sc.Scan(); i++ {
		sold[i], _ = strconv.Atoi(sc.Text())
	}
	ans := 0
	for i := 0; i < n-1; i++ {
		for j := i + 1; j < n; j++ {
			if sold[i]-sold[j] <= dif && sold[i]-sold[j] >= -dif {
				ans += 2
			}
		}
	}
	fmt.Print(ans)
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var soldiers, height int
	fmt.Scan(&soldiers, &height)

	var heights []int

	for i := 0; i < soldiers; i++ {
		var soldier int
		fmt.Scan(&soldier)

		heights = append(heights, soldier)
	}

	var count int
	for index, soldier := range heights {
		for i := 0; i < soldiers; i++ {
			if i != index {
				var difference = int(math.Abs(float64(soldier - heights[i])))
				if  difference <= height {
					count ++
				}
			}
		}
	}

	fmt.Printf("%d", count)
}

// 512.CodeForce 32A-Michael542
package main

import (
    "fmt"
)

func main() {
    var n, d, cou int
    fmt.Scan(&n, &d)
    z := make([]int, n)
    for x := 0; x < n; x++ {
        fmt.Scan(&z[x])
    }
    for c := 0; c < n-1; c++ {
        for b := c + 1; b < n; b++ {
            if z[c]-z[b] <= d && z[b]-z[c] <= d {
                cou++
            }
        }
    }
    fmt.Println(cou * 2)
}

package main

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

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

	var soldiersCount, maxDifference int

	fmt.Fscan(reader, &soldiersCount, &maxDifference)

	soldiersHeight := make([]int, soldiersCount)

	for i := 0; i < soldiersCount; i++ {
		fmt.Fscan(reader, &soldiersHeight[i])
	}

	sort.Ints(soldiersHeight)

	var answer = 0
	for i := 0; i < soldiersCount-1; i++ {
		var cnt int

		for j := i + 1; j < soldiersCount && soldiersHeight[j]-soldiersHeight[i] <= maxDifference; j++ {
			cnt++
		}

		answer += cnt * 2
	}

	fmt.Println(answer)
}

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 512*1024), 512*1024)
	sc.Split(bufio.ScanWords)
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())
	sold := make([]int, n)
	sc.Scan()
	dif, _ := strconv.Atoi(sc.Text())

	for i := 0; sc.Scan(); i++ {
		sold[i], _ = strconv.Atoi(sc.Text())
	}
	ans := 0
	for i := 0; i < n-1; i++ {
		for j := i + 1; j < n; j++ {
			if sold[i]-sold[j] < dif && sold[i]-sold[j] > -dif {
				ans += 2
			}
		}
	}
}

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 512*1024), 512*1024)
	sc.Split(bufio.ScanWords)
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())
	sold := make([]int, n)
	sc.Scan()
	dif, _ := strconv.Atoi(sc.Text())

	for i := 0; sc.Scan(); i++ {
		sold[i], _ = strconv.Atoi(sc.Text())
	}
	ans := 0
	for i := 0; i < n-1; i++ {
		for j := i + 1; j < n; j++ {
			if sold[i]-sold[j] < dif && sold[i]-sold[j] > -dif {
				ans += 2
			}
		}
	}
	fmt.Print(ans)
}


You are given an array $$$a_1, a_2 \dots a_n$$$. Calculate the number of tuples $$$(i, j, k, l)$$$ such that:   $$$1 \le i < j < k < l \le n$$$;  $$$a_i = a_k$$$ and $$$a_j = a_l$$$;

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$4 \le n \le 3000$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the array $$$a$$$. It's guaranteed that the sum of $$$n$$$ in one test doesn't exceed $$$3000$$$.

For each test case, print the number of described tuples.

NoteIn the first test case, for any four indices $$$i < j < k < l$$$ are valid, so the answer is the number of tuples.In the second test case, there are $$$2$$$ valid tuples:   $$$(1, 2, 4, 6)$$$: $$$a_1 = a_4$$$ and $$$a_2 = a_6$$$;  $$$(1, 3, 4, 6)$$$: $$$a_1 = a_4$$$ and $$$a_3 = a_6$$$.

package main

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

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

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

func main() {
	// STDOUT MUST BE FLUSHED MANUALLY!!!
	defer writer.Flush()
	var t, n int
	scanf("%d\n", &t)

	i := 0
	for i < t {
		scanf("%d\n", &n)
		var temp int
		var j int
		var arr []int
		for j < n {
			if j != n-1 {
				scanf("%d ", &temp)
				arr = append(arr, temp)
			} else {
				scanf("%d\n", &temp)
				arr = append(arr, temp)
			}
			j++
		}

		pre := make(map[int]int64)
		var ans int64
		// fmt.Println(arr)
		for j := 0; j < n; j++ {
			suf := make(map[int]int64)
			for k := n - 1; k > j; k-- {
				ans += pre[arr[k]] * suf[arr[j]]
				suf[arr[k]] += 1
			}
			pre[arr[j]] += 1
		}

		printf("%v\n", ans)
		i++
	}
}

package main

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

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

	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--

		n := readNum(reader)
		A := readNNums(reader, n)
		res := solve(n, A)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}
	fmt.Print(buf.String())
}

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

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

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

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

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

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

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

	return i
}

func solve(n int, A []int) int64 {
	cnt := make([][]int64, n+1)
	for i := 0; i <= n; i++ {
		cnt[i] = make([]int64, n+1)
	}

	var res int64

	for j := n - 1; j >= 0; j-- {
		k := j + 1
		for l := k + 1; l < n; l++ {
			cnt[A[k]][A[l]]++
		}
		for i := 0; i < j; i++ {
			res += cnt[A[i]][A[j]]
		}
	}

	return res
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.NextInt(); t > 0; t-- {
		n := io.NextInt()
		a := io.NextInts(n)

		ans := int64(0)
		p := make([]int, n+1)
		for i, x := range a {
			s := make([]int, n+1)
			for j := n - 1; j > i; j-- {
				y := a[j]
				ans += int64(s[x]) * int64(p[y])
				s[y]++
			}
			p[x]++
		}
		io.Println(ans)
	}
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

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

	in := func() int64 {
		sc.Scan()
		i, _ := strconv.ParseInt(sc.Text(), 10, 64)
		return i
	}

	for t := in(); t > 0; t-- {
		n := in()
		a := make([]int64, n)

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

		m := make([]int64, n*n+n+1)

		var tot uint64 = 0

		for j := n-1; j >= 0; j-- {
			k := j+1

			for l := k+1; l < n; l++ {
				m[a[k]*n+a[l]]++
			}

			for i := j-1; i >= 0; i-- {
				tot += uint64(m[a[i]*n+a[j]])
			}
		}

		fmt.Println(tot)
	}
}

/*
URL:
https://codeforces.com/contest/1400/problem/D
*/

package main

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

var (
	t int

	n int
	A []int
)

func main() {
	t = readi()

	for tc := 0; tc < t; tc++ {
		n = readi()
		A = readis(n)

		solve()
	}
}

func solve() {
	S := make([][]int, n)
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			if A[i] != A[j] {
				continue
			}
			S[i] = append(S[i], j)
		}
	}

	ft := NewFenwickTree(n + 5)

	ans := int64(0)
	// for _, seg := range S {
	// 	ans += ft.Sum(n) - ft.Sum(seg.s)
	// 	ft.Add(seg.t, 1)
	// }
	for i := 0; i < n; i++ {
		if i > 0 {
			val := ft.Sum(i) - ft.Sum(i-1)
			ft.Add(i, -val)
		}

		for _, t := range S[i] {
			ans += int64(ft.Sum(t - 1))
		}
		for _, t := range S[i] {
			ft.Add(t, 1)
		}
	}

	fmt.Println(ans)
}

// Public methods
// ft := NewFenwickTree(200000 + 5)
// s := ft.Sum(i) 						// Sum of [1, i] (1-based)
// ft.Add(i, x) 							// Add x to i (1-based)
// idx := ft.LowerBound(w) 		// minimum idx such that bit.Sum(idx) >= w

type FenwickTree struct {
	dat     []int
	n       int
	minPow2 int
}

// n(>=1) is number of elements of original data
func NewFenwickTree(n int) *FenwickTree {
	ft := new(FenwickTree)

	ft.dat = make([]int, n+1)
	ft.n = n

	ft.minPow2 = 1
	for {
		if (ft.minPow2 << 1) > n {
			break
		}
		ft.minPow2 <<= 1
	}

	return ft
}

// Sum of [1, i](1-based)
func (ft *FenwickTree) Sum(i int) int {
	s := 0

	for i > 0 {
		s += ft.dat[i]
		i -= i & (-i)
	}

	return s
}

// Add x to i(1-based)
func (ft *FenwickTree) Add(i, x int) {
	for i <= ft.n {
		ft.dat[i] += x
		i += i & (-i)
	}
}

// LowerBound returns minimum i such that bit.Sum(i) >= w.
func (ft *FenwickTree) LowerBound(w int) int {
	if w <= 0 {
		return 0
	}

	x := 0
	for k := ft.minPow2; k > 0; k /= 2 {
		if x+k <= ft.n && ft.dat[x+k] < w {
			w -= ft.dat[x+k]
			x += k
		}
	}

	return x + 1
}

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

/********** common constants **********/

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

/********** 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...)

/*********** Input ***********/

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

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

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

// readi returns an integer.
func readi() int {
	return int(readInt64())
}
func readi2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func readi3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func readi4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return readInt64()
}
func readll2() (int64, int64) {
	return readInt64(), readInt64()
}
func readll3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func readll4() (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
}

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

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	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())
}

/*********** Output ***********/

// 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])
		res = append(res, []rune(str)...)

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

	return string(res)
}

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

	for i := 0; i < len(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)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

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

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

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

/*
URL:
https://codeforces.com/contest/1400/problem/D
*/

package main

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

var (
	t int

	n int
	A []int
)

func main() {
	t = readi()
	for tc := 0; tc < t; tc++ {
		n = readi()
		A = readis(n)

		solve()
	}
}

func solve() {
	ans := int64(0)
	// memo := make(map[[2]int]int)
	// memo := make(map[Segment]int)
	memo := [3000 + 5][3000 + 5]int{}
	for j := n - 1; j >= 0; j-- {
		k := j + 1
		for l := k + 1; l < n; l++ {
			// memo[[2]int{A[k], A[l]}]++

			// tmp := Segment{int16(A[k]), int16(A[l])}
			// memo[tmp]++
			memo[A[k]][A[l]]++
		}

		for i := 0; i < j; i++ {
			// tmp := Segment{int16(A[i]), int16(A[j])}
			// ans += int64(memo[tmp])
			ans += int64(memo[A[i]][A[j]])
		}
	}
	fmt.Println(ans)
}

type Segment struct {
	l, r int16
}

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

/********** common constants **********/

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

/********** 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...)

/*********** Input ***********/

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

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

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

// readi returns an integer.
func readi() int {
	return int(readInt64())
}
func readi2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func readi3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func readi4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return readInt64()
}
func readll2() (int64, int64) {
	return readInt64(), readInt64()
}
func readll3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func readll4() (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
}

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

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	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())
}

/*********** Output ***********/

// 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])
		res = append(res, []rune(str)...)

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

	return string(res)
}

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

	for i := 0; i < len(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)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

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

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

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

/*
URL:
https://codeforces.com/contest/1400/problem/D
*/

package main

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

var (
	t int

	n int
	A []int
)

func main() {
	t = readi()

	for tc := 0; tc < t; tc++ {
		n = readi()
		A = readis(n)

		solve()
	}
}

func solve() {
	S := make([][]int, n)
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			if A[i] != A[j] {
				continue
			}
			S[i] = append(S[i], j)
		}
	}

	ft := NewFenwickTree(n)

	ans := int64(0)
	for i := 0; i < n; i++ {
		if i > 0 {
			val := ft.Sum(i) - ft.Sum(i-1)
			ft.Add(i, -val)
		}

		for _, t := range S[i] {
			ans += int64(ft.Sum(t - 1))
		}
		for _, t := range S[i] {
			ft.Add(t, 1)
		}
	}

	fmt.Println(ans)
}

// Public methods
// ft := NewFenwickTree(200000 + 5)
// s := ft.Sum(i) 						// Sum of [1, i] (1-based)
// ft.Add(i, x) 							// Add x to i (1-based)
// idx := ft.LowerBound(w) 		// minimum idx such that bit.Sum(idx) >= w

type FenwickTree struct {
	dat     []int
	n       int
	minPow2 int
}

// n(>=1) is number of elements of original data
func NewFenwickTree(n int) *FenwickTree {
	ft := new(FenwickTree)

	ft.dat = make([]int, n+1)
	ft.n = n

	ft.minPow2 = 1
	for {
		if (ft.minPow2 << 1) > n {
			break
		}
		ft.minPow2 <<= 1
	}

	return ft
}

// Sum of [1, i](1-based)
func (ft *FenwickTree) Sum(i int) int {
	s := 0

	for i > 0 {
		s += ft.dat[i]
		i -= i & (-i)
	}

	return s
}

// Add x to i(1-based)
func (ft *FenwickTree) Add(i, x int) {
	for i <= ft.n {
		ft.dat[i] += x
		i += i & (-i)
	}
}

// LowerBound returns minimum i such that bit.Sum(i) >= w.
func (ft *FenwickTree) LowerBound(w int) int {
	if w <= 0 {
		return 0
	}

	x := 0
	for k := ft.minPow2; k > 0; k /= 2 {
		if x+k <= ft.n && ft.dat[x+k] < w {
			w -= ft.dat[x+k]
			x += k
		}
	}

	return x + 1
}

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

/********** common constants **********/

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

/********** 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...)

/*********** Input ***********/

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

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

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

// readi returns an integer.
func readi() int {
	return int(readInt64())
}
func readi2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func readi3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func readi4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return readInt64()
}
func readll2() (int64, int64) {
	return readInt64(), readInt64()
}
func readll3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func readll4() (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
}

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

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	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())
}

/*********** Output ***********/

// 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])
		res = append(res, []rune(str)...)

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

	return string(res)
}

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

	for i := 0; i < len(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)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

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

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

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

package main

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

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

	var T, n int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		ans := int64(0)
		cnt := make([]int64, n+1)
		cnt[a[0]]++
		for j := 1; j < n-2; j++ {
			v := a[j]
			c := cnt[a[j+1]]
			for _, w := range a[j+2:] {
				if w == v {
					ans += c
				}
				c += cnt[w]
			}
			cnt[v]++
		}
		Fprintln(out, ans)
	}
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

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

		a := make([]int, n)
		for i, _ := range a {
			fmt.Fscan(reader, &a[i])
			a[i]--
		}

		solve(n, a)
	}
}

func solve(n int, a []int) {
	count := make([]int, n)
	countLeft := make([]int, n)
	countRight := make([]int, n)

	for i := 0; i < n; i++ {
		count[a[i]]++
	}

	var ans int64
	for j := 0; j < n; j++ {
		for i := 0; i < n; i++ {
			countRight[i] = 0
		}

		for k := n - 1; k > j; k-- {
			ans += int64(countLeft[a[k]] * countRight[a[j]])
			countRight[a[k]]++
		}
		countLeft[a[j]]++
	}

	fmt.Println(ans)
}

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

	return b
}

package main

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

func solve(arr []int) int64 {
	pos := make(map[int][]int)
	for i, num := range arr {
		pos[num] = append(pos[num], i)
	}
	n := len(arr)
	greater := make(map[int][]int)
	less := make(map[int][]int)
	for num, indices := range pos {
		greater[num] = make([]int, n)
		less[num] = make([]int, n)
		// fill the less array
		for i := 0; i < indices[0] + 1; i++ {
			less[num][i] = 0
		}
		currCount := 1
		for idx := 0; idx < len(indices) - 1; idx++ {
			i1 := indices[idx]
			i2 := indices[idx + 1]
			for i := i1 + 1; i < i2 + 1; i++ {
				less[num][i] = currCount
			}
			currCount++
		}
		for i := indices[len(indices) - 1] + 1; i < n; i++ {
			less[num][i] = currCount
		}
		// fill the greater array
		for i := n - 1; i > indices[len(indices) - 1] - 1; i-- {
			greater[num][i] = 0
		}
		currCount = 1
		for idx := len(indices) - 1; idx > 0; idx-- {
			i1 := indices[idx - 1]
			i2 := indices[idx]
			for i := i2 - 1; i > i1 - 1; i-- {
				greater[num][i] = currCount
			}
			currCount += 1
		}
		for i := indices[0] - 1; i >= 0; i-- {
			greater[num][i] = currCount
		}
	}

	// solve the question
	var ans int64
	for i := 1; i < len(arr); i++ {
		for j := i + 1; j < len(arr); j++ {
			ans += int64(greater[arr[i]][j]) * int64(less[arr[j]][i])
		}
	}
	return ans
}

func readNextInt(sc *bufio.Scanner) int {
	sc.Scan()
	s := sc.Text()
	i, _ := strconv.Atoi(s)
	return i
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	t := readNextInt(sc)
	for tc := 0; tc < t; tc++ {
		n := readNextInt(sc)
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = readNextInt(sc)
		}
		fmt.Println(solve(arr))
	}
}

package main

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

func solve(arr []int) int64 {
	pos := make(map[int][]int)
	for i, num := range arr {
		pos[num] = append(pos[num], i)
	}
	n := len(arr)
	greater := make(map[int][]int)
	less := make(map[int][]int)
	wg := sync.WaitGroup{}
	for num := range pos {
		greater[num] = make([]int, n)
		less[num] = make([]int, n)
	}
	for num, indices := range pos {
		wg.Add(1)
		go func(num int, indices []int) {
			// fill the less array
			for i := 0; i < indices[0] + 1; i++ {
				less[num][i] = 0
			}
			currCount := 1
			for idx := 0; idx < len(indices) - 1; idx++ {
				i1 := indices[idx]
				i2 := indices[idx + 1]
				for i := i1 + 1; i < i2 + 1; i++ {
					less[num][i] = currCount
				}
				currCount++
			}
			for i := indices[len(indices) - 1] + 1; i < n; i++ {
				less[num][i] = currCount
			}
			// fill the greater array
			for i := n - 1; i > indices[len(indices) - 1] - 1; i-- {
				greater[num][i] = 0
			}
			currCount = 1
			for idx := len(indices) - 1; idx > 0; idx-- {
				i1 := indices[idx - 1]
				i2 := indices[idx]
				for i := i2 - 1; i > i1 - 1; i-- {
					greater[num][i] = currCount
				}
				currCount += 1
			}
			for i := indices[0] - 1; i >= 0; i-- {
				greater[num][i] = currCount
			}
			wg.Done()
		}(num, indices)
	}
	wg.Wait()

	// solve the question
	var ans int64
	for i := 1; i < len(arr); i++ {
		for j := i + 1; j < len(arr); j++ {
			ans += int64(greater[arr[i]][j]) * int64(less[arr[j]][i])
		}
	}
	return ans
}

func readNextInt(sc *bufio.Scanner) int {
	sc.Scan()
	s := sc.Text()
	i, _ := strconv.Atoi(s)
	return i
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	t := readNextInt(sc)
	//wg := sync.WaitGroup{}
	//mutex := make(chan struct{}, 20)
	//for i := 0; i < 20; i++ {
	//
	//}
	for tc := 0; tc < t; tc++ {
		//wg.Add(1)
		n := readNextInt(sc)
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = readNextInt(sc)
		}
		fmt.Println(solve(arr))
	}
}

package main

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

func solve(arr []int) int64 {
	pos := make(map[int][]int)
	for i, num := range arr {
		pos[num] = append(pos[num], i)
	}
	n := len(arr)
	greater := make(map[int][]int)
	less := make(map[int][]int)
	wg := sync.WaitGroup{}
	mutex := make(chan bool, 5)
	for i := 0; i < 5; i++ {
		mutex <- true
	}
	for num := range pos {
		greater[num] = make([]int, n)
		less[num] = make([]int, n)
	}
	for num, indices := range pos {
		wg.Add(1)
		<-mutex
		go func(num int, indices []int) {
			// fill the less array
			for i := 0; i < indices[0] + 1; i++ {
				less[num][i] = 0
			}
			currCount := 1
			for idx := 0; idx < len(indices) - 1; idx++ {
				i1 := indices[idx]
				i2 := indices[idx + 1]
				for i := i1 + 1; i < i2 + 1; i++ {
					less[num][i] = currCount
				}
				currCount++
			}
			for i := indices[len(indices) - 1] + 1; i < n; i++ {
				less[num][i] = currCount
			}
			// fill the greater array
			for i := n - 1; i > indices[len(indices) - 1] - 1; i-- {
				greater[num][i] = 0
			}
			currCount = 1
			for idx := len(indices) - 1; idx > 0; idx-- {
				i1 := indices[idx - 1]
				i2 := indices[idx]
				for i := i2 - 1; i > i1 - 1; i-- {
					greater[num][i] = currCount
				}
				currCount += 1
			}
			for i := indices[0] - 1; i >= 0; i-- {
				greater[num][i] = currCount
			}
			wg.Done()
		}(num, indices)
		mutex <- true
	}
	wg.Wait()

	// solve the question
	var ans int64
	for i := 1; i < len(arr); i++ {
		for j := i + 1; j < len(arr); j++ {
			ans += int64(greater[arr[i]][j]) * int64(less[arr[j]][i])
		}
	}
	return ans
}

func readNextInt(sc *bufio.Scanner) int {
	sc.Scan()
	s := sc.Text()
	i, _ := strconv.Atoi(s)
	return i
}

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

	for tc := 0; tc < t; tc++ {
		n := readNextInt(sc)
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = readNextInt(sc)
		}
		fmt.Println(solve(arr))
	}
}

package main

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

func solve(arr []int) int64 {
	pos := make(map[int][]int)
	for i, num := range arr {
		pos[num] = append(pos[num], i)
	}
	n := len(arr)
	greater := make(map[int][]int)
	less := make(map[int][]int)
	wg := sync.WaitGroup{}
	mutex := make(chan bool, 20)
	for i := 0; i < 20; i++ {
		mutex <- true
	}
	for num := range pos {
		greater[num] = make([]int, n)
		less[num] = make([]int, n)
	}
	for num, indices := range pos {
		wg.Add(1)
		<-mutex
		go func(num int, indices []int) {
			// fill the less array
			for i := 0; i < indices[0] + 1; i++ {
				less[num][i] = 0
			}
			currCount := 1
			for idx := 0; idx < len(indices) - 1; idx++ {
				i1 := indices[idx]
				i2 := indices[idx + 1]
				for i := i1 + 1; i < i2 + 1; i++ {
					less[num][i] = currCount
				}
				currCount++
			}
			for i := indices[len(indices) - 1] + 1; i < n; i++ {
				less[num][i] = currCount
			}
			// fill the greater array
			for i := n - 1; i > indices[len(indices) - 1] - 1; i-- {
				greater[num][i] = 0
			}
			currCount = 1
			for idx := len(indices) - 1; idx > 0; idx-- {
				i1 := indices[idx - 1]
				i2 := indices[idx]
				for i := i2 - 1; i > i1 - 1; i-- {
					greater[num][i] = currCount
				}
				currCount += 1
			}
			for i := indices[0] - 1; i >= 0; i-- {
				greater[num][i] = currCount
			}
			wg.Done()
		}(num, indices)
		mutex <- true
	}
	wg.Wait()

	// solve the question
	var ans int64
	for i := 1; i < len(arr); i++ {
		for j := i + 1; j < len(arr); j++ {
			ans += int64(greater[arr[i]][j]) * int64(less[arr[j]][i])
		}
	}
	return ans
}

func readNextInt(sc *bufio.Scanner) int {
	sc.Scan()
	s := sc.Text()
	i, _ := strconv.Atoi(s)
	return i
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	t := readNextInt(sc)
	//wg := sync.WaitGroup{}
	//mutex := make(chan struct{}, 20)
	//for i := 0; i < 20; i++ {
	//
	//}
	for tc := 0; tc < t; tc++ {
		//wg.Add(1)
		n := readNextInt(sc)
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = readNextInt(sc)
		}
		fmt.Println(solve(arr))
	}
}

package main

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

func solve(arr []int) int64 {
	pos := make(map[int][]int)
	for i, num := range arr {
		pos[num] = append(pos[num], i)
	}
	n := len(arr)
	greater := make(map[int][]int)
	less := make(map[int][]int)
	wg := sync.WaitGroup{}
	mutex := make(chan bool, 2)
	for i := 0; i < 2; i++ {
		mutex <- true
	}
	for num := range pos {
		greater[num] = make([]int, n)
		less[num] = make([]int, n)
	}
	for num, indices := range pos {
		wg.Add(1)
		<-mutex
		go func(num int, indices []int) {
			// fill the less array
			for i := 0; i < indices[0] + 1; i++ {
				less[num][i] = 0
			}
			currCount := 1
			for idx := 0; idx < len(indices) - 1; idx++ {
				i1 := indices[idx]
				i2 := indices[idx + 1]
				for i := i1 + 1; i < i2 + 1; i++ {
					less[num][i] = currCount
				}
				currCount++
			}
			for i := indices[len(indices) - 1] + 1; i < n; i++ {
				less[num][i] = currCount
			}
			// fill the greater array
			for i := n - 1; i > indices[len(indices) - 1] - 1; i-- {
				greater[num][i] = 0
			}
			currCount = 1
			for idx := len(indices) - 1; idx > 0; idx-- {
				i1 := indices[idx - 1]
				i2 := indices[idx]
				for i := i2 - 1; i > i1 - 1; i-- {
					greater[num][i] = currCount
				}
				currCount += 1
			}
			for i := indices[0] - 1; i >= 0; i-- {
				greater[num][i] = currCount
			}
			wg.Done()
		}(num, indices)
		mutex <- true
	}
	wg.Wait()

	// solve the question
	var ans int64
	for i := 1; i < len(arr); i++ {
		for j := i + 1; j < len(arr); j++ {
			ans += int64(greater[arr[i]][j]) * int64(less[arr[j]][i])
		}
	}
	return ans
}

func readNextInt(sc *bufio.Scanner) int {
	sc.Scan()
	s := sc.Text()
	i, _ := strconv.Atoi(s)
	return i
}

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

	for tc := 0; tc < t; tc++ {
		n := readNextInt(sc)
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = readNextInt(sc)
		}
		fmt.Println(solve(arr))
	}
}

package main

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

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

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

func main() {
	// STDOUT MUST BE FLUSHED MANUALLY!!!
	defer writer.Flush()
	var t, n int
	scanf("%d\n", &t)

	i := 0
	for i < t {
		scanf("%d\n", &n)
		j := 0
		var arr []int
		var temp int
		for j < n {
			if j != n-1 {
				scanf("%d ", &temp)
				arr = append(arr, temp)
			} else {
				scanf("%d\n", &temp)
				arr = append(arr, temp)
			}
			j++
		}

		pre := make(map[int]map[int]int)
		j = 0
		for j < n {
			p := pre[j-1]
			if p == nil {
				p = make(map[int]int)
			}

			c := make(map[int]int)
			for k, v := range p {
				c[k] = v
			}

			c[arr[j]] += 1

			pre[j] = c
			j++
		}

		suf := make(map[int]map[int]int)
		j = n - 1
		for j >= 0 {
			p := suf[j+1]
			if p == nil {
				p = make(map[int]int)
			}

			c := make(map[int]int)
			for k, v := range p {
				c[k] = v
			}

			c[arr[j]] += 1
			suf[j] = c
			j--
		}

		ans := 0

		for j := 1; j < n-2; j++ {
			for k := j + 1; k < n-1; k++ {
				ans += pre[j-1][arr[k]] * suf[k+1][arr[j]]
			}
		}

		printf("%d\n", ans)
		i++
	}
}

package main

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

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

	tc := readNum(reader)
	var buf bytes.Buffer
	for tc > 0 {
		tc--

		n := readNum(reader)
		A := readNNums(reader, n)
		res := solve(n, A)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}
	fmt.Print(buf.String())
}

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

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

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

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

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

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

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

	return i
}

func solve(n int, A []int) int {
	cnt := make([][]int, n+1)
	for i := 0; i <= n; i++ {
		cnt[i] = make([]int, n+1)
	}

	var res int

	for j := n - 1; j >= 0; j-- {
		k := j + 1
		for l := k + 1; l < n; l++ {
			cnt[A[k]][A[l]]++
		}
		for i := 0; i < j; i++ {
			res += cnt[A[i]][A[j]]
		}
	}

	return res
}

package main

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

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

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

	for t := in(); t > 0; t-- {
		n := in()
		a := make([]int, n)

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

		m := make(map[int]int)
		tot := 0

		for j := n-1; j >= 0; j-- {
			k := j+1

			for l := k+1; l < n; l++ {
				m[a[k]*n+a[l]]++
			}

			for i := j-1; i >= 0; i-- {
				tot += m[a[i]*n+a[j]]
			}
		}

		fmt.Println(tot)
	}
}

/*
URL:
https://codeforces.com/contest/1400/problem/D
*/

package main

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

var (
	t int

	n int
	A []int
)

func main() {
	t = readi()

	for tc := 0; tc < t; tc++ {
		n = readi()
		A = readis(n)

		solve()
	}
}

func solve() {
	S := make([][]int, n)
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			if A[i] != A[j] {
				continue
			}
			S[i] = append(S[i], j)
		}
	}

	ft := NewFenwickTree(n + 5)

	ans := 0
	// for _, seg := range S {
	// 	ans += ft.Sum(n) - ft.Sum(seg.s)
	// 	ft.Add(seg.t, 1)
	// }
	for i := 0; i < n; i++ {
		if i > 0 {
			val := ft.Sum(i) - ft.Sum(i-1)
			ft.Add(i, -val)
		}

		for _, t := range S[i] {
			ans += ft.Sum(t - 1)
		}
		for _, t := range S[i] {
			ft.Add(t, 1)
		}
	}

	fmt.Println(ans)
}

// Public methods
// ft := NewFenwickTree(200000 + 5)
// s := ft.Sum(i) 						// Sum of [1, i] (1-based)
// ft.Add(i, x) 							// Add x to i (1-based)
// idx := ft.LowerBound(w) 		// minimum idx such that bit.Sum(idx) >= w

type FenwickTree struct {
	dat     []int
	n       int
	minPow2 int
}

// n(>=1) is number of elements of original data
func NewFenwickTree(n int) *FenwickTree {
	ft := new(FenwickTree)

	ft.dat = make([]int, n+1)
	ft.n = n

	ft.minPow2 = 1
	for {
		if (ft.minPow2 << 1) > n {
			break
		}
		ft.minPow2 <<= 1
	}

	return ft
}

// Sum of [1, i](1-based)
func (ft *FenwickTree) Sum(i int) int {
	s := 0

	for i > 0 {
		s += ft.dat[i]
		i -= i & (-i)
	}

	return s
}

// Add x to i(1-based)
func (ft *FenwickTree) Add(i, x int) {
	for i <= ft.n {
		ft.dat[i] += x
		i += i & (-i)
	}
}

// LowerBound returns minimum i such that bit.Sum(i) >= w.
func (ft *FenwickTree) LowerBound(w int) int {
	if w <= 0 {
		return 0
	}

	x := 0
	for k := ft.minPow2; k > 0; k /= 2 {
		if x+k <= ft.n && ft.dat[x+k] < w {
			w -= ft.dat[x+k]
			x += k
		}
	}

	return x + 1
}

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

/********** common constants **********/

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

/********** 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...)

/*********** Input ***********/

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

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

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

// readi returns an integer.
func readi() int {
	return int(readInt64())
}
func readi2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func readi3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func readi4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return readInt64()
}
func readll2() (int64, int64) {
	return readInt64(), readInt64()
}
func readll3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func readll4() (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
}

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

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	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())
}

/*********** Output ***********/

// 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])
		res = append(res, []rune(str)...)

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

	return string(res)
}

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

	for i := 0; i < len(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)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

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

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

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

		a := make([]int, n)
		for i, _ := range a {
			fmt.Fscan(reader, &a[i])
			a[i]--
		}

		solve(n, a)
	}
}

func solve(n int, a []int) {
	count := make([]int, n)
	countLeft := make([]int, n)
	countRight := make([]int, n)

	for i := 0; i < n; i++ {
		count[a[i]]++
	}

	ans := 0
	for j := 0; j < n; j++ {
		for i := 0; i < n; i++ {
			countRight[i] = 0
		}

		for k := n - 1; k > j; k-- {
			ans += countLeft[a[k]] * countRight[a[j]]
			countRight[a[k]]++
		}
		countLeft[a[j]]++
	}

	fmt.Println(ans)
}

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

	return b
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

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

		a := make([]int, n)
		for i, _ := range a {
			fmt.Fscan(reader, &a[i])
		}

		solve(n, a)
	}
}

func solve(n int, a []int) {
	count := make([]int, 3001)
	countLeft := make([]int, 3001)
	countRight := make([]int, 3001)

	for i := 0; i < n; i++ {
		count[a[i]]++
	}

	copy(countLeft, count)
	for i := n - 3; i < n; i++ {
		countLeft[a[i]]--
	}

	ans := 0
	for j := n - 3; j > 0; j-- {
		copy(countRight, count)
		for i := 0; i <= j+1; i++ {
			countRight[a[i]]--
		}

		for k := j + 1; k < n-1; k++ {
			ans += max(countLeft[a[k]], 0) * max(countRight[a[j]], 0)
			countRight[a[k+1]]--
		}
		countLeft[a[j-1]]--
	}

	fmt.Println(ans)
}

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

	return b
}

package main

import (
	"bufio"
	"strconv"
	"sync"
)

func solve(arr []int) int64 {
	pos := make(map[int][]int)
	for i, num := range arr {
		pos[num] = append(pos[num], i)
	}
	n := len(arr)
	greater := make(map[int][]int)
	less := make(map[int][]int)
	wg := sync.WaitGroup{}
	mutex := make(chan bool, 20)
	for i := 0; i < 20; i++ {
		mutex <- true
	}
	for num := range pos {
		greater[num] = make([]int, n)
		less[num] = make([]int, n)
	}
	for num, indices := range pos {
		wg.Add(1)
		<-mutex
		go func(num int, indices []int) {
			// fill the less array
			for i := 0; i < indices[0] + 1; i++ {
				less[num][i] = 0
			}
			currCount := 1
			for idx := 0; idx < len(indices) - 1; idx++ {
				i1 := indices[idx]
				i2 := indices[idx + 1]
				for i := i1 + 1; i < i2 + 1; i++ {
					less[num][i] = currCount
				}
				currCount++
			}
			for i := indices[len(indices) - 1] + 1; i < n; i++ {
				less[num][i] = currCount
			}
			// fill the greater array
			for i := n - 1; i > indices[len(indices) - 1] - 1; i-- {
				greater[num][i] = 0
			}
			currCount = 1
			for idx := len(indices) - 1; idx > 0; idx-- {
				i1 := indices[idx - 1]
				i2 := indices[idx]
				for i := i2 - 1; i > i1 - 1; i-- {
					greater[num][i] = currCount
				}
				currCount += 1
			}
			for i := indices[0] - 1; i >= 0; i-- {
				greater[num][i] = currCount
			}
			wg.Done()
		}(num, indices)
		mutex <- true
	}
	wg.Wait()

	// solve the question
	var ans int64
	for i := 1; i < len(arr); i++ {
		for j := i + 1; j < len(arr); j++ {
			ans += int64(greater[arr[i]][j]) * int64(less[arr[j]][i])
		}
	}
	return ans
}

func readNextInt(sc *bufio.Scanner) int {
	sc.Scan()
	s := sc.Text()
	i, _ := strconv.Atoi(s)
	return i
}

func main() {
	//sc := bufio.NewScanner(os.Stdin)
	//sc.Split(bufio.ScanWords)
	//t := readNextInt(sc)
	////wg := sync.WaitGroup{}
	////mutex := make(chan struct{}, 20)
	////for i := 0; i < 20; i++ {
	////
	////}
	//for tc := 0; tc < t; tc++ {
	//	//wg.Add(1)
	//	n := readNextInt(sc)
	//	arr := make([]int, n)
	//	for i := 0; i < n; i++ {
	//		arr[i] = readNextInt(sc)
	//	}
	//	fmt.Println(solve(arr))
	//}
	arr := make([]int, 3000)
	for i := 0; i < 3000; i++ {
		arr[i] = i + 1
	}
	print(solve(arr))
}

package main

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

func solve(arr []int) int {
	pos := make(map[int][]int)
	for i, num := range arr {
		pos[num] = append(pos[num], i)
	}
	n := len(arr)
	greater := make(map[int][]int)
	less := make(map[int][]int)
	for num, indices := range pos {
		greater[num] = make([]int, n)
		less[num] = make([]int, n)
		// fill the less array
		for i := 0; i < indices[0] + 1; i++ {
			less[num][i] = 0
		}
		currCount := 1
		for idx := 0; idx < len(indices) - 1; idx++ {
			i1 := indices[idx]
			i2 := indices[idx + 1]
			for i := i1 + 1; i < i2 + 1; i++ {
				less[num][i] = currCount
			}
			currCount++
		}
		for i := indices[len(indices) - 1] + 1; i < n; i++ {
			less[num][i] = currCount
		}
		// fill the greater array
		for i := n - 1; i > indices[len(indices) - 1] - 1; i-- {
			greater[num][i] = 0
		}
		currCount = 1
		for idx := len(indices) - 1; idx > 0; idx-- {
			i1 := indices[idx - 1]
			i2 := indices[idx]
			for i := i2 - 1; i > i1 - 1; i-- {
				greater[num][i] = currCount
			}
			currCount += 1
		}
		for i := indices[0] - 1; i >= 0; i-- {
			greater[num][i] = currCount
		}
	}

	// solve the question
	ans := 0
	for i := 1; i < len(arr); i++ {
		for j := i + 1; j < len(arr); j++ {
			ans += greater[arr[i]][j] * less[arr[j]][i]
		}
	}
	return ans
}

func readNextInt(sc *bufio.Scanner) int {
	sc.Scan()
	s := sc.Text()
	i, _ := strconv.Atoi(s)
	return i
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	t := readNextInt(sc)
	for tc := 0; tc < t; tc++ {
		n := readNextInt(sc)
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = readNextInt(sc)
		}
		fmt.Println(solve(arr))
	}
}


This is the easy version of Problem F. The only difference between the easy version and the hard version is the constraints.We will call a non-empty string balanced if it contains the same number of plus and minus signs. For example: strings "+--+" and "++-+--" are balanced, and strings "+--", "--" and "" are not balanced.We will call a string promising if the string can be made balanced by several (possibly zero) uses of the following operation:  replace two adjacent minus signs with one plus sign. In particular, every balanced string is promising. However, the converse is not true: not every promising string is balanced.For example, the string "-+---" is promising, because you can replace two adjacent minuses with plus and get a balanced string "-++-", or get another balanced string "-+-+".How many non-empty substrings of the given string $$$s$$$ are promising? Each non-empty promising substring must be counted in the answer as many times as it occurs in string $$$s$$$.Recall that a substring is a sequence of consecutive characters of the string. For example, for string "+-+" its substring are: "+-", "-+", "+", "+-+" (the string is a substring of itself) and some others. But the following strings are not its substring: "--", "++", "-++".

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 500$$$) —the number of test cases in the test. Then the descriptions of test cases follow. Each test case of input data consists of two lines. The first line consists of the number $$$n$$$ ($$$1 \le n \le 3000$$$): the length of $$$s$$$. The second line of the test case contains the string $$$s$$$ of length $$$n$$$, consisting only of characters "+" and "-". It is guaranteed that the sum of values $$$n$$$ over all test cases does not exceed $$$3000$$$.

For each test case, print a single number: the number of the promising non-empty substrings of string $$$s$$$. Each non-empty promising substring must be counted in the answer as many times as it occurs in string $$$s$$$.

package main

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

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

	var T, n int
	var s string
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &s)
		sum := make([]int, n+1)
		for i, b := range s {
			sum[i+1] = sum[i] + int(b&3) - 2
		}
		ans := int64(0)
		t := [3][]int{}
		for i := range t {
			t[i] = make([]int, n*2+2)
		}
		for i := n; i >= 0; i-- {
			j, k := (sum[i]%3+3)%3, sum[i]+n+1
			for k := k; k > 0; k &= k - 1 {
				ans += int64(t[j][k])
			}
			for ; k < len(t[j]); k += k & -k {
				t[j][k]++
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := 0
	fmt.Fscan(in, &t)
	for ii := 0; ii < t; ii++ {
		n:=0
		fmt.Fscan(in, &n)
		var s string
		fmt.Fscan(in, &s)
		ans := 0
		for i := 0; i < n; i++ {
			z,f:=0,0
			ff:=0
			last:=false
			for j := i; j < n; j++ {
				if s[j]=='-'{
					if last{
						last=false
						ff++
					}else {
						last= true
					}
					f++
				}else {
					z++
				}
				//fmt.Println(z,f,ff,i,j)
				if z==f || ( z < f && (z-f)%3 ==0 && (z-f)/3 <= ff){
					ans++
				}
			}
		}
		fmt.Fprintln(out, ans)
	}
}

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

package main

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

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

func solve() {
	var n int
	var s string
	Fscan(in, &n, &s)
	pref := make([]int, n+1)
	for i, c := range s {
		pref[i+1] = pref[i]
		if c == '+' {
			pref[i+1] += 1
		} else {
			pref[i+1] -= 1
		}
	}
	t := [3][]int{}
	for i := range t {
		t[i] = make([]int, 2*n+2)
	}
	offset := n + 1
	ans := int64(0)
	//matching boundaries to with %3 and greater than cur (fenwick tree) distributed on 0,1,2
	for i := 0; i <= n; i++ {
		rem, num := ((pref[i]%3)+3)%3, pref[i]+offset

		//accumulate in answer
		for j := num; j <= 2*n+1; j += (j & -j) {
			ans += int64(t[rem][j])
		}

		//update the tree backwards
		for j := num; j > 0; j -= (j & -j) {
			t[rem][j]++
		}
	}
	Fprintln(out, ans)

}
func main() {
	defer out.Flush()
	var t int
	Fscan(in, &t)
	for tt := 0; tt < t; tt++ {
		solve()
	}
}

package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := 0
	fmt.Fscan(in, &t)
	for ii := 0; ii < t; ii++ {
		n:=0
		fmt.Fscan(in, &n)
		var s string
		fmt.Fscan(in, &s)
		ans := 0
		for i := 0; i < n; i++ {
			z,f:=0,0
			ff:=0
			last:=false
			for j := i; j < n; j++ {
				if s[j]=='-'{
					if last{
						last=false
						ff++
					}else {
						last= true
					}
					f++
				}else {
					z++
				}
				fmt.Println(z,f,ff,i,j)
				if z==f || ( z < f && (z-f)%3 ==0 && (z-f)/3 <= ff){
					ans++
				}
			}
		}
		fmt.Fprintln(out, ans)
	}
}

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


Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.There are $$$n$$$ flights from A to B, they depart at time moments $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ and arrive at B $$$t_a$$$ moments later.There are $$$m$$$ flights from B to C, they depart at time moments $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ and arrive at C $$$t_b$$$ moments later.The connection time is negligible, so one can use the $$$i$$$-th flight from A to B and the $$$j$$$-th flight from B to C if and only if $$$b_j \ge a_i + t_a$$$.You can cancel at most $$$k$$$ flights. If you cancel a flight, Arkady can not use it.Arkady wants to be in C as early as possible, while you want him to be in C as late as possible. Find the earliest time Arkady can arrive at C, if you optimally cancel $$$k$$$ flights. If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$.

The first line contains five integers $$$n$$$, $$$m$$$, $$$t_a$$$, $$$t_b$$$ and $$$k$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$, $$$1 \le k \le n + m$$$, $$$1 \le t_a, t_b \le 10^9$$$) — the number of flights from A to B, the number of flights from B to C, the flight time from A to B, the flight time from B to C and the number of flights you can cancel, respectively. The second line contains $$$n$$$ distinct integers in increasing order $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ ($$$1 \le a_1 < a_2 < \ldots < a_n \le 10^9$$$) — the times the flights from A to B depart. The third line contains $$$m$$$ distinct integers in increasing order $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ ($$$1 \le b_1 < b_2 < \ldots < b_m \le 10^9$$$) — the times the flights from B to C depart.

If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$. Otherwise print the earliest time Arkady can arrive at C if you cancel $$$k$$$ flights in such a way that maximizes this time.

NoteConsider the first example. The flights from A to B depart at time moments $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ and arrive at B at time moments $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, respectively. The flights from B to C depart at time moments $$$1$$$, $$$2$$$, $$$3$$$, $$$9$$$, and $$$10$$$ and arrive at C at time moments $$$2$$$, $$$3$$$, $$$4$$$, $$$10$$$, $$$11$$$, respectively. You can cancel at most two flights. The optimal solution is to cancel the first flight from A to B and the fourth flight from B to C. This way Arkady has to take the second flight from A to B, arrive at B at time moment $$$4$$$, and take the last flight from B to C arriving at C at time moment $$$11$$$.In the second example you can simply cancel all flights from A to B and you're done.In the third example you can cancel only one flight, and the optimal solution is to cancel the first flight from A to B. Note that there is still just enough time to catch the last flight from B to C.

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, m, ta, tb, k := 0, 0, 0, 0, 0
	fmt.Fscanf(in, "%d %d %d %d %d\n", &n, &m, &ta, &tb, &k)
	a := make([]int, n)
	b := make([]int, m)
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d", &a[i])
		a[i] += ta
	}
	fmt.Fscanf(in, "\n")
	for i := 0; i < m; i++ {
		fmt.Fscanf(in, "%d", &b[i])
	}
	fmt.Fscanf(in, "\n")
	sort.Ints(a)
	sort.Ints(b)
	if k >= len(a) || k >= len(b) {
		fmt.Fprintf(out, "-1\n")
		return
	}
	ans := -1
	for i := 0; i <= k; i++ {
		numberInB := find(a[i], b)
		if numberInB == -1 {
			fmt.Fprintf(out, "-1\n")
			return
		}
		remaining := k - i
		idInB := numberInB + remaining
		//fmt.Println(i, numberInB, remaining, idInB, b[idInB])
		if idInB >= len(b) {
			fmt.Fprintf(out, "-1\n")
			return
		}
		if b[idInB]+tb > ans || ans == -1 {
			ans = b[idInB] + tb
		}
	}
	fmt.Fprintf(out, "%d\n", ans)
	return
}

// first index in b >= a
func find(a int, b []int) int {
	n := len(b)
	if n == 0 {
		return -1
	}
	if b[n-1] < a {
		return -1
	}
	l := 0
	r := n - 1
	for l < r {
		mid := (l + r) / 2
		if b[mid] >= a {
			r = mid
		} else {
			l = mid + 1
		}
	}
	return l
}

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

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


You are given an undirected connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. $$$k$$$ vertices of this graph are special.You have to direct each edge of this graph or leave it undirected. If you leave the $$$i$$$-th edge undirected, you pay $$$w_i$$$ coins, and if you direct it, you don't have to pay for it.Let's call a vertex saturated if it is reachable from each special vertex along the edges of the graph (if an edge is undirected, it can be traversed in both directions). After you direct the edges of the graph (possibly leaving some of them undirected), you receive $$$c_i$$$ coins for each saturated vertex $$$i$$$. Thus, your total profit can be calculated as $$$\sum \limits_{i \in S} c_i - \sum \limits_{j \in U} w_j$$$, where $$$S$$$ is the set of saturated vertices, and $$$U$$$ is the set of edges you leave undirected.For each vertex $$$i$$$, calculate the maximum possible profit you can get if you have to make the vertex $$$i$$$ saturated.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$n - 1 \le m \le \min(3 \cdot 10^5, \frac{n(n-1)}{2})$$$, $$$1 \le k \le n$$$). The second line contains $$$k$$$ pairwise distinct integers $$$v_1$$$, $$$v_2$$$, ..., $$$v_k$$$ ($$$1 \le v_i \le n$$$) — the indices of the special vertices. The third line contains $$$n$$$ integers $$$c_1$$$, $$$c_2$$$, ..., $$$c_n$$$ ($$$0 \le c_i \le 10^9$$$). The fourth line contains $$$m$$$ integers $$$w_1$$$, $$$w_2$$$, ..., $$$w_m$$$ ($$$0 \le w_i \le 10^9$$$). Then $$$m$$$ lines follow, the $$$i$$$-th line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) — the endpoints of the $$$i$$$-th edge. There is at most one edge between each pair of vertices.

Print $$$n$$$ integers, where the $$$i$$$-th integer is the maximum profit you can get if you have to make the vertex $$$i$$$ saturated.

NoteConsider the first example:  the best way to make vertex $$$1$$$ saturated is to direct the edges as $$$2 \to 1$$$, $$$3 \to 2$$$; $$$1$$$ is the only saturated vertex, so the answer is $$$11$$$;  the best way to make vertex $$$2$$$ saturated is to leave the edge $$$1-2$$$ undirected and direct the other edge as $$$3 \to 2$$$; $$$1$$$ and $$$2$$$ are the saturated vertices, and the cost to leave the edge $$$1-2$$$ undirected is $$$10$$$, so the answer is $$$2$$$;  the best way to make vertex $$$3$$$ saturated is to direct the edges as $$$2 \to 3$$$, $$$1 \to 2$$$; $$$3$$$ is the only saturated vertex, so the answer is $$$5$$$. The best course of action in the second example is to direct the edges along the cycle: $$$1 \to 2$$$, $$$2 \to 3$$$, $$$3 \to 4$$$ and $$$4 \to 1$$$. That way, all vertices are saturated.

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	type Edge struct {
		v, w int
	}

	n, m, k := io.NextInt(), io.NextInt(), io.NextInt()
	s, c, w := io.NextInts(k), io.NextInts(n), io.NextInts(m)
	g := make([][]Edge, n+1)
	for _, w := range w {
		u, v := io.NextInt(), io.NextInt()
		g[u] = append(g[u], Edge{v, w})
		g[v] = append(g[v], Edge{u, w})
	}

	// Construct tree of biconnected components
	idx := make([]int, n+1)
	var g2 [][]Edge
	{
		time, low := 0, make([]int, n+1)
		var st []int
		var ed [][3]int
		id := 0
		var dfs func(u, p, w int)
		dfs = func(u, p, w int) {
			time++
			tin := time
			low[u] = time
			sz := len(st)
			st = append(st, u)
			for _, e := range g[u] {
				if e.v == p {
					continue
				}
				if low[e.v] == 0 {
					dfs(e.v, u, e.w)
				}
				low[u] = min(low[u], low[e.v])
			}
			if low[u] == tin {
				if u != p {
					ed = append(ed, [3]int{p, u, w})
				}
				for _, v := range st[sz:] {
					idx[v] = id
				}
				st = st[:sz]
				id++
			}
		}
		dfs(1, 1, 0)

		g2 = make([][]Edge, id)
		for _, e := range ed {
			u, v, w := idx[e[0]], idx[e[1]], e[2]
			g2[u] = append(g2[u], Edge{v, w})
			g2[v] = append(g2[v], Edge{u, w})
		}
	}

	n2 := len(g2)
	gain, scnt := make([]int64, n2), make([]int, n2)
	for u, c := range c {
		gain[idx[u+1]] += int64(c)
	}
	for _, u := range s {
		scnt[idx[u]]++
	}

	// Perform rerooting tree dp
	ans := make([]int64, n2)
	{
		ssum, dp := make([]int, n2), make([]int64, n2)
		upd := func(u, v, w, sign int) {
			if u == v {
				return
			}
			ssum[u] += sign * ssum[v]
			if ssum[v] == 0 || ssum[v] == k {
				dp[u] += int64(sign) * dp[v]
			} else {
				dp[u] += int64(sign) * max64(dp[v]-int64(w), 0)
			}
		}

		var dfs func(u, p int)
		dfs = func(u, p int) {
			ssum[u], dp[u] = scnt[u], gain[u]
			for _, e := range g2[u] {
				if e.v == p {
					continue
				}
				dfs(e.v, u)
				upd(u, e.v, e.w, 1)
			}
		}
		dfs(0, 0)

		var dfs2 func(u, p, w int)
		dfs2 = func(u, p, w int) {
			upd(u, p, w, 1)
			for _, e := range g2[u] {
				if e.v == p {
					continue
				}
				upd(u, e.v, e.w, -1)
				dfs2(e.v, u, e.w)
				upd(u, e.v, e.w, 1)
			}
			ans[u] = dp[u]
			upd(u, p, w, -1)
		}
		dfs2(0, 0, 0)
	}

	for i := 1; i <= n; i++ {
		io.Print(ans[idx[i]], " ")
	}
	io.Println()
}

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

func max64(i, j int64) int64 {
	if i > j {
		return i
	}
	return j
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	type Edge struct {
		v, w int
	}

	n, m, k := io.NextInt(), io.NextInt(), io.NextInt()
	s, c, w := io.NextInts(k), io.NextInts(n), io.NextInts(m)
	g := make([][]Edge, n+1)
	for _, ww := range w {
		u, v := io.NextInt(), io.NextInt()
		g[u] = append(g[u], Edge{v, ww})
		g[v] = append(g[v], Edge{u, ww})
	}

	idx := make([]int, n+1)
	var h [][]Edge
	{
		time, low := 0, make([]int, n+1)
		var st []int
		var ed [][3]int
		id := 0
		var dfs func(u, p, w int)
		dfs = func(u, p, w int) {
			time++
			tin := time
			low[u] = time
			sz := len(st)
			st = append(st, u)
			for _, e := range g[u] {
				if e.v == p {
					continue
				}
				if low[e.v] == 0 {
					dfs(e.v, u, e.w)
				}
				low[u] = min(low[u], low[e.v])
			}
			if low[u] == tin {
				if u != p {
					ed = append(ed, [3]int{p, u, w})
				}
				for _, v := range st[sz:] {
					idx[v] = id
				}
				st = st[:sz]
				id++
			}
		}
		dfs(1, 1, 0)

		h = make([][]Edge, id)
		for _, e := range ed {
			u, v, w := idx[e[0]], idx[e[1]], e[2]
			h[u] = append(h[u], Edge{v, w})
			h[v] = append(h[v], Edge{u, w})
		}
	}

	n2 := len(h)
	gain, scnt := make([]int64, n2), make([]int, n2)
	for u, cc := range c {
		gain[idx[u+1]] += int64(cc)
	}
	for _, u := range s {
		scnt[idx[u]]++
	}

	ans := make([]int64, n2)
	{
		ssum, dp := make([]int, n2), make([]int64, n2)
		upd := func(u, v, w, sign int) {
			if u == v {
				return
			}
			ssum[u] += sign * ssum[v]
			if ssum[v] == 0 || ssum[v] == k {
				dp[u] += int64(sign) * dp[v]
			} else {
				dp[u] += int64(sign) * max64(dp[v]-int64(w), 0)
			}
		}

		var dfs func(u, p int)
		dfs = func(u, p int) {
			ssum[u], dp[u] = scnt[u], gain[u]
			for _, e := range h[u] {
				if e.v == p {
					continue
				}
				dfs(e.v, u)
				upd(u, e.v, e.w, 1)
			}
		}
		dfs(0, 0)

		var dfs2 func(u, p, w int)
		dfs2 = func(u, p, w int) {
			upd(u, p, w, 1)
			for _, e := range h[u] {
				if e.v == p {
					continue
				}
				upd(u, e.v, e.w, -1)
				dfs2(e.v, u, e.w)
				upd(u, e.v, e.w, 1)
			}
			ans[u] = dp[u]
			upd(u, p, w, -1)
		}
		dfs2(0, 0, 0)
	}

	for i := 1; i <= n; i++ {
		io.Print(ans[idx[i]], " ")
	}
	io.Println()
}

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

func max64(i, j int64) int64 {
	if i > j {
		return i
	}
	return j
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}