A permutation — is a sequence of length $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all the numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ — permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ — no.Polycarp was recently gifted a permutation $$$a[1 \dots n]$$$ of length $$$n$$$. Polycarp likes trees more than permutations, so he wants to transform permutation $$$a$$$ into a rooted binary tree. He transforms an array of different integers into a tree as follows:   the maximum element of the array becomes the root of the tree;  all elements to the left of the maximum — form a left subtree (which is built according to the same rules but applied to the left part of the array), but if there are no elements to the left of the maximum, then the root has no left child;  all elements to the right of the maximum — form a right subtree (which is built according to the same rules but applied to the right side of the array), but if there are no elements to the right of the maximum, then the root has no right child. For example, if he builds a tree by permutation $$$a=[3, 5, 2, 1, 4]$$$, then the root will be the element $$$a_2=5$$$, and the left subtree will be the tree that will be built for the subarray $$$a[1 \dots 1] = [3]$$$, and the right one — for the subarray $$$a[3 \dots 5] = [2, 1, 4]$$$. As a result, the following tree will be built:     The tree corresponding to the permutation $$$a=[3, 5, 2, 1, 4]$$$. Another example: let the permutation be $$$a=[1, 3, 2, 7, 5, 6, 4]$$$. In this case, the tree looks like this:     The tree corresponding to the permutation $$$a=[1, 3, 2, 7, 5, 6, 4]$$$. Let us denote by $$$d_v$$$ the depth of the vertex $$$a_v$$$, that is, the number of edges on the path from the root to the vertex numbered $$$a_v$$$. Note that the root depth is zero. Given the permutation $$$a$$$, for each vertex, find the value of $$$d_v$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the permutation. This is followed by $$$n$$$ numbers $$$a_1, a_2, \ldots, a_n$$$ — permutation $$$a$$$.

For each test case, output $$$n$$$ values — $$$d_1, d_2, \ldots, d_n$$$.

/*
	A template for Go on codeforces.com
	Author: Yakov, frvr.ru
*/

package main

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

func main() {
	// START WRITING YOUR SOLUTION HERE:
	// writeLine(typeOf(readInt()))
	t := readInt()
	for i := 0; i < t; i++ {
		n := readInt()
		arr := readInts()
		ans := make([]int, n)
		map1 := make(map[int]int)
		for i := 0; i < len(arr); i++ {
			map1[arr[i]] = i
		}
		Solve(arr, map1, &ans, 0)
		for i := 0; i < len(ans); i++ {
			writeFormat("%v ", ans[i])
		}
		writeLine()
	}
}
func Solve(arr []int, map1 map[int]int, ans *[]int, level int) {
	//fmt.Printf("arr===>%v,ans====>%v,level===>%v\n", arr, *ans, level)
	if len(arr) == 1 {
		(*ans)[map1[arr[0]]] = level
		return
	}
	max1, index := 0, 0
	for i := 0; i < len(arr); i++ {
		if max1 < arr[i] {
			max1 = arr[i]
			index = i
		}
	}
	(*ans)[map1[max1]] = level

	if index-1 >= 0 {
		//for left
		Solve(arr[:index], map1, ans, level+1)
	}
	if index+1 < len(arr) {
		//for right
		Solve(arr[index+1:], map1, ans, level+1)
	}
}

/* ~~~~~~~~~~ */
/* ~~~~~~~~~~ */
/* ~~~~~~~~~~ */

var in = bufio.NewReader(os.Stdin)

type float = float32
type double = float64
type long = int64
type ulong = uint64

func typeOf(arg interface{}) string {
	switch reflect.TypeOf(arg).Kind() {
	case reflect.Int:
		return "int"
	case reflect.Int8:
		return "int8"
	case reflect.Int16:
		return "int16"
	case reflect.Int32:
		return "int32"
	case reflect.Int64:
		return "int64"
	case reflect.Uint:
		return "uint"
	case reflect.Uint8:
		return "uint8"
	case reflect.Uint16:
		return "uint16"
	case reflect.Uint32:
		return "uint32"
	case reflect.Uint64:
		return "uint64"
	case reflect.Float32:
		return "float32"
	case reflect.Float64:
		return "float64"
	case reflect.Complex64:
		return "complex64"
	case reflect.Complex128:
		return "complex128"
	case reflect.Bool:
		return "bool"
	case reflect.String:
		return "string"
	case reflect.Chan:
		return "chan"
	case reflect.Ptr:
		return "ptr"
	case reflect.Uintptr:
		return "uintptr"
	case reflect.UnsafePointer:
		return "unsafeptr"
	case reflect.Interface:
		return "interface"
	case reflect.Array:
		return "array"
	case reflect.Slice:
		return "slice"
	case reflect.Map:
		return "map"
	case reflect.Struct:
		return "struct"
	case reflect.Func:
		return "func"
	case reflect.Invalid:
		return "invalid"
	default:
		return "nil"
	}
}

/* ~~~~~~~~~~ */

func _scln() string {
	ln, _ := in.ReadString('\n')
	return strings.Trim(ln, " \r\n")
}
func _sc(s []string) string {
	if len(s) == 0 {
		return _scln()
	}
	return s[0]
}

func readLine() string              { return _scln() }
func readString() string            { return _scln() }
func readStrings() []string         { return strings.Split(_scln(), " ") }
func readBool(s ...string) bool     { t, _ := strconv.ParseBool(_sc(s)); return t }
func readByte(s ...string) byte     { t, _ := strconv.ParseUint(_sc(s), 10, 8); return byte(t) }
func readDouble(s ...string) double { t, _ := strconv.ParseFloat(_sc(s), 64); return t }
func readFloat(s ...string) float   { t, _ := strconv.ParseFloat(_sc(s), 32); return float32(t) }
func readInt(s ...string) int       { t, _ := strconv.Atoi(_sc(s)); return t }
func readLong(s ...string) long     { t, _ := strconv.ParseInt(_sc(s), 10, 64); return t }
func readULong(s ...string) ulong   { t, _ := strconv.ParseUint(_sc(s), 10, 64); return t }

/* ~~~~~~~~~~ */

// Too much overhead with universal method using interface{}, wait for the generics,
// but for now — just don't look at the redundancy of the code after that commentary :)

func readBools() []bool {
	strs := readStrings()
	arr := make([]bool, len(strs))
	for i, s := range strs {
		arr[i] = readBool(s)
	}
	return arr
}
func readBytes() []byte {
	strs := readStrings()
	arr := make([]byte, len(strs))
	for i, s := range strs {
		arr[i] = readByte(s)
	}
	return arr
}
func readDoubles() []double {
	strs := readStrings()
	arr := make([]double, len(strs))
	for i, s := range strs {
		arr[i] = readDouble(s)
	}
	return arr
}
func readFloats() []float {
	strs := readStrings()
	arr := make([]float, len(strs))
	for i, s := range strs {
		arr[i] = readFloat(s)
	}
	return arr
}
func readInts() []int {
	strs := readStrings()
	arr := make([]int, len(strs))
	for i, s := range strs {
		arr[i] = readInt(s)
	}
	return arr
}
func readLongs() []long {
	strs := readStrings()
	arr := make([]long, len(strs))
	for i, s := range strs {
		arr[i] = readLong(s)
	}
	return arr
}
func readULongs() []ulong {
	strs := readStrings()
	arr := make([]ulong, len(strs))
	for i, s := range strs {
		arr[i] = readULong(s)
	}
	return arr
}

/* ~~~~~~~~~~ */

func write(arg ...interface{})                 { fmt.Print(arg...) }
func writeLine(arg ...interface{})             { fmt.Println(arg...) }
func writeFormat(f string, arg ...interface{}) { fmt.Printf(f, arg...) }

package main

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

// return index of maximum element
func findMax(lo, hi int, arr []int) int {
	ans := lo
	for i := lo; i <= hi; i++ {
		if arr[i] > arr[ans] {
			ans = i
		}
	}
	return ans
}

//func dfs(low, hi, cur int, arr []int, ans []int) {
//	if low > hi {
//		return
//	}
//	if low == hi {
//		ans[low] = cur
//		return
//	}
//	maxInd := findMax(low, hi, arr)
//	ans[maxInd] = cur
//	dfs(low, maxInd-1, cur+1, arr, ans)
//	dfs(maxInd+1, hi, cur+1, arr, ans)
//}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(in, &n)
		arr := make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &arr[j])
		}
		ans := make([]int, n)
		var dfs func(low, hi, cur int)
		dfs = func(low, hi, cur int) {
			if low > hi {
				return
			}
			if low == hi {
				ans[low] = cur
				return
			}
			maxInd := findMax(low, hi, arr)
			ans[maxInd] = cur
			dfs(low, maxInd-1, cur+1)
			dfs(maxInd+1, hi, cur+1)
		}
		dfs(0, n-1, 0)
		for _, val := range ans {
			fmt.Fprint(out, val, " ")
		}
		fmt.Fprintln(out)
	}
}

package main

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

// return index of maximum element
func findMax(lo, hi int, arr []int) int {
	ans := lo
	for i := lo; i <= hi; i++ {
		if arr[i] > arr[ans] {
			ans = i
		}
	}
	return ans
}

func dfs(low, hi, cur int, arr []int, ans []int) {
	if low > hi {
		return
	}
	if low == hi {
		ans[low] = cur
		return
	}
	maxInd := findMax(low, hi, arr)
	ans[maxInd] = cur
	dfs(low, maxInd-1, cur+1, arr, ans)
	dfs(maxInd+1, hi, cur+1, arr, ans)
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(in, &n)
		arr := make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &arr[j])
		}
		ans := make([]int, n)
		dfs(0, n-1, 0, arr, ans)
		for _, val := range ans {
			fmt.Fprint(out, val, " ")
		}
		fmt.Fprintln(out)
	}
}

package main

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

var sc = bufio.NewScanner(os.Stdin)
var wr = bufio.NewWriter(os.Stdout)

type Pair struct {
	idx, num int64
}

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 4096), 1e9)
	// this template is new version.
	// use getI(), getS(), getInts(), getF()
	cases := getI()
	forEach(cases, func(i int64) {
		perms := getI()        // n: len of perm
		nums := getInts(perms) // nums: a1, a2
		res := make([]int64, perms)
		build(0, perms-1, &nums, &res, 0) // // 0, 4
		outSlice(res)
	})
}

func build(l, r int64, nums, res *[]int64, height int64) {
	if r < l {
		return
	}
	if l == r {
		(*res)[l] = height
		return
	}
	m := l
	for i := l + 1; i <= r; i++ {
		if (*nums)[m] < (*nums)[i] {
			m = i
		}
	}
	(*res)[m] = height
	build(l, m-1, nums, res, height+1)
	build(m+1, r, nums, res, height+1)
}

// !------- HELPERS -------!

func out(x ...interface{}) {
	fmt.Fprintln(wr, x...)
}

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

func outSlice(x ...interface{}) {
	fmt.Fprintf(wr, strings.Trim(fmt.Sprint(x...), "[]")+"\n")
}

func getI() int64 {
	s := getS()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func getF() float64 {
	sc.Scan()
	i, e := strconv.ParseFloat(sc.Text(), 64)
	if e != nil {
		panic(e)
	}
	return i
}

func getInts(N int64) []int64 {
	ret := make([]int64, N)
	for i := range ret {
		ret[i] = getI()
	}
	return ret
}

func getS() string {
	if !sc.Scan() {
		panic(sc.Err())
	}
	return sc.Text()
}

func sortInts(data []int64) {
	sort.Slice(data, func(i, j int) bool { return data[i] < data[j] })
}

func joinInts(s []int64) string {
	return strings.Trim(fmt.Sprintf("%v", s), "[]")
}

func forEach(n int64, fn func(int64)) {
	for i := int64(0); i < n; i++ {
		fn(i)
	}
}

// min, max, asub, abs
func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

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

// min for n entry
func nmin(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = min(ret, e)
	}
	return ret
}

// max for n entry
func nmax(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = max(ret, e)
	}
	return ret
}

func asub(a, b int64) int64 {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int64) int64 {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

package main

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

var sc = bufio.NewScanner(os.Stdin)
var wr = bufio.NewWriter(os.Stdout)

type Pair struct {
	idx, num int64
}

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 4096), 1e9)
	// this template is new version.
	// use getI(), getS(), getInts(), getF()
	cases := getI()
	forEach(cases, func(i int64) {
		perms := getI()        // n: len of perm
		nums := getInts(perms) // nums: a1, a2
		sortInts(nums)
		tree := make([]int64, perms)
		createTree(nums, 0, &tree)
		outSlice(tree)
	})
}

func createTree(nums []Pair, height int64, tree *[]int64) {
	if len(nums) != 0 {
		last := nums[len(nums)-1]
		(*tree)[last.idx] = height
		var left []Pair
		var right []Pair
		forEach(int64(len(nums)-1), func(i int64) {
			cur := nums[i]
			if cur.idx < last.idx {
				left = append(left, cur)
			} else {
				right = append(right, cur)
			}
		})
		createTree(left, height+1, tree)
		createTree(right, height+1, tree)
	}
}

// !------- HELPERS -------!

func out(x ...interface{}) {
	fmt.Fprintln(wr, x...)
}

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

func outSlice(x ...interface{}) {
	fmt.Fprintf(wr, strings.Trim(fmt.Sprint(x...), "[]")+"\n")
}

func getI() int64 {
	s := getS()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func getF() float64 {
	sc.Scan()
	i, e := strconv.ParseFloat(sc.Text(), 64)
	if e != nil {
		panic(e)
	}
	return i
}

func getInts(N int64) []Pair {
	ret := make([]Pair, N)
	for i := range ret {
		ret[i] = Pair{int64(i), getI()}
	}
	return ret
}

func getS() string {
	if !sc.Scan() {
		panic(sc.Err())
	}
	return sc.Text()
}

func sortInts(data []Pair) {
	sort.Slice(data, func(i, j int) bool { return data[i].num < data[j].num })
}

func joinInts(s []int64) string {
	return strings.Trim(fmt.Sprintf("%v", s), "[]")
}

func forEach(n int64, fn func(int64)) {
	for i := int64(0); i < n; i++ {
		fn(i)
	}
}

// min, max, asub, abs
func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

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

// min for n entry
func nmin(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = min(ret, e)
	}
	return ret
}

// max for n entry
func nmax(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = max(ret, e)
	}
	return ret
}

func asub(a, b int64) int64 {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int64) int64 {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

// 00
package main

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

func write(f *bufio.Writer, a ...interface{}) {
	f.Write([]byte(fmt.Sprint(a...)))
}

type Number interface {
	int64 | float64 | int
}

func min[K Number](a K, b K) K {
	if a < b {
		return a
	}
	return b
}
func max[K Number](a K, b K) K {
	if a > b {
		return a
	}
	return b
}
func heights(a []int, d []int, i int, j int, h int) {
	if j < i {
		return
	} else if i == j {
		d[i] = h
		return
	} else {
		mx := a[i]
		mi := i
		for k := i; k <= j; k++ {
			if a[k] > mx {
				mx = a[k]
				mi = k
			}
		}
		d[mi] = h
		heights(a, d, i, mi-1, h+1)
		heights(a, d, mi+1, j, h+1)
	}
}
func main() {
	var T int
	reader := bufio.NewReader(os.Stdin)
	f := bufio.NewWriter(os.Stdout)
	defer f.Flush()
	fmt.Fscan(reader, &T)
	for t := 1; t <= T; t++ {
		var n int
		fmt.Fscan(reader, &n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i])
		}
		d := make([]int, n)
		heights(a, d, 0, n-1, 0)
		for i := 0; i < n; i++ {
			write(f, d[i])
			if i == n-1 {
				write(f, "\n")
			} else {
				write(f, " ")
			}
		}
	}
}

package main

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

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

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

var (
	n   int
	ans = make([]int, 101)
)

func maxIdSlice(a []int) (int, int) {
	max := 0
	id := -1
	for i, e := range a {
		// printf("%d ", e)
		if max < e {
			// printf("trang:%d %d\n", e, i)
			max = e
			id = i
		}
	}
	// printf("\nid:%d\n", id)
	return id, max
}
func conquer(a []int, begin int) {
	id, max := maxIdSlice(a)
	ans[max] = begin
	// printf("start:%d %d\n", id, max)
	l := a[:id]
	r := a[id+1:]
	if len(l) > 0 {
		conquer(l, begin+1)
	}
	if len(r) > 0 {
		conquer(r, begin+1)
	}
}
func solve() {
	scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		scan(&a[i])
	}
	begin := 0
	conquer(a, begin)
	for i := 0; i < n; i++ {
		printf("%d ", ans[a[i]])
	}
	printf("\n")
}

func main() {
	defer out.Flush()
	n := 1
	scan(&n)
	for i := 0; i < n; i++ {
		solve()
	}
}

package main

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

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

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

		type e struct {
			v, idx int
		}
		arr := make([]e, n)
		for i := 0; i < n; i++ {
			var v int
			fmt.Fscan(in, &v)
			arr[i] = e{v, i}
		}

		g := make([]int, n)
		var walk func(d int, b []e)
		walk = func(d int, b []e) {
			var max e
			var idx int
			for i, v := range b {
				if v.v > max.v {
					max = v
					idx = i
				}
			}

			g[max.idx] = d
			if idx > 0 {
				walk(d+1, b[:idx])
			}
			if idx+1 < len(b) {
				walk(d+1, b[idx+1:])
			}
		}
		walk(0, arr)
		for _, v := range g {
			fmt.Fprintf(out, "%d ", v)
		}
		fmt.Fprintln(out)
	}
}

package main

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

var reader *bufio.Reader
var writer *bufio.Writer

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

func findMaxIdx(arr []int, l, r int) int {
	max := l
	for i := l; i <= r; i++ {
		if arr[i] > arr[max] {
			max = i
		}
	}
	return max
}

func solve(arr, depths []int, depth, l, r int) {
	if r < l {
		return
	}

	if r == l {
		depths[r] = depth
	}

	mid := findMaxIdx(arr, l, r)
	depths[mid] = depth

	solve(arr, depths, depth+1, l, mid-1)
	solve(arr, depths, depth+1, mid+1, r)
}

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

	var N, x, y int
	scan(&N)
	for N > 0 {
		scan(&x)
		arr := make([]int, x)
		for i := 0; i < x; i++ {
			scan(&y)
			arr[i] = y
		}

		ans := make([]int, x)
		solve(arr, ans, 0, 0, x-1)

		for i := 0; i < x; i++ {
			print(ans[i])
			if i != x-1 {
				print(" ")
			} else {
				print("\n")
			}
		}
		N--
	}
}

// link:

package main

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

func solve(input, answer []int, d int) {
	if len(answer) == 1 {
		answer[0] = d
		return
	}

	var maxIndex int
	for i := 0; i < len(input); i++ {
		if input[i] > input[maxIndex] {
			maxIndex = i
		}
	}

	answer[maxIndex] = d

	if maxIndex != 0 {
		solve(input[:maxIndex], answer[:maxIndex], d+1)

	}

	if maxIndex != len(input)-1 {
		solve(input[maxIndex+1:], answer[maxIndex+1:], d+1)
	}
}

func logic(reader io.Reader, writer io.Writer) {
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

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

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

		input := make([]int, n)
		answer := make([]int, n)

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

			input[j] = val
		}

		solve(input, answer, 0)

		for j := 0; j < n; j++ {
			if j == n-1 {
				fmt.Fprintf(out, "%d", answer[j])
			} else {
				fmt.Fprintf(out, "%d ", answer[j])
			}
		}
		fmt.Fprintln(out)
	}
}

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

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(A)
		for i := 0; i < n; i++ {
			buf.WriteString(fmt.Sprintf("%d ", res[i]))
		}
		buf.WriteByte('\n')
	}

	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(A []int) []int {
	n := len(A)
	parent := make([]int, n)
	stack := make([]int, n)
	var p int
	for i := 0; i < n; i++ {
		for p > 0 && A[stack[p-1]] < A[i] {
			if p == 1 || A[stack[p-2]] > A[i] {
				parent[stack[p-1]] = i
			}
			p--
		}

		if p > 0 {
			parent[i] = stack[p-1]
		} else {
			parent[i] = -1
		}
		stack[p] = i
		p++
	}
	root := stack[0]
	cnt := make([]int, n)
	for i := 0; i < n; i++ {
		if parent[i] >= 0 {
			cnt[parent[i]]++
		}
	}
	out := make([][]int, n)
	for i := 0; i < n; i++ {
		out[i] = make([]int, 0, cnt[i])
	}

	for i := 0; i < n; i++ {
		if parent[i] >= 0 {
			out[parent[i]] = append(out[parent[i]], i)
		}
	}
	D := make([]int, n)
	var dfs func(u int)

	dfs = func(u int) {
		for _, v := range out[u] {
			D[v] = D[u] + 1
			dfs(v)
		}
	}
	dfs(root)

	return D
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1490D(_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])
		}
		var f func(l, r, d int)
		f = func(l, r, d int) {
			if l == r {
				return
			}
			p := l
			for i := l; i < r; i++ {
				if a[i] > a[p] {
					p = i
				}
			}
			a[p] = d
			f(l, p, d+1)
			f(p+1, r, d+1)
		}
		f(0, n, 0)
		for _, v := range a {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}

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

package main

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

var a, ans []int;

func dfs(s, e, d int) {
	if s > e {
		return;
	}
	mx := 0;
	for i:=s;i<=e;i++ {
		if mx < a[i] {
			mx = a[i];
		}
	}

	for i:=s;i<=e;i++ {
		if mx == a[i] {
			dfs(s, i-1, d+1);
			dfs(i+1, e, d+1);
			ans[i] = d;
		}
	}
}

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

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

		a = make([]int, n);
		for i:=0;i<n;i++ {
			Fscan(in, &a[i]);
		}
		ans = make([]int, n);
		dfs(0, n-1, 0);
		for i:=0;i<n;i++ {
			Fprint(out, ans[i], " ");
		}
		Fprint(out, "\n");
	}
}

package main

import (
    "bufio"
    "io"
    "os"
    . "fmt"
    // . "math"
)
var input io.Reader = bufio.NewReader(os.Stdin)

var a, ans []int
func find(l int, r int, dep int) {

    if l >= r {
        return
    }

    maxn, pos := 0, 0
    for i := l; i < r; i++ {
        it := a[i]
        if it > maxn {
            maxn = it
            pos = i
        }
    }

    // Println("maxn:", maxn)
    // Println("pos:", pos)

    ans[pos] = dep
    find(l, pos, dep + 1)
    find(pos + 1, r, dep + 1)
}

func main() {
    var t int
    Fscan(input, &t)
    for i := 0; i < t; i++ {
        var n int
        Fscan(input, &n)
        a = make([]int, n)
        ans = make([]int, n)
        for i := 0; i < n; i++ {
            Fscan(input, &a[i])
        }
        find(0, n, 0)
        for _, it := range(ans) {
            Print(it, " ")
        }
        Println()
    }
}

package main

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

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

func init() {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 4096), 1e9)
}

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

func sint64() int64 {
	s := sstring()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func sint64s(n int64) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	return a
}

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

func main() {
	defer writer.Flush()
	for t := sint64(); t > 0; t-- {
		n := sint64()
		a := sint64s(n)
		for _, d := range sol(0, n, a, 0) {
			printf("%d ", d)
		}
		printf("\n")
	}
}

func sol(l, r int64, a []int64, depth int64) []int64 {
	if l >= r {
		return []int64{}
	}
	mxi := maxIdx(a, l, r)
	lsol := sol(l, mxi, a, depth+1)
	rsol := sol(mxi+1, r, a, depth+1)
	return append(append(lsol, depth), rsol...)
}

func maxIdx(a []int64, l, r int64) int64 {
	v := a[l]
	idx := l
	for i := l; i < r; i++ {
		if a[i] > v {
			v = a[i]
			idx = i
		}
	}
	return idx
}

/*
	A template for Go on codeforces.com
	Author: Yakov, frvr.ru
*/

package main

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

func main() {
	// START WRITING YOUR SOLUTION HERE:
	// writeLine(typeOf(readInt()))
	t := readInt()
	for i := 0; i < t; i++ {
		n := readInt()
		arr := readInts()
		ans := make([]int, n)
		map1 := make(map[int]int)
		for i := 0; i < len(arr); i++ {
			map1[arr[i]] = i
		}
		Solve(arr, map1, &ans, 0)
		writeLine(ans)
	}
}
func Solve(arr []int, map1 map[int]int, ans *[]int, level int) {
	//fmt.Printf("arr===>%v,ans====>%v,level===>%v\n", arr, *ans, level)
	if len(arr) == 1 {
		(*ans)[map1[arr[0]]] = level
		return
	}
	max1, index := 0, 0
	for i := 0; i < len(arr); i++ {
		if max1 < arr[i] {
			max1 = arr[i]
			index = i
		}
	}
	(*ans)[map1[max1]] = level

	if index-1 >= 0 {
		//for left
		Solve(arr[:index], map1, ans, level+1)
	}
	if index+1 < len(arr) {
		//for right
		Solve(arr[index+1:], map1, ans, level+1)
	}
}

/* ~~~~~~~~~~ */
/* ~~~~~~~~~~ */
/* ~~~~~~~~~~ */

var in = bufio.NewReader(os.Stdin)

type float = float32
type double = float64
type long = int64
type ulong = uint64

func typeOf(arg interface{}) string {
	switch reflect.TypeOf(arg).Kind() {
	case reflect.Int:
		return "int"
	case reflect.Int8:
		return "int8"
	case reflect.Int16:
		return "int16"
	case reflect.Int32:
		return "int32"
	case reflect.Int64:
		return "int64"
	case reflect.Uint:
		return "uint"
	case reflect.Uint8:
		return "uint8"
	case reflect.Uint16:
		return "uint16"
	case reflect.Uint32:
		return "uint32"
	case reflect.Uint64:
		return "uint64"
	case reflect.Float32:
		return "float32"
	case reflect.Float64:
		return "float64"
	case reflect.Complex64:
		return "complex64"
	case reflect.Complex128:
		return "complex128"
	case reflect.Bool:
		return "bool"
	case reflect.String:
		return "string"
	case reflect.Chan:
		return "chan"
	case reflect.Ptr:
		return "ptr"
	case reflect.Uintptr:
		return "uintptr"
	case reflect.UnsafePointer:
		return "unsafeptr"
	case reflect.Interface:
		return "interface"
	case reflect.Array:
		return "array"
	case reflect.Slice:
		return "slice"
	case reflect.Map:
		return "map"
	case reflect.Struct:
		return "struct"
	case reflect.Func:
		return "func"
	case reflect.Invalid:
		return "invalid"
	default:
		return "nil"
	}
}

/* ~~~~~~~~~~ */

func _scln() string {
	ln, _ := in.ReadString('\n')
	return strings.Trim(ln, " \r\n")
}
func _sc(s []string) string {
	if len(s) == 0 {
		return _scln()
	}
	return s[0]
}

func readLine() string              { return _scln() }
func readString() string            { return _scln() }
func readStrings() []string         { return strings.Split(_scln(), " ") }
func readBool(s ...string) bool     { t, _ := strconv.ParseBool(_sc(s)); return t }
func readByte(s ...string) byte     { t, _ := strconv.ParseUint(_sc(s), 10, 8); return byte(t) }
func readDouble(s ...string) double { t, _ := strconv.ParseFloat(_sc(s), 64); return t }
func readFloat(s ...string) float   { t, _ := strconv.ParseFloat(_sc(s), 32); return float32(t) }
func readInt(s ...string) int       { t, _ := strconv.Atoi(_sc(s)); return t }
func readLong(s ...string) long     { t, _ := strconv.ParseInt(_sc(s), 10, 64); return t }
func readULong(s ...string) ulong   { t, _ := strconv.ParseUint(_sc(s), 10, 64); return t }

/* ~~~~~~~~~~ */

// Too much overhead with universal method using interface{}, wait for the generics,
// but for now — just don't look at the redundancy of the code after that commentary :)

func readBools() []bool {
	strs := readStrings()
	arr := make([]bool, len(strs))
	for i, s := range strs {
		arr[i] = readBool(s)
	}
	return arr
}
func readBytes() []byte {
	strs := readStrings()
	arr := make([]byte, len(strs))
	for i, s := range strs {
		arr[i] = readByte(s)
	}
	return arr
}
func readDoubles() []double {
	strs := readStrings()
	arr := make([]double, len(strs))
	for i, s := range strs {
		arr[i] = readDouble(s)
	}
	return arr
}
func readFloats() []float {
	strs := readStrings()
	arr := make([]float, len(strs))
	for i, s := range strs {
		arr[i] = readFloat(s)
	}
	return arr
}
func readInts() []int {
	strs := readStrings()
	arr := make([]int, len(strs))
	for i, s := range strs {
		arr[i] = readInt(s)
	}
	return arr
}
func readLongs() []long {
	strs := readStrings()
	arr := make([]long, len(strs))
	for i, s := range strs {
		arr[i] = readLong(s)
	}
	return arr
}
func readULongs() []ulong {
	strs := readStrings()
	arr := make([]ulong, len(strs))
	for i, s := range strs {
		arr[i] = readULong(s)
	}
	return arr
}

/* ~~~~~~~~~~ */

func write(arg ...interface{})                 { fmt.Print(arg...) }
func writeLine(arg ...interface{})             { fmt.Println(arg...) }
func writeFormat(f string, arg ...interface{}) { fmt.Printf(f, arg...) }


Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally.

The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even.

If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes).

NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1215D(in io.Reader, out io.Writer) {
	var n, sl, cl, sr, cr int
	var s []byte
	Fscan(bufio.NewReader(in), &n, &s)
	for _, b := range s[:n/2] {
		if b != '?' {
			sl += int(b & 15)
		} else {
			cl++
		}
	}
	for _, b := range s[n/2:] {
		if b != '?' {
			sr += int(b & 15)
		} else {
			cr++
		}
	}
	if (cl+cr)&1 > 0 {
		Fprint(out, "Monocarp")
		return
	}
	if sl == sr {
		if cl != cr {
			Fprint(out, "Monocarp")
		} else {
			Fprint(out, "Bicarp")
		}
		return
	}
	if cl > cr {
		sl, cl, sr, cr = sr, cr, sl, cl
	}
	if sl != sr+(cr-cl)/2*9 {
		Fprint(out, "Monocarp")
	} else {
		Fprint(out, "Bicarp")
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	var n, sl, cl, sr, cr int
	var s []byte
	Fscan(bufio.NewReader(os.Stdin), &n, &s)
	for _, b := range s[:n/2] {
		if b != '?' {
			sl += int(b & 15)
		} else {
			cl++
		}
	}
	for _, b := range s[n/2:] {
		if b != '?' {
			sr += int(b & 15)
		} else {
			cr++
		}
	}
	if (cl+cr)&1 > 0 {
		Print("Monocarp")
		return
	}
	if sl == sr {
		if cl != cr {
			Print("Monocarp")
		} else {
			Print("Bicarp")
		}
		return
	}
	if cl > cr {
		sl, cl, sr, cr = sr, cr, sl, cl
	}
	if sl != sr+(cr-cl)/2*9 {
		Print("Monocarp")
	} else {
		Print("Bicarp")
	}
}

package main

import (
    "bufio"
    "fmt"
    "os"
)
const(
    mod int = 1e9 + 7
    N = 1e6
)
func main() {
    in := bufio.NewReader(os.Stdin)
    var n int
    var s string
    fmt.Fscan(in, &n)
    fmt.Fscan(in, &s)
    sum := make([]int, 2)
    x := make([]int, 2)
    for i := 0; i < n / 2; i++ {
        if s[i] == '?' {
            x[0]++
        }else {
            sum[0] += int(s[i] - '0')
        }
    }
    for i := n / 2; i < n; i++ {
        if s[i] == '?' {
            x[1]++
        }else {
            sum[1] += int(s[i] - '0')
        }
    }
    if sum[0] == sum[1] {
        if x[0] == x[1] {
            fmt.Println("Bicarp")
        }else{
            fmt.Println("Monocarp")
        }
    }else{
        b := 1
        for i := 0; i < n / 2; i++ {
            if s[i] == '?' {
                sum[0] += b * 9
                b ^= 1
            }
        }
        b ^= 1
        for i := n / 2; i < n; i++ {
            if s[i] == '?' {
                sum[1] += b * 9
                b ^= 1
            }
        }
        if sum[0] == sum[1] {
            fmt.Println("Bicarp")
        }else{
            fmt.Println("Monocarp")
        }
    }
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1215D(in io.Reader, out io.Writer) {
	var n, sl, cl, sr, cr int
	var s []byte
	Fscan(bufio.NewReader(in), &n, &s)
	for _, b := range s[:n/2] {
		if b != '?' {
			sl += int(b & 15)
		} else {
			cl++
		}
	}
	for _, b := range s[n/2:] {
		if b != '?' {
			sr += int(b & 15)
		} else {
			cr++
		}
	}
	if (cl+cr)&1 > 0 {
		Fprint(out, "Monocarp")
		return
	}
	if sl == sr {
		if cl == cr {
			Fprint(out, "Bicarp")
		} else {
			Fprint(out, "Monocarp")
		}
		return
	}
	if cl > cr {
		sl, cl, sr, cr = sr, cr, sl, cl
	}
	if sl > sr && sl+cl*9 <= sr+((cl+cr)/2)*9 {
		Fprint(out, "Bicarp")
	} else {
		Fprint(out, "Monocarp")
	}
}

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


The little girl loves the problems on array queries very much.One day she came across a rather well-known problem: you've got an array of $$$n$$$ elements (the elements of the array are indexed starting from 1); also, there are $$$q$$$ queries, each one is defined by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \le l_i \le r_i \le n)$$$. You need to find for each query the sum of elements of the array with indexes from $$$l_i$$$ to $$$r_i$$$, inclusive.The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.

The first line contains two space-separated integers $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) and $$$q$$$ ($$$1 \le q \le 2\cdot10^5$$$) — the number of elements in the array and the number of queries, correspondingly. The next line contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \le a_i \le 2\cdot10^5$$$) — the array elements. Each of the following $$$q$$$ lines contains two space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the $$$i$$$-th query.

In a single line print, a single integer — the maximum sum of query replies after the array elements are reordered. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

package main

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

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

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

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

	s := make([]int, n)
	for i := 0; i < q; i++ {
		var l, r int
		fmt.Fscan(in, &l, &r)
		s[l-1]++
		if r < n {
			s[r]--
		}
	}

	d := 0
	for i := 0; i < n; i++ {
		d += s[i]
		s[i] = d
	}

	sort.Ints(s)
	sort.Ints(a)

	var sum int64
	for i, v := range a {
		sum += int64(s[i]) * int64(v)
	}
	fmt.Println(sum)
}

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

func main() {
	var n,q,l,r int
	var ans int64
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&n,&q)
	a :=make([]int,n)
	x :=make([]int,n)
	t :=make([]int,n+1)
	for i:=0;i<n;i++ {
		input.Scan()
		aa,_:=strconv.Atoi(input.Text())
		a[i]=aa
	}
	sort.Ints(a)
	for i:=0;i<q;i++ {
		input.Scan()
		cc,_:=strconv.Atoi(input.Text())
		l=cc
		input.Scan()
		bb,_:=strconv.Atoi(input.Text())
		r=bb
		t[l-1]++
		t[r]--
	}
	for i:=1;i<n;i++ {
		t[i]+=t[i-1]
	}
	sort.Sort(sort.Reverse(sort.IntSlice(t)))

	for i,j:=n-1,0;i>=0;i-- {
		x[j]=t[i]
		//fmt.Println(t[i])
		j++
	}
	for i:=0;i<n;i++ {
		ans+=int64(a[i])*int64(x[i])
	}
	fmt.Println(ans)
}

package main

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

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

    ScanInts := func(a... *int) {
        for i := 0; i < len(a); i++ {
            scanner.Scan()
            *(a[i]), _ = strconv.Atoi(scanner.Text())
        }
    }

    var n,q,l,r int
    ScanInts(&n,&q)
    a, x := make([]int,n), make([]int,n)
    for i := 0; i < n; i++ {
        ScanInts(&a[i])
    }
    sort.Ints(a)
    for i := 0; i < q; i++ {
        ScanInts(&l,&r)
        l--; r--;
        x[l]++
        if (r+1) < n { x[r+1]-- }
    }
    for i := 1; i < n; i++ {
        x[i] += x[i-1]
    }
    sort.Ints(x)
    ans := int64(0)
    for i := 0; i < n; i++ {
        ans += int64(a[i])*int64(x[i])
    }
    fmt.Println(ans)
}

package main

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

type Op struct {
	l, r, d int
}

type Pair struct {
	l, r int
}

type BITTree struct {
	n int
	s []int64
}

func NewBITTree(n int) *BITTree {
	t := BITTree{n: n, s: make([]int64, n+1)}
	return &t
}

func (t *BITTree) Update(x int, val int64) {
	x++
	for ; x <= t.n; x += x & -x {
		t.s[x] += val
	}
}

func (t *BITTree) GetSum(x int) int64 {
	x++
	var sum int64 = 0
	for ; x > 0; x -= x & -x {
		sum += t.s[x]
	}
	return sum
}

func main() {
	stdin := bufio.NewReader(os.Stdin)
	stdout := bufio.NewWriter(os.Stdout)

	for true {
		var n, q int
		if _, err := fmt.Fscan(stdin, &n, &q); err != nil {
			break
		}
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(stdin, &a[i])
		}
		t := NewBITTree(n)
		for i := 0; i < q; i++ {
			var l, r int
			fmt.Fscan(stdin, &l, &r)
			l--
			r--
			t.Update(l, 1)
			if r + 1 < n {
				t.Update(r + 1, -1)
			}
		}
		count := make([]int, n)
		for i := 0; i < n; i++ {
			count[i] = int(t.GetSum(i))
			//fmt.Printf("count[%d] = %d\n", i, count[i])
		}
		sort.Ints(count)
		sort.Ints(a)
		sum := int64(0)
		for i := 0; i < n; i++ {
			sum += int64(count[i]) * int64(a[i])
		}
		fmt.Fprintf(stdout, "%d\n", sum)
		stdout.Flush()
	}
}

package main

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

type LRStruct struct {
	l int64
	r int64
	val int64
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n, m int
	fmt.Fscanln(reader, &n, &m)

	a := make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
		//a[i] = int64(i)
	}
	fmt.Fscanln(reader)
	//fmt.Println("*****")
	countArray := make([]LRStruct, n)
	for i := 0; i < m; i++ {
		var l, r int64 //= int64(i+1), int64(n)
		fmt.Fscanln(reader, &l, &r)
		countArray[l-1].l++
		countArray[r-1].r++
	}
	countArray[0].val = countArray[0].l
	for i := 1; i < n; i++ {
		countArray[i].val =  countArray[i-1].l - countArray[i-1].r + countArray[i].l
		countArray[i].l += countArray[i-1].l - countArray[i-1].r
	}
	//fmt.Println("======")
	sort.Slice(countArray, func(i, j int) bool {
		return countArray[i].val > countArray[j].val
	})
	//fmt.Println("++++++++")
	sort.Slice(a, func(i, j int) bool {
		return a[i] > a[j]
	})

	var retSum int64
	for i := 0; i < n; i++ {
		retSum += a[i] * countArray[i].val
	}
	fmt.Println(retSum)
}

package main

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

type uintslice []uint64

func (uis uintslice) Len() int {
	return len(uis)
}

func (uis uintslice) Less(i, j int) bool {
	return uis[i] < uis[j]
}

func (uis uintslice) Swap(i, j int) {
	uis[i], uis[j] = uis[j], uis[i]
}

func main() {
	var n, q int
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%d", &n)
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%d", &q)
	scanner.Split(bufio.ScanWords)
	a := make([]int, n)
	b := make(uintslice, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	var s, e int
	for j := 0; j < q; j++ {
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d", &s)
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d", &e)
		b[s-1]++
		if e != n {
			b[e]--
		}

	}
	for j := 1; j < n; j++ {
		b[j] += b[j-1]
	}

	sort.Ints(a)
	sort.Sort(b)
	var res uint64
	for j := 0; j < n; j++ {
		res += uint64(a[j]) * b[j]
	}
	fmt.Print(res)
}

func toInt(buf []byte) (n int) {
	for _, v := range buf {
		n = n*10 + int(v-'0')
	}
	return
}

package main

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

type uintslice []uint64

func (uis uintslice) Len() int {
	return len(uis)
}

func (uis uintslice) Less(i, j int) bool {
	return uis[i] < uis[j]
}

func (uis uintslice) Swap(i, j int) {
	uis[i], uis[j] = uis[j], uis[i]
}

func main() {
	var n, q int
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%d", &n)
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%d", &q)
	scanner.Split(bufio.ScanWords)
	a := make(uintslice, n)
	b := make(uintslice, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		a[i] = toUInt(scanner.Bytes())
	}

	var s, e int
	for j := 0; j < q; j++ {
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d", &s)
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d", &e)
		b[s-1]++
		if e != n {
			b[e]--
		}

	}
	for j := 1; j < n; j++ {
		b[j] += b[j-1]
	}

	sort.Sort(a)
	sort.Sort(b)
	var res uint64
	for j := 0; j < n; j++ {
		res += a[j] * b[j]
	}
	fmt.Print(res)
}

func toInt(buf []byte) (n int) {
	for _, v := range buf {
		n = n*10 + int(v-'0')
	}
	return
}

func toUInt(buf []byte) (n uint64) {
	for _, v := range buf {
		n = n*10 + uint64(v-'0')
	}
	return
}

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/276/C

package main

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

type Query struct {
	l int
	r int
}

func Solve(n int, a []int, queries []Query) int64 {
	sort.Ints(a)
	dp := make([]int, n+2)
	for _, query := range queries {
		dp[query.l] += 1
		dp[query.r+1] -= 1
	}
	sums := make([]int, n+1)
	for i := 1; i <= n; i++ {
		sums[i] += dp[i] + sums[i-1]
	}
	sort.Ints(sums)
	ans := int64(0)
	for i := 1; i <= n; i++ {
		ans += int64(sums[i]) * int64(a[i-1])
	}
	return ans
}

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

	var n, q int
	fmt.Fscanf(reader, "%d %d\n", &n, &q)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &a[i])
	}
	fmt.Fscanf(reader, "\n")
	queries := make([]Query, q)
	for i := 0; i < q; i++ {
		fmt.Fscanf(reader, "%d %d\n", &queries[i].l, &queries[i].r)
	}

	fmt.Fprintf(writer, "%d\n", Solve(n, a, queries))
}

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

func main() {
	var ans,n,q,l,r int
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&n,&q)
	a :=make([]int,n)
	x :=make([]int,n)
	t :=make([]int,n+1)
	for i:=0;i<n;i++ {
		input.Scan()
		aa,_:=strconv.Atoi(input.Text())
		a[i]=aa
	}
	sort.Ints(a)
	for i:=0;i<q;i++ {
		input.Scan()
		cc,_:=strconv.Atoi(input.Text())
		l=cc
		input.Scan()
		bb,_:=strconv.Atoi(input.Text())
		r=bb
		t[l-1]++
		t[r]--
	}
	for i:=1;i<n;i++ {
		t[i]+=t[i-1]
	}
	sort.Sort(sort.Reverse(sort.IntSlice(t)))

	for i,j:=n-1,0;i>=0;i-- {
		x[j]=t[i]
		//fmt.Println(t[i])
		j++
	}
	for i:=0;i<n;i++ {
		ans+=a[i]*x[i]
	}
	fmt.Println(ans)
}

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

func main() {
	var ans,n,q,l,r int
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&n,&q)
	a :=make([]int,n)
	x :=make([]int,n)
	t :=make([]int,200010)
	for i:=0;i<n;i++ {
		input.Scan()
		aa,_:=strconv.Atoi(input.Text())
		a[i]=aa
	}
	sort.Ints(a)
	for i:=0;i<q;i++ {
		input.Scan()
		cc,_:=strconv.Atoi(input.Text())
		l=cc
		input.Scan()
		bb,_:=strconv.Atoi(input.Text())
		r=bb
		t[l-1]++
		t[r]--
	}
	for i:=1;i<n;i++ {
		t[i]+=t[i-1]
	}
	sort.Sort(sort.Reverse(sort.IntSlice(t)))

	for i,j:=n-1,0;i>=0;i-- {
		x[j]=t[i]
		//fmt.Println(t[i])
		j++
	}
	for i:=0;i<n;i++ {
		ans+=a[i]*x[i]
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, q int
	fmt.Scanln(&n, &q)
	a := make([]int, n)
	var x int
	for i := 0; i < n; i++ {
		_, _ = fmt.Scan(&x)
		a = append(a, x)
	}
	b := make([]int, n)
	var s, e int
	for j := 0; j < q; j++ {
		_, _ = fmt.Scan(&s, &e)
		b[s-1]++
		if e != n {
			b[e]--
		}

	}
	for j := 1; j < n; j++ {
		b[j] += b[j-1]
	}

	sort.Ints(a)
	sort.Ints(b)
	var res uint64
	for j := 0; j < n; j++ {
		res += uint64(a[j] * b[j])
	}
	fmt.Print(res)
}

package main

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

type uintslice []uint64

func (uis uintslice) Len() int {
	return len(uis)
}

func (uis uintslice) Less(i, j int) bool {
	return uis[i] < uis[j]
}

func (uis uintslice) Swap(i, j int) {
	uis[i], uis[j] = uis[j], uis[i]
}

func main() {
	var n, q int
	scanner := bufio.NewScanner(os.Stdin)

	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%d %d", &n, &q)
	a := make(uintslice, n)
	b := make(uintslice, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		a[i] = toUInt(scanner.Bytes())
	}

	var s, e int
	for j := 0; j < q; j++ {
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d %d", &s, &e)
		b[s-1]++
		if e != n {
			b[e]--
		}

	}
	for j := 1; j < n; j++ {
		b[j] += b[j-1]
	}

	sort.Sort(a)
	sort.Sort(b)
	var res uint64
	for j := 0; j < n; j++ {
		res += a[j] * b[j]
	}
	fmt.Print(res)
}

func toInt(buf []byte) (n int) {
	for _, v := range buf {
		n = n*10 + int(v-'0')
	}
	return
}

func toUInt(buf []byte) (n uint64) {
	for _, v := range buf {
		n = n*10 + uint64(v-'0')
	}
	return
}