Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence $$$s$$$ is called correct if:   $$$s$$$ is empty;  $$$s$$$ is equal to "($$$t$$$)", where $$$t$$$ is correct bracket sequence;  $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.

First of line of input contains a single number $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — length of the sequence which Petya received for his birthday. Second line of the input contains bracket sequence of length $$$n$$$, containing symbols "(" and ")".

Print "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No".

NoteIn the first example, Petya can move first bracket to the end, thus turning the sequence into "()", which is correct bracket sequence.In the second example, there is no way to move at most one bracket so that the sequence becomes correct.In the third example, the sequence is already correct and there's no need to move brackets.

package main

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

/* solution */

func solve() {

	n := readInt()
	s := read()

	if n%2 == 1 {
		print("NO")
		return
	}

	cur := 0
	for _, c := range s {
		switch c {
		case '(':
			cur++
		case ')':
			cur--
		}
		if cur < -1 {
			print("NO")
			return
		}
	}

	if cur == 0 {
		print("YES")
	} else {
		print("NO")
	}

}

/* stubs */

func main() {

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

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

	reader = bufio.NewScanner(f)

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

	reader.Split(bufio.ScanLines)

	solve()

}

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

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

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

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

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

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

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

package main

import (
	"fmt"
)

func main() {
	var n int
	var s string
	fmt.Scan(&n, &s)
	l, r := 0, 0
	for _, i := range s {
		if i == '(' {
			l++
		} else {
			if l > 0 {
				l--
			} else {
				r++
			}
		}
	}
	if l == r && r <= 1 {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

package main

import "fmt"

func main() {
	n := 0;
	name := "";
	fmt.Scanf("%d\n", &n);
	fmt.Scanf("%s\n", &name);

	op := 0;
	acc := 0;
	ok := true;
	for i:= 0; i < n; i++ {
		if name[i] == '(' {
			acc ++;
		} else {
			if acc == 0 {
				if op == 0 {
					op = 1;
				} else {
					ok = false;
				}
			} else {
				acc --;
			}
		}
	}

	acc -= op;
	if ok && acc == 0 {
		fmt.Printf("Yes");
	} else {
		fmt.Printf("No");
	}
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var a int
	var s string
	fmt.Scan(&a, &s)
	l := strings.Count(s, "(")
	r := strings.Count(s, ")")
	if l != r {
		fmt.Println("No")
	} else {
		min := 0
		cnt := 0
		for i := 0; i < len(s); i++ {
			if s[i] == '(' {
				cnt++
			} else {
				cnt--
			}
			if cnt < min {
				min = cnt
			}
		}
		if min < -1 {
			fmt.Println("No")
		} else {
			fmt.Println("Yes")
		}
	}
}

package main

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

func main() {

	//stdin, err := os.Open("in.txt")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	var n int
	fmt.Fscanf(reader, "%d\n", &n)

	var s string
	fmt.Fscanf(reader, "%s", &s)

	var o, p int
	for i := 0; i < n; i++ {
		if s[i] == ')' {
			o--
		} else {
			o++
		}
		if i < 0 {
			p++
		}
		if o < -1 || p > 1 {
			fmt.Println("No")
			return
		}

	}
	if o == 0 {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}

}


Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or  - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di =  - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them.

The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected.

Print  - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1.

NoteIn the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.

package main

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

const maxInputSize = 512 * 1024 //bytes
var answer []*edge

type edge struct {
	index int
	to    int
}

type edges []*edge

func (e edges) Len() int {
	return len(e)
}

func (e edges) Less(i, j int) bool {
	return e[i].index < e[j].index
}

func (e edges) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, maxInputSize), maxInputSize)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ := strconv.Atoi(scanner.Text())

	graph := make([][]*edge, n)

	d := make([]int, n)
	total := 0
	for i := 0; i < n; i++ {
		scanner.Scan()
		d[i], _ = strconv.Atoi(scanner.Text())
		if d[i] == 1 {
			total++
		}
	}
	for i := 0; i < m; i++ {
		scanner.Scan()
		u, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		v, _ := strconv.Atoi(scanner.Text())

		graph[u-1] = append(graph[u-1], &edge{
			to:    v - 1,
			index: (i + 1),
		})
		graph[v-1] = append(graph[v-1], &edge{
			to:    u - 1,
			index: (i + 1),
		})
	}

	for i := 0; i < n; i++ {
		if d[i] == -1 {
			if total%2 == 1 {
				d[i] = 1
				total = 0
				continue
			}
			d[i] = 0
		}
	}
	if total%2 == 1 {
		fmt.Println(-1)
		return
	}

	traverse(0, graph, d, make([]bool, n))
	print(answer)
}

func print(es []*edge) {
	// sort.Sort(edges(es))
	fmt.Println(len(es))
	for _, e := range es {
		fmt.Println(e.index)
	}
}

func traverse(cur int, graph [][]*edge, d []int, marked []bool) int {
	marked[cur] = true

	counted := 0
	for _, e := range graph[cur] {
		if marked[e.to] {
			continue
		}
		t := traverse(e.to, graph, d, marked)

		if t == 1 {
			counted++
			answer = append(answer, e)
		}
	}

	if d[cur]%2 != counted%2 {
		return 1
	}
	return 0
}

package main

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

const maxInputSize = 512 * 1024 //bytes

type edge struct {
	index   int
	counted bool
	to      int
}

type edges []*edge

func (e edges) Len() int {
	return len(e)
}

func (e edges) Less(i, j int) bool {
	return e[i].index < e[j].index
}

func (e edges) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, maxInputSize), maxInputSize)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ := strconv.Atoi(scanner.Text())

	graph := make([][]*edge, n)

	d := make([]int, n)
	total := 0
	for i := 0; i < n; i++ {
		scanner.Scan()
		d[i], _ = strconv.Atoi(scanner.Text())
		if d[i] == 1 {
			total++
		}
	}
	for i := 0; i < m; i++ {
		scanner.Scan()
		u, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		v, _ := strconv.Atoi(scanner.Text())

		graph[u-1] = append(graph[u-1], &edge{
			to:    v - 1,
			index: (i + 1),
		})
		graph[v-1] = append(graph[v-1], &edge{
			to:    u - 1,
			index: (i + 1),
		})
	}
	answer := make([]*edge, 0)

	for i := 0; i < n; i++ {
		if d[i] == -1 {
			if total%2 == 1 {
				d[i] = 1
				total = 0
				continue
			}
			d[i] = 0
		}
	}
	// now there are no "-1"s ...
	// by handshaking lemma https://en.wikipedia.org/wiki/Handshaking_lemma :
	// number of vertices with odd degree is odd
	// so let's check that this holds
	if total%2 == 1 {
		fmt.Println(-1)
		return
	}

	//let's do dfs now
	answer, _ = traverse(0, graph, d, make([]bool, n), make([]*edge, 0))
	print(answer)
}

func print(es []*edge) {
	sort.Sort(edges(es))
	fmt.Println(len(es))
	for _, e := range es {
		fmt.Println(e.index)
	}
}

func traverse(cur int, graph [][]*edge, d []int, marked []bool, answer []*edge) ([]*edge, int) {
	marked[cur] = true

	counted := 0
	for _, e := range graph[cur] {
		if marked[e.to] {
			// if e.counted {
			// counted++
			// }
			continue
		}
		var t int
		answer, t = traverse(e.to, graph, d, marked, answer)
		if t == 1 {
			counted++
			answer = append(answer, e)
			e.counted = true
		}
	}

	if d[cur]%2 != counted%2 {
		return answer, 1
	}
	return answer, 0
}

package main

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

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

	var n, m, v, w int
	Fscan(in, &n, &m)
	neg, s := -1, int8(0)
	d := make([]int8, n)
	for i := range d {
		Fscan(in, &d[i])
		if d[i] < 0 {
			d[i] = 0
			neg = i
		} else {
			s ^= d[i]
		}
	}
	if neg < 0 {
		if s > 0 {
			Fprint(out, -1)
			return
		}
	} else {
		d[neg] = s
	}

	type nb struct{ to, i int }
	g := make([][]nb, n)
	for i := 1; i <= m; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], nb{w, i})
		g[w] = append(g[w], nb{v, i})
	}
	ans := []interface{}{}
	vis := make([]bool, n)
	var f func(int) int8
	f = func(v int) int8 {
		vis[v] = true
		s := d[v]
		for _, e := range g[v] {
			if w := e.to; !vis[w] && f(w) > 0 {
				ans = append(ans, e.i)
				s ^= 1
			}
		}
		return s
	}
	f(0)
	Fprintln(out, len(ans))
	Fprintln(out, ans...)
}

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

package main

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

const maxInputSize = 512 * 1024 //bytes

type edge struct {
	index int
	to    int
}

type edges []*edge

func (e edges) Len() int {
	return len(e)
}

func (e edges) Less(i, j int) bool {
	return e[i].index < e[j].index
}

func (e edges) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, maxInputSize), maxInputSize)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ := strconv.Atoi(scanner.Text())

	graph := make([][]*edge, n)

	d := make([]int, n)
	total := 0
	for i := 0; i < n; i++ {
		scanner.Scan()
		d[i], _ = strconv.Atoi(scanner.Text())
		if d[i] == 1 {
			total++
		}
	}
	for i := 0; i < m; i++ {
		scanner.Scan()
		u, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		v, _ := strconv.Atoi(scanner.Text())

		graph[u-1] = append(graph[u-1], &edge{
			to:    v - 1,
			index: (i + 1),
		})
		graph[v-1] = append(graph[v-1], &edge{
			to:    u - 1,
			index: (i + 1),
		})
	}
	answer := make([]*edge, 0)

	for i := 0; i < n; i++ {
		if d[i] == -1 {
			if total%2 == 1 {
				d[i] = 1
				total = 0
				continue
			}
			d[i] = 0
		}
	}
	if total%2 == 1 {
		fmt.Println(-1)
		return
	}

	answer, _ = traverse(0, graph, d, make([]bool, n), make([]*edge, 0))
	print(answer)
}

func print(es []*edge) {
	// sort.Sort(edges(es))
	fmt.Println(len(es))
	for _, e := range es {
		fmt.Println(e.index)
	}
}

func traverse(cur int, graph [][]*edge, d []int, marked []bool, answer []*edge) ([]*edge, int) {
	marked[cur] = true

	counted := 0
	for _, e := range graph[cur] {
		if marked[e.to] {
			continue
		}
		var t int
		answer, t = traverse(e.to, graph, d, marked, answer)
		if t == 1 {
			counted++
			answer = append(answer, e)
		}
	}

	if d[cur]%2 != counted%2 {
		return answer, 1
	}
	return answer, 0
}

package main

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

const maxInputSize = 512 * 1024 //bytes

type edge struct {
	index   int
	counted bool
	to      int
}

type edges []*edge

func (e edges) Len() int {
	return len(e)
}

func (e edges) Less(i, j int) bool {
	return e[i].index < e[j].index
}

func (e edges) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, maxInputSize), maxInputSize)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ := strconv.Atoi(scanner.Text())

	graph := make([][]*edge, n)

	d := make([]int, n)
	total := 0
	for i := 0; i < n; i++ {
		scanner.Scan()
		d[i], _ = strconv.Atoi(scanner.Text())
		if d[i] == 1 {
			total++
		}
	}
	for i := 0; i < m; i++ {
		scanner.Scan()
		u, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		v, _ := strconv.Atoi(scanner.Text())

		graph[u-1] = append(graph[u-1], &edge{
			to:    v - 1,
			index: (i + 1),
		})
		graph[v-1] = append(graph[v-1], &edge{
			to:    u - 1,
			index: (i + 1),
		})
	}
	answer := make([]*edge, 0)

	for i := 0; i < n; i++ {
		if d[i] == -1 {
			if total%2 == 1 {
				d[i] = 1
				total = 0
				continue
			}
			d[i] = 0
		}
	}
	// now there are no "-1"s ...
	// by handshaking lemma https://en.wikipedia.org/wiki/Handshaking_lemma :
	// number of vertices with odd degree is odd
	// so let's check that this holds
	if total%2 == 1 {
		fmt.Println(-1)
		return
	}

	//let's do dfs now
	answer, _ = traverse(0, graph, d, make([]bool, n), make([]*edge, 0))
	print(answer)
}

func print(es []*edge) {
	sort.Sort(edges(es))
	fmt.Println(len(es))
	for _, e := range es {
		fmt.Println(e.index)
	}
}

func traverse(cur int, graph [][]*edge, d []int, marked []bool, answer []*edge) ([]*edge, int) {
	marked[cur] = true

	counted := 0
	for _, e := range graph[cur] {
		if marked[e.to] {
			if e.counted {
				counted++
			}
			continue
		}
		var t int
		answer, t = traverse(e.to, graph, d, marked, answer)
		if t == 1 {
			counted++
			answer = append(answer, e)
			e.counted = true
		}
	}

	if d[cur]%2 != counted%2 {
		return answer, 1
	}
	return answer, 0
}

package main

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

const maxInputSize = 512 * 1024 //bytes

type edge struct {
	index int
	to    int
}

type edges []*edge

func (e edges) Len() int {
	return len(e)
}

func (e edges) Less(i, j int) bool {
	return e[i].index < e[j].index
}

func (e edges) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, maxInputSize), maxInputSize)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ := strconv.Atoi(scanner.Text())

	graph := make([][]*edge, n)

	d := make([]int, n)
	deg := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		d[i], _ = strconv.Atoi(scanner.Text())
	}
	for i := 0; i < m; i++ {
		scanner.Scan()
		u, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		v, _ := strconv.Atoi(scanner.Text())

		graph[u-1] = append(graph[u-1], &edge{
			to:    v - 1,
			index: (i + 1),
		})
		graph[v-1] = append(graph[v-1], &edge{
			to:    u - 1,
			index: (i + 1),
		})
		deg[u-1]++
		deg[v-1]++
	}
	answer := make([]*edge, 0)
	di := -1
	for i := 0; i < n; i++ {
		if d[i] == -1 {
			di = i
		}
	}
	if di != -1 {
		marked := make([]bool, n)
		for _, e := range graph[di] {
			if !marked[e.to] {
				if d[e.to] == 1 {
					answer = append(answer, e)
				}
				marked[e.to] = true
			}
		}
		print(answer)
		return
	}
	// now there are no "-1"s ...
	// by handshaking lemma https://en.wikipedia.org/wiki/Handshaking_lemma :
	// number of vertices with odd degree is odd
	// so let's check that this holds
	odd := 0
	for i := 0; i < n; i++ {
		odd += d[i] % 2
	}
	if odd%2 == 1 {
		fmt.Println(-1)
		return
	}

	//let's do dfs now
	answer, _ = traverse(0, graph, d, make([]bool, n), make([]*edge, 0))
	print(answer)
}

func print(es []*edge) {
	sort.Sort(edges(es))
	fmt.Println(len(es))
	for _, e := range es {
		fmt.Println(e.index)
	}
}

func traverse(cur int, graph [][]*edge, d []int, marked []bool, answer []*edge) ([]*edge, int) {
	marked[cur] = true

	counted := 0
	for _, e := range graph[cur] {
		if marked[e.to] {
			continue
		}
		var t int
		answer, t = traverse(e.to, graph, d, marked, answer)
		if t == 1 {
			counted++
			answer = append(answer, e)
		}
	}

	if d[cur]%2 != counted%2 {
		return answer, 1
	}
	return answer, 0
}

package main

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

const maxInputSize = 512 * 1024 //bytes

type edge struct {
	index int
	to    int
}

type edges []*edge

func (e edges) Len() int {
	return len(e)
}

func (e edges) Less(i, j int) bool {
	return e[i].index < e[j].index
}

func (e edges) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, maxInputSize), maxInputSize)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ := strconv.Atoi(scanner.Text())

	graph := make([][]*edge, n)

	d := make([]int, n)
	deg := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		d[i], _ = strconv.Atoi(scanner.Text())
	}
	for i := 0; i < m; i++ {
		scanner.Scan()
		u, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		v, _ := strconv.Atoi(scanner.Text())

		graph[u-1] = append(graph[u-1], &edge{
			to:    v - 1,
			index: (i + 1),
		})
		graph[v-1] = append(graph[v-1], &edge{
			to:    u - 1,
			index: (i + 1),
		})
		deg[u-1]++
		deg[v-1]++
	}
	answer := make([]*edge, 0)
	di := -1
	for i := 0; i < n; i++ {
		if d[i] == -1 {
			di = i
		}
	}
	if di != -1 {
		marked := make([]bool, n)
		for _, e := range graph[di] {
			if !marked[e.to] {
				if d[e.to] == 1 {
					answer = append(answer, e)
				}
				marked[e.to] = true
			}
		}
		print(answer)
		return
	}
	// now there are no "-1"s ...
	// by handshaking lemma https://en.wikipedia.org/wiki/Handshaking_lemma :
	// number of vertices with odd degree is odd
	// so let's check that this holds
	odd := 0
	for i := 0; i < n; i++ {
		odd += deg[i] % 2
	}
	if odd%2 == 1 {
		fmt.Println(-1)
		return
	}

	//let's do dfs now
	answer, _ = traverse(0, graph, d, make([]bool, n), make([]*edge, 0))
	print(answer)
}

func print(es []*edge) {
	sort.Sort(edges(es))
	fmt.Println(len(es))
	for _, e := range es {
		fmt.Println(e.index)
	}
}

func traverse(cur int, graph [][]*edge, d []int, marked []bool, answer []*edge) ([]*edge, int) {
	marked[cur] = true

	counted := 0
	for _, e := range graph[cur] {
		if marked[e.to] {
			continue
		}
		var t int
		answer, t = traverse(e.to, graph, d, marked, answer)
		if t == 1 {
			counted++
			answer = append(answer, e)
		}
	}

	if d[cur]%2 != counted%2 {
		return answer, 1
	}
	return answer, 0
}

package main

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

const maxInputSize = 512 * 1024 //bytes

type edge struct {
	index   int
	counted bool
	to      int
}

type edges []*edge

func (e edges) Len() int {
	return len(e)
}

func (e edges) Less(i, j int) bool {
	return e[i].index < e[j].index
}

func (e edges) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, maxInputSize), maxInputSize)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ := strconv.Atoi(scanner.Text())

	graph := make([][]*edge, n)

	d := make([]int, n)
	deg := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		d[i], _ = strconv.Atoi(scanner.Text())
	}
	for i := 0; i < m; i++ {
		scanner.Scan()
		u, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		v, _ := strconv.Atoi(scanner.Text())

		graph[u-1] = append(graph[u-1], &edge{
			to:    v - 1,
			index: (i + 1),
		})
		graph[v-1] = append(graph[v-1], &edge{
			to:    u - 1,
			index: (i + 1),
		})
		deg[u-1]++
		deg[v-1]++
	}
	answer := make([]*edge, 0)
	di := -1
	for i := 0; i < n; i++ {
		if d[i] == -1 {
			di = i
		}
	}
	if di != -1 {
		marked := make([]bool, n)
		for _, e := range graph[di] {
			if !marked[e.to] {
				if d[e.to] == 1 {
					answer = append(answer, e)
				}
				marked[e.to] = true
			}
		}
		print(answer)
		return
	}
	// now there are no "-1"s ...
	// by handshaking lemma https://en.wikipedia.org/wiki/Handshaking_lemma :
	// number of vertices with odd degree is odd
	// so let's check that this holds
	odd := 0
	for i := 0; i < n; i++ {
		odd += d[i] % 2
	}
	if odd%2 == 1 {
		fmt.Println(-1)
		return
	}

	//let's do dfs now
	answer, _ = traverse(0, graph, d, make([]bool, n), make([]*edge, 0))
	print(answer)
}

func print(es []*edge) {
	sort.Sort(edges(es))
	fmt.Println(len(es))
	for _, e := range es {
		fmt.Println(e.index)
	}
}

func traverse(cur int, graph [][]*edge, d []int, marked []bool, answer []*edge) ([]*edge, int) {
	marked[cur] = true

	counted := 0
	for _, e := range graph[cur] {
		if marked[e.to] {
			if e.counted {
				counted++
			}
			continue
		}
		var t int
		answer, t = traverse(e.to, graph, d, marked, answer)
		if t == 1 {
			counted++
			answer = append(answer, e)
			e.counted = true
		}
	}

	if d[cur]%2 != counted%2 {
		return answer, 1
	}
	return answer, 0
}

package main

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

const maxInputSize = 512 * 1024 //bytes

type edge struct {
	index   int
	counted bool
	to      int
}

type edges []*edge

func (e edges) Len() int {
	return len(e)
}

func (e edges) Less(i, j int) bool {
	return e[i].index < e[j].index
}

func (e edges) Swap(i, j int) {
	e[i], e[j] = e[j], e[i]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, maxInputSize), maxInputSize)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ := strconv.Atoi(scanner.Text())

	graph := make([][]*edge, n)

	d := make([]int, n)
	total := 0
	for i := 0; i < n; i++ {
		scanner.Scan()
		d[i], _ = strconv.Atoi(scanner.Text())
		total += (d[i] % 2)
	}
	for i := 0; i < m; i++ {
		scanner.Scan()
		u, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		v, _ := strconv.Atoi(scanner.Text())

		graph[u-1] = append(graph[u-1], &edge{
			to:    v - 1,
			index: (i + 1),
		})
		graph[v-1] = append(graph[v-1], &edge{
			to:    u - 1,
			index: (i + 1),
		})
	}
	answer := make([]*edge, 0)
	for i := 0; i < n; i++ {
		if d[i] == -1 {
			if total%2 == 1 {
				d[i] = 1
				total = 0
				continue
			}
			d[i] = 0
		}
	}
	// now there are no "-1"s ...
	// by handshaking lemma https://en.wikipedia.org/wiki/Handshaking_lemma :
	// number of vertices with odd degree is odd
	// so let's check that this holds
	if total%2 == 1 {
		fmt.Println(-1)
		return
	}

	//let's do dfs now
	answer, _ = traverse(0, graph, d, make([]bool, n), make([]*edge, 0))
	print(answer)
}

func print(es []*edge) {
	sort.Sort(edges(es))
	fmt.Println(len(es))
	for _, e := range es {
		fmt.Println(e.index)
	}
}

func traverse(cur int, graph [][]*edge, d []int, marked []bool, answer []*edge) ([]*edge, int) {
	marked[cur] = true

	counted := 0
	for _, e := range graph[cur] {
		if marked[e.to] {
			if e.counted {
				counted++
			}
			continue
		}
		var t int
		answer, t = traverse(e.to, graph, d, marked, answer)
		if t == 1 {
			counted++
			answer = append(answer, e)
			e.counted = true
		}
	}

	if d[cur]%2 != counted%2 {
		return answer, 1
	}
	return answer, 0
}


You are given two strings $$$s$$$ and $$$t$$$ consisting of lowercase Latin letters. Also you have a string $$$z$$$ which is initially empty. You want string $$$z$$$ to be equal to string $$$t$$$. You can perform the following operation to achieve this: append any subsequence of $$$s$$$ at the end of string $$$z$$$. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if $$$z = ac$$$, $$$s = abcde$$$, you may turn $$$z$$$ into following strings in one operation:   $$$z = acace$$$ (if we choose subsequence $$$ace$$$);  $$$z = acbcd$$$ (if we choose subsequence $$$bcd$$$);  $$$z = acbce$$$ (if we choose subsequence $$$bce$$$). Note that after this operation string $$$s$$$ doesn't change.Calculate the minimum number of such operations to turn string $$$z$$$ into string $$$t$$$.

The first line contains the integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. The first line of each testcase contains one string $$$s$$$ ($$$1 \le |s| \le 10^5$$$) consisting of lowercase Latin letters. The second line of each testcase contains one string $$$t$$$ ($$$1 \le |t| \le 10^5$$$) consisting of lowercase Latin letters. It is guaranteed that the total length of all strings $$$s$$$ and $$$t$$$ in the input does not exceed $$$2 \cdot 10^5$$$.

For each testcase, print one integer — the minimum number of operations to turn string $$$z$$$ into string $$$t$$$. If it's impossible print $$$-1$$$.

package main

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

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...) }

const maxn int = 1e5+2

var db bool = true

var tc int
var s, t string

var cc [maxn][26]int
var ch_pos [26]int

func main() {
    defer writer.Flush()

    scanf("%d\n", &tc)

    for ; tc > 0; tc-- {

        scanf("%s\n", &s)
        scanf("%s\n", &t)

        for ch := 0; ch < 26; ch++ {
            ch_pos[ch] = 0
        }

        len_s := len(s)
        for i := len_s; i >= 1; i-- {
            for ch := 0; ch < 26; ch++ {
                cc[i][ch] = ch_pos[ch]
            }
            ch_pos[s[i-1]-'a'] = i;
        }
        for ch := 0; ch < 26; ch++ {
            cc[0][ch] = ch_pos[ch]
        }

        ans, ch_v := 0, 0
        len_t := len(t)
        for ti := 0; ti < len_t; {
            ch_v = int(t[ti]-'a')
            if(cc[0][ch_v] == 0) {
                ans = -1
                break;
            }
            ans++
            for si := 0; si <= len_s && ti < len_t; {
                ch_v = int(t[ti]-'a')
                if cc[si][ch_v] == 0 {
                    break;
                } else {
                    si = cc[si][ch_v]
                }
                ti++;
            }
        }
        printf("%d\n", ans)
    }
}

package main

import (
  "fmt"
)

// DEBUG = Only for development
const DEBUG bool = false

func foundL(l []int, maxIndex *int) bool {
  start := 0
  end := len(l)-1

  if(l[start] >= *maxIndex){
    *maxIndex = l[start] + 1
    return true
  }
  if(l[end] == *maxIndex){
    *maxIndex = l[end] + 1
    return true
  }

  if(l[end] < *maxIndex){
    return false
  }

  for end-start > 1{
    mid := (end+start)/2
    if l[mid] == *maxIndex{
      *maxIndex = l[mid] + 1
      return true
    } else if l[mid] > *maxIndex{
      end = mid
    } else {
      start = mid
    }
  }

  *maxIndex = l[end] + 1
  return true
}

func main() {
  if DEBUG {
    fmt.Print("Enter the number of testcases :: ")
  }
  var numTest uint16
  fmt.Scanln(&numTest)

  var s string
  var t string

  for numTest > 0 {
    fmt.Scanln(&s)
    fmt.Scanln(&t)

    if DEBUG {
      fmt.Println("s :: ", s)
      fmt.Println("t :: ", t)
    }

    letterArr := make([][]int, 26)

    for i := range s {
      letterArr[s[i]-'a'] = append(letterArr[s[i]-'a'], i)
    }

    if DEBUG {
      fmt.Println("letterArr :: ", letterArr)
    }

    var maxIndex int = 0
    var cost int = 1
    var notFoundLetter = false

    for i := range t {
      letterIndex := t[i] - 'a'
      //var found bool = false

      if len(letterArr[letterIndex]) == 0{
        notFoundLetter = true
        fmt.Println("-1")
        break
      }

      /*for j := range letterArr[letterIndex] {
        if letterArr[letterIndex][j] >= maxIndex {
          maxIndex = letterArr[letterIndex][j]+1
          found = true
        }
        if found {
          break
        }
      }*/

      if !foundL(letterArr[letterIndex], &maxIndex){
        cost++
        maxIndex = letterArr[letterIndex][0]+1
      }
    }

    if !notFoundLetter {
      fmt.Println(cost)
    }

    numTest--
  }
}

package main

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

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

	var t int
	for Fscan(in, &t); t > 0; t-- {
		var s, t []byte
		Fscan(in, &s, &t)
		pos := [26][]int{}
		for i := range s {
			s[i] -= 'a'
			pos[s[i]] = append(pos[s[i]], i)
		}
		for i := range pos {
			pos[i] = append(pos[i], -1)
		}
		next := make([][]int, len(s)+1)
		next[0] = make([]int, 26)
		for i := range next[0] {
			next[0][i] = pos[i][0]
		}
		cur := [26]int{}
		for i, b := range s {
			cur[b]++
			next[i+1] = make([]int, 26)
			copy(next[i+1], next[i])
			next[i+1][b] = pos[b][cur[b]]
		}
		ans := 0
		for i := 0; i < len(t); {
			si := next[0][t[i]-'a']
			if si == -1 {
				ans = -1
				break
			}
			for i++; i < len(t); i++ {
				si = next[si+1][t[i]-'a']
				if si == -1 {
					break
				}
			}
			ans++
		}
		Fprintln(out, ans)
	}
}

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

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

package main

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

const alphabet = "abcdefghijklmnopqrstuvwxyz"

func createJumpTable(n int) [][]int {
	m := make([][]int, n)
	for i := 0; i < n; i++ {
		m[i] = make([]int, 26)
		for j := 0; j < 26; j++ {
			m[i][j] = -1
		}
	}
	return m
}

func traverseMap(count int, n int, mi int, ti int, m [][]int, t string) int {
	if ti == len(t) {
		return count
	}
	if mi == n {
		return traverseMap(count+1, n, 0, ti, m, t)
	}
	if m[mi][t[ti]-'a'] == -1 && mi == 0 {
		return -1
	}
	if m[mi][t[ti]-'a'] == -1 {
		return traverseMap(count+1, n, 0, ti, m, t)
	}
	return traverseMap(count, n, m[mi][t[ti]-'a']+1, ti+1, m, t)
}

func Solve(s string, t string) int {
	n := len(s)
	m := createJumpTable(n)
	for i := n - 1; i >= 0; i-- {
		for j := 0; j < 26; j++ {
			if i+1 <= n-1 {
				m[i][j] = m[i+1][j]
			}
		}
		m[i][s[i]-'a'] = i
	}
	return traverseMap(1, n, 0, 0, m, t)
}

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

	var T int
	fmt.Fscanf(reader, "%d\n", &T)
	for i := 0; i < T; i++ {
		var s, t string
		fmt.Fscanf(reader, "%s\n%s\n", &s, &t)
		fmt.Fprintf(writer, "%d\n", Solve(s, t))
	}
}


The company "Divan's Sofas" is planning to build $$$n + 1$$$ different buildings on a coordinate line so that:   the coordinate of each building is an integer number;  no two buildings stand at the same point. Let $$$x_i$$$ be the coordinate of the $$$i$$$-th building. To get from the building $$$i$$$ to the building $$$j$$$, Divan spends $$$|x_i - x_j|$$$ minutes, where $$$|y|$$$ is the absolute value of $$$y$$$.All buildings that Divan is going to build can be numbered from $$$0$$$ to $$$n$$$. The businessman will live in the building $$$0$$$, the new headquarters of "Divan's Sofas". In the first ten years after construction Divan will visit the $$$i$$$-th building $$$a_i$$$ times, each time spending $$$2 \cdot |x_0-x_i|$$$ minutes for walking.Divan asks you to choose the coordinates for all $$$n + 1$$$ buildings so that over the next ten years the businessman will spend as little time for walking as possible.

Each test contains several test cases. The first line contains one integer number $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. The first line of each case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of buildings that "Divan's Sofas" is going to build, apart from the headquarters. The second line contains the sequence $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$), where $$$a_i$$$ is the number of visits to the $$$i$$$-th building. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, on the first line print the number $$$T$$$ — the minimum time Divan will spend walking.  On the second line print the sequence $$$x_0, x_1, \ldots, x_n$$$ of $$$n + 1$$$ integers, where $$$x_i$$$ ($$$-10^6 \le x_i \le 10^6$$$) is the selected coordinate of the $$$i$$$-th building. It can be shown that an optimal answer exists with coordinates not exceeding $$$10^6$$$. If there are multiple answers, print any of them.

NoteLet's look at the first example.Divan will visit the first building $$$a_1 = 1$$$ times, the second $$$a_2 = 2$$$ times and the third $$$a_3 = 3$$$ times. Then one of the optimal solution will be as follows:   the headquarters is located in $$$x_0 = 2$$$;  $$$x_1 = 4$$$: Divan will spend $$$2 \cdot |x_0-x_1| \cdot a_1 = 2 \cdot |2-4| \cdot 1 = 4$$$ minutes walking to the first building;  $$$x_2 = 1$$$: Divan will spend $$$2 \cdot |x_0-x_2| \cdot a_2 = 2 \cdot |2-1| \cdot 2 = 4$$$ minutes walking to the second building;  $$$x_3 = 3$$$: Divan will spend $$$2 \cdot |x_0-x_3| \cdot a_3 = 2 \cdot |2-3| \cdot 3 = 6$$$ minutes walking to the third building. In total, Divan will spend $$$4 + 4 + 6 = 14$$$ minutes. It can be shown that it is impossible to arrange buildings so that the businessman spends less time.Among others, $$$x = [1, 3, 2, 0]$$$, $$$x = [-5, -3, -6, -4]$$$ are also correct answers for the first example.

package main

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

type building struct {
	id   int
	v, d int64
}

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)

		b := make([]building, n)
		for i := 0; i < n; i++ {
			var build building
			build.id = i
			fmt.Fscan(in, &build.v)

			b[i] = build
		}

		sort.SliceStable(b, func(i, j int) bool {
			return b[i].v > b[j].v
		})

		ans := make([]int, n+1)
		diff := 1
		var sum int64
		for i := 0; i < n; i++ {
			if i > 0 && i%2 == 0 {
				diff++
			}

			build := b[i]
			build.d = int64(diff)
			sum += build.d * build.v

			if i%2 == 1 {
				build.d *= -1
			}
			ans[build.id+1] = int(build.d)
		}

		fmt.Fprintln(out, sum*2)
		for i := 0; i < n+1; i++ {
			fmt.Fprintf(out, "%d ", ans[i])
		}
		fmt.Fprintln(out)
	}
}

package main

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

type building struct {
	id   int
	v, d int64
}

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)

		b := make([]building, n)
		for i := 0; i < n; i++ {
			var build building
			build.id = i
			fmt.Fscan(in, &build.v)

			b[i] = build
		}

		sort.SliceStable(b, func(i, j int) bool {
			return b[i].v > b[j].v
		})

		m := make(map[int]building, n)
		diff := 1
		var sum int64
		for i := 0; i < n; i++ {
			if i > 0 && i%2 == 0 {
				diff++
			}

			build := b[i]
			build.d = int64(diff)
			sum += build.d * build.v

			if i%2 == 1 {
				build.d *= -1
			}
			m[build.id] = build
		}

		fmt.Fprintln(out, sum*2)
		fmt.Fprintf(out, "%d ", 0)

		for i := 0; i < n; i++ {
			fmt.Fprintf(out, "%d ", m[i].d)
		}
		fmt.Fprintln(out)
	}
}

package main

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

var sc = bufio.NewScanner(os.Stdin)

func scan() string {
	for sc.Scan() {
		break
	}
	return sc.Text()
}

func scanInt() int {
	i, err := strconv.Atoi(scan())
	if err != nil {
		panic(err)
	}
	return i
}

func scanInt8() int8 {
	i, err := strconv.ParseInt(scan(), 10, 8)
	if err != nil {
		panic(err)
	}
	return int8(i)
}

func scanInt64() int64 {
	i, err := strconv.ParseInt(scan(), 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}

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

func min(ints ...int) int {
	a := ints[0]
	n := len(ints)
	for i := 1; i < n; i++ {
		if ints[i] < a {
			a = ints[i]
		}
	}
	return a
}

func max(ints ...int) int {
	a := ints[0]
	n := len(ints)
	for i := 1; i < n; i++ {
		if ints[i] > a {
			a = ints[i]
		}
	}
	return a
}

type Noop struct{}

var noop = Noop{}

type Node struct {
	x int64
	p int
}

func proc() {
	n := scanInt()
	mas := make([]Node, n)
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		mas[i].x = scanInt64()
		mas[i].p = i
	}
	sort.Slice(mas, func(i, j int) bool { return mas[i].x < mas[j].x })
	var ans int64
	k := -1
	for i := n - 1; i >= 0; i-- {
		ans += mas[i].x * int64(abs(k)) * 2
		arr[mas[i].p] = int64(k)
		if k < 0 {
			k = -k
		} else {
			k = -(k + 1)
		}
	}
	fmt.Println(ans)
	fmt.Printf("0 ")
	for i := 0; i < n; i++ {
		if i+1 == n {
			fmt.Println(arr[i])
		} else {
			fmt.Printf("%d ", arr[i])
		}
	}
}

func main() {
	sc.Split(bufio.ScanWords)
	t := scanInt()
	for i := 0; i < t; i++ {
		proc()
	}
}

package main

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

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

var (
	TC, n int
)

type info struct {
	idx, times int
}

func main() {
	defer out.Flush()
	in.Split(bufio.ScanWords)
	TC = nextInt()
	for t := 0; t < TC; t++ {
		n = nextInt()
		a := make([]info, 0)
		for i := 0; i < n; i++ {
			tmp := info{i, nextInt()}
			a = append(a, tmp)
		}
		T, x := solve(a)
		fmt.Fprintln(out, T)
		fmt.Fprintln(out, strings.Trim(fmt.Sprint(x), "[]"))
	}
}

func solve(a []info) (int64, []int) {
	sort.Slice(a, func(i, j int) bool {
		return a[i].times > a[j].times
	})

	min_time := int64(0)
	x := make([]int, len(a)+1)

	x[0] = 0
	coord := 1
	for _, val := range a {
		x[val.idx+1] = coord
		min_time += (int64(abs(coord)) * int64(val.times) * 2)
		coord *= -1
		if coord > 0 {
			coord++
		}
	}

	return min_time, x
}

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

func nextStr() string {
	in.Scan()
	return in.Text()
}

func nextInt() int {
	ret, _ := strconv.Atoi(nextStr())
	return ret
}

package main

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

type Building struct {
	number     int
	coordinate int
	visit      int
}

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

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

func solve(n int, a []Building) string {
	sort.Slice(a, func(i, j int) bool {
		return a[i].visit > a[j].visit
	})
	var time int64
	for i := 0; i < n; i++ {
		a[i].coordinate = i/2 + 1
		if i%2 == 0 {
			a[i].coordinate *= -1
		}
		time += int64(a[i].visit) * int64(abs(a[i].coordinate))
	}
	sort.Slice(a, func(i, j int) bool {
		return a[i].number < a[j].number
	})
	y := make([]string, n+1)
	for i := range a {
		y[i] = fmt.Sprint(a[i].coordinate)
	}
	return fmt.Sprintln(2*time) + strings.Join(y, " ")
}

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

package main

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

var n int

var a []int

func main() {

	r := bufio.NewReader(os.Stdin)

	var t int

	fmt.Fscan(r, &t)

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

		a = make([]int, n)

		for j := 0; j  <n; j++ {
			fmt.Fscan(r, &a[j])
		}

		solve()

		fmt.Println()
	}
}

type pair struct {
	k, v int
}

type ByK []*pair

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

type item struct {
	la, ra int
	lb, rb int
}

const MAX int = 1e6

func solve() {

	var p []*pair

	for i := 0; i < n; i++ {
		p = append(p, &pair{a[i], i})
	}
	sort.Sort(ByK(p))

	ans := make([]int, n + 1)
	ans[0] = 0

	var dist int64

	r := 0
	right := 1
	left := 1

	for i := n - 1; i >= 0; i-- {
		b := p[i].v
		times := p[i].k

		if r % 2 == 0 {
			ans[b + 1] = right
			dist += int64(times) * int64(right)

			right++

		} else {
			ans[b + 1] = -left
			dist+= int64(times)* int64(left)

			left++
		}

		r++
	}

	fmt.Println(2 * dist)

	for i := 0; i <= n; i++ {
		fmt.Print(ans[i], " ")
	}
}

func add(idx int, delta int, bit *[]int, n int) {
	for ; idx <= n; idx += idx & -idx {
		(*bit)[idx] += delta
	}
}

func get(idx int, bit *[]int) int {
	ret := 0
	for ; idx > 0; idx -= idx & -idx {
		ret += (*bit)[idx];
	}
	return ret
}

//A -  1 3 5 3 1

//B -  4 3 6 1

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

package main

import (
	"bufio"
	//	"container/heap" for heap.Init()
	"fmt"
	"os"
	"runtime"
	"sort"
)

func check(b bool) {
	if !b {
		_, _, line, _ := runtime.Caller(1)
		fmt.Printf("check failed line %d\n", line)
		os.Exit(-1)
	}
}

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

type IntHeap []int

func (h IntHeap) Len() int            { return len(h) }
func (h IntHeap) Less(i, j int) bool  { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

const (
	INIT = -1
)

var (
	n   int
	arr []int64
)

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

	var tc int
	fmt.Fscan(r, &tc)

	for ; tc > 0; tc-- {
		fmt.Fscan(r, &n)
		arr = make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &arr[i])
		}

		iord := make([]int, n)
		for i := 0; i < n; i++ {
			iord[i] = i
		}
		sort.Slice(iord, func(i, j int) bool {
			return arr[iord[i]] < arr[iord[j]]
		})

		// for i := 0; i < n; i++ {
		// 	fmt.Printf("%d ", arr[iord[i]])
		// }
		// fmt.Println()

		var sum int64
		var cnt int64
		pos := make([]int64, n+1)
		for i := n - 1; i >= 0; i-- {
			diff := cnt/2 + 1

			sum += 2 * arr[iord[i]] * diff

			if (cnt % 2) == 1 {
				diff = -diff
			}
			pos[iord[i]+1] = diff
			cnt++
		}

		fmt.Println(sum)
		for i := 0; i <= n; i++ {
			fmt.Printf("%d ", pos[i])
		}
		fmt.Println()

	}
}

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func B() {
	var n int64
	scan(&n)
	a := make([][2]int64, n)
	for i := range a {
		a[i][0] = int64(i)
		scan(&a[i][1])
	}
	sort.Slice(a, func(i, j int) bool { return a[i][1] > a[j][1] })

	var x, time int64 = 1, 0
	ans := make([]int64, n)
	for i := range a {
		y := x
		if y < 0 {
			y = -y
		}
		time += a[i][1] * 2 * y
		ans[a[i][0]] = x
		if x < 0 {
			x = -x + 1
		} else {
			x = -x
		}
	}

	printf("%v\n0 ", time)
	for i := int64(0); i < n; i++ {
		printf("%v ", ans[i])
	}
	printf("\n")
}

func main() {
	defer writer.Flush()
	//redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		B()
	}
}

// 00
package main

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

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 abs[K Number](a K) K {
	if a < 0 {
		return -a
	}
	return a
}

type Pair struct {
	i, v int
}

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([]Pair, n)
		as := make([]int, n)
		for i := 0; i < n; i++ {
			a[i] = Pair{i: i}
			fmt.Fscan(reader, &a[i].v)
			as[i] = a[i].v
		}
		sort.Slice(a, func(i, j int) bool { return a[i].v > a[j].v })
		x := make([]int, n+1)
		curr := 1
		for i := 0; i < n; i++ {
			if i%2 == 0 {
				x[a[i].i+1] = curr
			} else {
				x[a[i].i+1] = -curr
			}
			if i%2 == 1 {
				curr++
			}
		}
		ans := int64(0)
		for i := 1; i <= n; i++ {
			ans += abs(int64(as[i-1] * 2 * x[i]))
		}
		write(f, ans, "\n")
		for i := 0; i <= n; i++ {
			write(f, x[i])
			if i == n {
				write(f, "\n")
			} else {
				write(f, " ")
			}
		}
	}
}

package main

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

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

type Value struct {
	value int
	index int
}

func solveCase() {
	var n int
	fmt.Fscan(in, &n)
	var a []Value = make([]Value, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &a[i].value)
		a[i].index = i
	}
	sort.Slice(a[:], func(i, j int) bool {
		return a[i].value > a[j].value
	})
	var ans []int = make([]int, n+1)
	var totalDist int64 = 0
	for i := 0; i < n; i++ {
		var coordinate = (i / 2) + 1
		totalDist += int64(a[i].value) * int64(coordinate)
		if i%2 == 1 {
			coordinate = -coordinate
		}
		ans[a[i].index+1] = coordinate
	}
	fmt.Fprintln(out, totalDist*2)
	for i := 0; i <= n; i++ {
		fmt.Fprintf(out, "%d ", ans[i])
	}
	fmt.Fprintln(out)
}

func main() {
	var ntc int
	fmt.Fscan(in, &ntc)
	for t := 0; t < ntc; t++ {
		solveCase()
	}
	out.Flush()
}

package main

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

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

	solve := func(Case int) {
		var n int
		Fscan(in, &n)
		type pair struct{ v, i int }
		a := make([]pair, n)
		for i := range a {
			Fscan(in, &a[i].v)
			a[i].i = i
		}
		sort.Slice(a, func(i, j int) bool { return a[i].v > a[j].v })
		ans := make([]int, n)
		l,r := -1,1
		t := int64(0)
		for i, p := range a {
			if i&1==0 {
				t+=int64(r)*2*int64(p.v)
				ans[p.i]=r
				r++
			} else {
				t+=int64(-l)*2*int64(p.v)
				ans[p.i] = l
				l--
			}
		}
		Fprintln(out, t)
		Fprint(out, 0," ")
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}

	T := 1
	Fscan(in, &T)
	for Case := 1; Case <= T; Case++ {
		solve(Case)
	}

	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("有未读入的数据：\n" + _s)
	}

}

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

package main

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

type building struct {
	id, v, d int
}

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)

		b := make([]building, n)
		for i := 0; i < n; i++ {
			var build building
			build.id = i
			fmt.Fscan(in, &build.v)

			b[i] = build
		}

		sort.SliceStable(b, func(i, j int) bool {
			return b[i].v > b[j].v
		})

		m := make(map[int]building, n)
		diff := 1
		var sum int
		for i := 0; i < n; i++ {
			if i > 0 && i%2 == 0 {
				diff++
			}

			build := b[i]
			build.d = diff
			sum += build.d * build.v

			if i%2 == 1 {
				build.d *= -1
			}
			m[build.id] = build
		}

		fmt.Fprintln(out, sum*2)
		fmt.Fprintf(out, "%d ", 0)

		for i := 0; i < n; i++ {
			fmt.Fprintf(out, "%d ", m[i].d)
		}
		fmt.Fprintln(out)
	}
}

package main

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

type building struct {
	id, v, d int
}

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)

		b := make([]building, n)
		for i := 0; i < n; i++ {
			var build building
			build.id = i
			fmt.Fscan(in, &build.v)

			b[i] = build
		}

		sort.SliceStable(b, func(i, j int) bool {
			return b[i].v < b[j].v
		})

		var sum int
		m := make(map[int]building, n)
		for i := 0; i < n; i++ {
			b[i].d = ((n - 1 - i) / 2) + 1
			sum += b[i].v * b[i].d
			m[b[i].id] = b[i]
		}

		fmt.Fprintln(out, sum*2)
		fmt.Fprintf(out, "%d ", 0)

		for i := 0; i < n; i++ {
			d := m[i].d
			if i%2 > 0 {
				d *= -1
			}

			fmt.Fprintf(out, "%d ", d)
		}
		fmt.Fprintln(out)
	}
}

package main

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

type building struct {
	id, v int
}

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)

		b := make([]building, n)
		for i := 0; i < n; i++ {
			var build building
			build.id = i
			fmt.Fscan(in, &build.v)

			b[i] = build
		}

		sort.SliceStable(b, func(i, j int) bool {
			return b[i].v < b[j].v
		})

		var sum int
		for i := 0; i < n; i++ {
			d := ((n - 1 - i) / 2) + 1
			sum += b[i].v * d
		}

		fmt.Fprintln(out, sum*2)
		fmt.Fprintf(out, "%d ", 0)

		for i := 0; i < n; i++ {
			d := ((n - 1 - i) / 2) + 1
			if i%2 > 0 {
				d *= -1
			}

			fmt.Fprintf(out, "%d ", d)
		}
		fmt.Fprintln(out)
	}
}

package main

import (
	"fmt"
	"sort"
)

// var sc = bufio.NewScanner(os.Stdin)

// func scan() string {
// 	for sc.Scan() {
// 		break
// 	}
// 	return sc.Text()
// }

// func scanInt() int {
// 	i, err := strconv.Atoi(scan())
// 	if err != nil {
// 		panic(err)
// 	}
// 	return i
// }

// func scanInt8() int8 {
// 	i, err := strconv.ParseInt(scan(), 10, 8)
// 	if err != nil {
// 		panic(err)
// 	}
// 	return int8(i)
// }

// func scanInt64() int64 {
// 	i, err := strconv.ParseInt(scan(), 10, 64)
// 	if err != nil {
// 		panic(err)
// 	}
// 	return i
// }

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

func min(ints ...int) int {
	a := ints[0]
	n := len(ints)
	for i := 1; i < n; i++ {
		if ints[i] < a {
			a = ints[i]
		}
	}
	return a
}

func max(ints ...int) int {
	a := ints[0]
	n := len(ints)
	for i := 1; i < n; i++ {
		if ints[i] > a {
			a = ints[i]
		}
	}
	return a
}

type Noop struct{}

var noop = Noop{}

func proc() {
	var n int
	fmt.Scan(&n)
	mas := make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&mas[i])
	}
	sort.Slice(mas, func(i, j int) bool { return mas[i] < mas[j] })
	var ans int64
	k := -1
	for i := n - 1; i >= 0; i-- {
		ans += mas[i] * int64(abs(k)) * 2
		if k < 0 {
			k = -k
		} else {
			k = -(k + 1)
		}
	}
	fmt.Println(ans)
	k = -1
	fmt.Printf("0 ")
	for i := n - 1; i >= 0; i-- {
		if i == 0 {
			fmt.Println(k)
		} else {
			fmt.Printf("%d ", k)
		}
		if k < 0 {
			k = -k
		} else {
			k = -(k + 1)
		}
	}
}

func main() {
	// sc.Split(bufio.ScanWords)
	var t int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		proc()
	}
}

package main

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

var sc = bufio.NewScanner(os.Stdin)

func scan() string {
	for sc.Scan() {
		break
	}
	return sc.Text()
}

func scanInt() int {
	i, err := strconv.Atoi(scan())
	if err != nil {
		panic(err)
	}
	return i
}

func scanInt8() int8 {
	i, err := strconv.ParseInt(scan(), 10, 8)
	if err != nil {
		panic(err)
	}
	return int8(i)
}

func scanInt64() int64 {
	i, err := strconv.ParseInt(scan(), 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}

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

func min(ints ...int) int {
	a := ints[0]
	n := len(ints)
	for i := 1; i < n; i++ {
		if ints[i] < a {
			a = ints[i]
		}
	}
	return a
}

func max(ints ...int) int {
	a := ints[0]
	n := len(ints)
	for i := 1; i < n; i++ {
		if ints[i] > a {
			a = ints[i]
		}
	}
	return a
}

type Noop struct{}

var noop = Noop{}

func proc() {
	n := scanInt()
	mas := make([]int64, n)
	for i := 0; i < n; i++ {
		mas[i] = scanInt64()
	}
	sort.Slice(mas, func(i, j int) bool { return mas[i] < mas[j] })
	var ans int64
	k := -1
	for i := n - 1; i >= 0; i-- {
		ans += mas[i] * int64(abs(k)) * 2
		if k < 0 {
			k = -k
		} else {
			k = -(k + 1)
		}
	}
	fmt.Println(ans)
	k = -1
	fmt.Printf("0 ")
	for i := n - 1; i >= 0; i-- {
		if i == 0 {
			fmt.Println(k)
		} else {
			fmt.Printf("%d ", k)
		}
		if k < 0 {
			k = -k
		} else {
			k = -(k + 1)
		}
	}
}

func main() {
	sc.Split(bufio.ScanWords)
	t := scanInt()
	for i := 0; i < t; i++ {
		proc()
	}
}

package main

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

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

var (
	TC, n int
)

type info struct {
	idx, times int
}

func main() {
	defer out.Flush()
	in.Split(bufio.ScanWords)
	TC = nextInt()
	for t := 0; t < TC; t++ {
		n = nextInt()
		a := make([]info, 0)
		for i := 0; i < n; i++ {
			tmp := info{i, nextInt()}
			a = append(a, tmp)
		}
		T, x := solve(a)
		fmt.Fprintln(out, T)
		fmt.Fprintln(out, strings.Trim(fmt.Sprint(x), "[]"))
	}
}

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

	min_time := 0
	x := make([]int, len(a)+1)

	x[0] = 0
	coord := 1
	for _, val := range a {
		x[val.idx+1] = coord
		min_time += (abs(coord) * val.times * 2)
		coord *= -1
		if coord > 0 {
			coord++
		}
	}

	return min_time, x
}

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

func nextStr() string {
	in.Scan()
	return in.Text()
}

func nextInt() int {
	ret, _ := strconv.Atoi(nextStr())
	return ret
}

package main

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

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

var (
	TC, n int
)

type info struct {
	idx, times int
}

func main() {
	defer out.Flush()
	in.Split(bufio.ScanWords)
	TC = nextInt()
	for t := 0; t < TC; t++ {
		n = nextInt()
		a := make([]info, 0)
		for i := 0; i < n; i++ {
			tmp := info{i, nextInt()}
			a = append(a, tmp)
		}
		T, x := solve(a)
		fmt.Fprintln(out, T)
		fmt.Fprintln(out, strings.Trim(fmt.Sprint(x), "[]"))
	}
}

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

	min_time := 0
	x := make([]int, len(a)+1)

	x[0] = 0
	coord := 1
	for _, val := range a {
		x[val.idx+1] = coord
		min_time += func(v int) int {
			if v < 0 {
				v *= -1
			}
			return v
		}(coord) * val.times * 2
		coord *= -1
		if coord > 0 {
			coord++
		}
	}

	return min_time, x
}

func nextStr() string {
	in.Scan()
	return in.Text()
}

func nextInt() int {
	ret, _ := strconv.Atoi(nextStr())
	return ret
}

package main

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

var n int

var a []int

func main() {

	r := bufio.NewReader(os.Stdin)

	var t int

	fmt.Fscan(r, &t)

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

		a = make([]int, n)

		for j := 0; j  <n; j++ {
			fmt.Fscan(r, &a[j])
		}

		solve()

		fmt.Println()
	}
}

type pair struct {
	k, v int
}

type ByK []*pair

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

type item struct {
	la, ra int
	lb, rb int
}

const MAX int = 1e6

func solve() {

	var p []*pair

	for i := 0; i < n; i++ {
		p = append(p, &pair{a[i], i})
	}
	sort.Sort(ByK(p))

	ans := make([]int, n + 1)
	ans[0] = 0

	var dist int64

	r := 0
	right := 1
	left := 1

	for i := n - 1; i >= 0; i-- {
		b := p[i].v
		times := p[i].k

		if r % 2 == 0 {
			ans[b] = right
			dist += int64(times) * int64(right)

			right++

		} else {
			ans[b] = -left
			dist+= int64(times)* int64(left)

			left++
		}

		r++
	}

	fmt.Println(2 * dist)

	for i := 0; i <= n; i++ {
		fmt.Print(ans[i], " ")
	}
}

func add(idx int, delta int, bit *[]int, n int) {
	for ; idx <= n; idx += idx & -idx {
		(*bit)[idx] += delta
	}
}

func get(idx int, bit *[]int) int {
	ret := 0
	for ; idx > 0; idx -= idx & -idx {
		ret += (*bit)[idx];
	}
	return ret
}

//A -  1 3 5 3 1

//B -  4 3 6 1

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

package main

import (
	"bufio"
	//	"container/heap" for heap.Init()
	"fmt"
	"os"
	"runtime"
	"sort"
)

func check(b bool) {
	if !b {
		_, _, line, _ := runtime.Caller(1)
		fmt.Printf("check failed line %d\n", line)
		os.Exit(-1)
	}
}

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

type IntHeap []int

func (h IntHeap) Len() int            { return len(h) }
func (h IntHeap) Less(i, j int) bool  { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

const (
	INIT = -1
)

var (
	n   int
	arr []int
)

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

	var tc int
	fmt.Fscan(r, &tc)

	for ; tc > 0; tc-- {
		fmt.Fscan(r, &n)
		arr = make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &arr[i])
		}

		iord := make([]int, n)
		for i := 0; i < n; i++ {
			iord[i] = i
		}
		sort.Slice(iord, func(i, j int) bool {
			return arr[iord[i]] < arr[iord[j]]
		})

		// for i := 0; i < n; i++ {
		// 	fmt.Printf("%d ", arr[iord[i]])
		// }
		// fmt.Println()

		sum := 0
		cnt := 0
		pos := make([]int, n+1)
		for i := n - 1; i >= 0; i-- {
			diff := cnt/2 + 1

			sum += 2 * arr[iord[i]] * diff

			if (cnt % 2) == 1 {
				diff = -diff
			}
			pos[iord[i]+1] = diff
			cnt++
		}

		fmt.Println(sum)
		for i := 0; i <= n; i++ {
			fmt.Printf("%d ", pos[i])
		}
		fmt.Println()

	}
}

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func B() {
	n := 0
	scan(&n)
	a := make([][2]int, n)
	for i := range a {
		a[i][0] = i
		scan(&a[i][1])
	}
	sort.Slice(a, func(i, j int) bool { return a[i][1] > a[j][1] })

	x := 1
	time := 0
	ans := make([]int, n)
	for i := range a {
		y := x
		if y < 0 {
			y = -y
		}
		time += a[i][1] * 2 * y
		ans[a[i][0]] = x
		if x < 0 {
			x = -x + 1
		} else {
			x = -x
		}
	}

	printf("%v\n0 ", time)
	for i := 0; i < n; i++ {
		printf("%v ", ans[i])
	}
	printf("\n")
}

func main() {
	defer writer.Flush()
	//redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		B()
	}
}


You are given a tree (a connected acyclic undirected graph) of n vertices. Vertices are numbered from 1 to n and each vertex is assigned a character from a to t.A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome.For each vertex, output the number of palindromic paths passing through it. Note: The path from vertex u to vertex v is considered to be the same as the path from vertex v to vertex u, and this path will be counted only once for each of the vertices it passes through.

The first line contains an integer n (2 ≤ n ≤ 2·105)  — the number of vertices in the tree. The next n - 1 lines each contain two integers u and v (1  ≤  u, v  ≤  n, u ≠ v) denoting an edge connecting vertex u and vertex v. It is guaranteed that the given graph is a tree. The next line contains a string consisting of n lowercase characters from a to t where the i-th (1 ≤ i ≤ n) character is the label of vertex i in the tree.

Print n integers in a single line, the i-th of which is the number of palindromic paths passing through vertex i in the tree.

NoteIn the first sample case, the following paths are palindromic:2 - 3 - 42 - 3 - 54 - 3 - 5Additionally, all paths containing only one vertex are palindromic. Listed below are a few paths in the first sample that are not palindromic:1 - 2 - 31 - 2 - 3 - 41 - 2 - 3 - 5

package main

import (
	"bufio"
	"fmt"
	"io"
	"math/bits"
	"os"
)

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()
	cLim := int('t'-'a') + 1

	n := io.NextInt()
	g := make([][]int, n+1)
	for i := 0; i < n-1; i++ {
		u, v := io.NextInt(), io.NextInt()
		g[u] = append(g[u], v)
		g[v] = append(g[v], u)
	}
	a := make([]int, n+1)
	for i, c := range io.Next() {
		a[i+1] = 1 << (int(c) - 'a')
	}

	good := []int{0}
	for i := 0; i < cLim; i++ {
		good = append(good, 1<<i)
	}
	upto, cnts := make([]int, n+1), make([]int, 1<<cLim)
	ans := make([]int64, n+1)

	centroidDecompose(g, func(cen int) {
		var upd func(u, x, d int)
		upd = func(u, x, d int) {
			upto[u] = x ^ a[u]
			cnts[upto[u]] += d
			for _, v := range g[u] {
				upd(v, upto[u], d)
			}
		}

		var cenCnt int64
		var get func(int) int64
		get = func(u int) int64 {
			var cnt int64
			for _, x := range good {
				cnt += int64(cnts[upto[u]^a[cen]^x])
			}
			if bits.OnesCount(uint(upto[u])) <= 1 {
				cenCnt++
			}
			for _, v := range g[u] {
				cnt += get(v)
			}
			ans[u] += int64(cnt)
			return cnt
		}

		var cnt int64
		upd(cen, 0, +1)
		for _, v := range g[cen] {
			upd(v, a[cen], -1)
			cnt += get(v)
			upd(v, a[cen], +1)
		}
		upd(cen, 0, -1)
		ans[cen] += (cnt-cenCnt)/2 + cenCnt + 1
	})

	for _, x := range ans[1:] {
		fmt.Fprint(io, x, " ")
	}
	fmt.Fprintln(io)
}

func centroidDecompose(g [][]int, f func(int)) {
	remove := func(u, v int) {
		j := len(g[u]) - 1
		for i, x := range g[u] {
			if x == v {
				g[u][i] = g[u][j]
				g[u] = g[u][:j]
				return
			}
		}
	}

	sz := make([]int, len(g))
	var calcSz func(int)
	calcSz = func(u int) {
		sz[u] = 1
		for _, v := range g[u] {
			remove(v, u)
			calcSz(v)
			sz[u] += sz[v]
		}
	}
	calcSz(1)

	var getCentroid func(int) int
	getCentroid = func(u int) int {
		for _, v := range g[u] {
			if sz[v]*2 > sz[u] {
				remove(u, v)
				g[v], sz[u], sz[v] = append(g[v], u), sz[u]-sz[v], sz[u]
				return getCentroid(v)
			}
		}
		return u
	}

	var decompose func(int)
	decompose = func(u int) {
		cen := getCentroid(u)
		f(cen)
		for _, v := range g[cen] {
			remove(v, cen)
			decompose(v)
		}
	}
	decompose(1)
}

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 {
			return 0
		}
		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) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math/bits"
	"os"
)

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()
	clim := int('t'-'a') + 1

	n := io.NextInt()
	g := make([][]int, n+1)
	for i := 0; i < n-1; i++ {
		u, v := io.NextInt(), io.NextInt()
		g[u] = append(g[u], v)
		g[v] = append(g[v], u)
	}
	a := make([]int, n+1)
	for i, c := range io.Next() {
		a[i+1] = 1 << (int(c) - 'a')
	}

	good := []int{0}
	for i := 0; i < clim; i++ {
		good = append(good, 1<<i)
	}
	upto, cnts := make([]int, n+1), make([]int, 1<<clim)
	ans := make([]int64, n+1)

	centroidDecompose(g, func(cen int, off []bool) {
		var upd func(u, p, d int)
		upd = func(u, p, d int) {
			upto[u] = upto[p] ^ a[u]
			cnts[upto[u]] += d
			for _, v := range g[u] {
				if v != p && !off[v] {
					upd(v, u, d)
				}
			}
		}

		var cenCnt int64
		var get func(u, p int) int64
		get = func(u, p int) int64 {
			var cnt int64
			for _, x := range good {
				cnt += int64(cnts[upto[u]^a[cen]^x])
			}
			if bits.OnesCount(uint(upto[u])) <= 1 {
				cenCnt++
			}
			for _, v := range g[u] {
				if v != p && !off[v] {
					cnt += get(v, u)
				}
			}
			ans[u] += int64(cnt)
			return cnt
		}

		var cnt int64
		upd(cen, 0, +1)
		for _, v := range g[cen] {
			if !off[v] {
				upd(v, cen, -1)
				cnt += get(v, cen)
				upd(v, cen, +1)
			}
		}
		upd(cen, 0, -1)
		ans[cen] += (cnt-cenCnt)/2 + cenCnt + 1
	})

	for _, x := range ans[1:] {
		fmt.Fprint(io, x, " ")
	}
	fmt.Fprintln(io)
}

func centroidDecompose(g [][]int, f func(int, []bool)) {
	sz, off := make([]int, len(g)), make([]bool, len(g))

	var calcSz func(u, p int)
	calcSz = func(u, p int) {
		sz[u] = 1
		for _, v := range g[u] {
			if v != p && !off[v] {
				calcSz(v, u)
				sz[u] += sz[v]
			}
		}
	}

	var getCentroid func(u, p, cur int) int
	getCentroid = func(u, p, cur int) int {
		for _, v := range g[u] {
			if v != p && !off[v] {
				if sz[v]*2 > cur {
					return getCentroid(v, u, cur)
				}
			}
		}
		return u
	}

	var decompose func(int)
	decompose = func(u int) {
		calcSz(u, u)
		cen := getCentroid(u, u, sz[u])
		f(cen, off)
		off[cen] = true
		for _, v := range g[cen] {
			if !off[v] {
				decompose(v)
			}
		}
	}
	decompose(1)
}

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 {
	if n, _ := f.Read(f.c[:]); n != 0 {
		return f.c[0]
	}
	return 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) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}


Nezzar's favorite digit among $$$1,\ldots,9$$$ is $$$d$$$. He calls a positive integer lucky if $$$d$$$ occurs at least once in its decimal representation. Given $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$, for each $$$1 \le i \le q$$$ Nezzar would like to know if $$$a_i$$$ can be equal to a sum of several (one or more) lucky numbers.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 9$$$) — the number of test cases. The first line of each test case contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q \le 10^4$$$, $$$1 \le d \le 9$$$). The second line of each test case contains $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$ ($$$1 \le a_i \le 10^9$$$).

For each integer in each test case, print "YES" in a single line if $$$a_i$$$ can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower).

YES
NO
YES
YES
YES
NO
YES
YES
YES
YES
YES
YES
NO

NoteIn the first test case, $$$24 = 17 + 7$$$, $$$27$$$ itself is a lucky number, $$$25$$$ cannot be equal to a sum of lucky numbers.

package main

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

func calc(q int64, item int64) bool {
	if item%q == 0 {
		return true
	}
	if item < 10*q {
		for p := int64(1); p < q; p++ {
			temp := item
			for temp > 0 {
				temp -= q + p*10
				if temp >= 0 && temp%q == 0 {
					return true
				}
			}
		}

		return false
	}

	return true
}

func main() {
	const maxCapacity = 1024 * 1024
	buf := make([]byte, maxCapacity)
	input := bufio.NewScanner(os.Stdin)
	input.Buffer(buf, maxCapacity)
	input.Scan()
	t, _ := strconv.Atoi(input.Text())
	results := make([]bool, 0)
	for i := 0; i < t; i++ {
		input.Scan()
		var q, d int64
		fmt.Sscanf(input.Text(), "%d %d\n", &q, &d)
		input.Scan()
		str := strings.Split(input.Text(), " ")
		for j := int64(0); j < q; j++ {
			item, _ := strconv.Atoi(str[j])
			results = append(results, calc(d, int64(item)))
		}
	}

	for _, result := range results {
		if result {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

func main() {
	//goland:noinspection GoUnhandledErrorResult
	defer writer.Flush()

	var t int
	scanf("%d\n", &t)

	var bl strings.Builder

	for i := 0; i < t; i++ {
		var q, d int
		scanf("%d %d\n", &q, &d)

		luckySet := make(map[int]bool)
		for j := 0; j < 10; j++ {
			luckySet[d+j*10] = true
		}

		numToIsLuckySum := make(map[int]bool)

		for j := 0; j < q; j++ {
			var num int
			scanf("%d", &num)

			if num >= 10*d {
				//goland:noinspection GoUnhandledErrorResult
				fmt.Fprintf(&bl, "YES\n")
			} else {
				isLuckySum, found := numToIsLuckySum[num]
                                if !found {
                                  isLuckySum = isSumOfLuckyNumbers(num, luckySet)
                                }

				if isLuckySum {
					numToIsLuckySum[num] = true
					//goland:noinspection GoUnhandledErrorResult
					fmt.Fprintf(&bl, "YES\n")
				} else {
					numToIsLuckySum[num] = false
					//goland:noinspection GoUnhandledErrorResult
					fmt.Fprintf(&bl, "NO\n")
				}
			}
		}
		scanf("\n")
	}

	printf(bl.String())
}

func isSumOfLuckyNumbers(num int, luckySet map[int]bool) bool {
	if _, found := luckySet[num]; found {
		return true
	}

	for n := range luckySet {
		diff := num - n
		if diff > 0 && isSumOfLuckyNumbers(diff, luckySet) {
			return true
		}
	}

	return false
}

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

func printf(f string, a ...interface{}) {
	if _, err := fmt.Fprintf(writer, f, a...); err != nil {
		panic(err)
	}
}
func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

//goland:noinspection GoUnusedFunction
func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

package main

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

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
	t   int
	q   int
	d   int
	a   int
)

func main() {

	defer out.Flush()

	fmt.Fscan(in, &t)

	for ; t > 0; t-- {

		fmt.Fscan(in, &q, &d)

		for ; q > 0; q-- {

			fmt.Fscan(in, &a)

			fmt.Fprintln(out, solve2(a, d))

		}

	}

}

func solve2(a int, d int) string {

	if d == 1 || a >= 10*d {
		return "YES"
	}

	for a > 0 {

		if a%d == 0 {
			return "YES"
		}

		a -= 10

	}

	return "NO"

}

func solve(a int, d int) string {

	n := 1

	for d*n <= a {

		if (a-d*n)%10 == 0 {
			return "YES"
		}

		n++

	}

	return "NO"

}

package main

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

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

func scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		log.Fatal(err)
	}
}

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		log.Fatal(err)
	}
}

func printf(f string, a ...interface{}) {
	if _, err := fmt.Fprintf(writer, f, a...); err != nil {
		log.Fatal(err)
	}
}

func isLucky(v int, d int) bool {
	for v > 0 {
		if v % 10 == d {
			return true
		}
		v /= 10
	}
	return false
}

func solve() {
	var q, d int
	scan(&q, &d)
	var dp = make([]bool, MAXV)
	dp[0] = true
	for v := 0; v < MAXV; v++ {
		if dp[v] {
			continue
		}
		for vv := 1; vv <= v; vv++ {
			if isLucky(vv, d) && dp[v - vv] {
				dp[v] = true
				break
			}
		}
	}
	for i := 0; i < q; i++ {
		var x int
		scan(&x)
		if x >= 10 * d || dp[x] {
			printf("YES\n")
		} else {
			printf("NO\n")
		}
	}
}

func main() {
	defer writer.Flush()

	testCases := 0
	scan(&testCases)
	for ; testCases > 0; {
		testCases -= 1
		solve()
	}
}

package main

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

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

	var t, q, d, a int
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
		fmt.Fscan(in, &q, &d)
	Loop:
		for i := 0; i < q; i++ {
			fmt.Fscan(in, &a)
			if a >= 11*d {
				fmt.Println("YES")
				continue Loop
			}
			if a/10 == d || a%10 == d {
				fmt.Println("YES")
				continue Loop
			}
			for ; a > 0; a -= 10 {
				if a%d == 0 {
					fmt.Println("YES")
					continue Loop
				}
			}
			fmt.Println("NO")
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)
var (
    input = bufio.NewReader(os.Stdin)
    output = bufio.NewWriter(os.Stdout)
)

func assert(test bool) {
    if !test {panic("assertion!")}
}

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)
func main() {
    var t int
	fmt.Fscan(input, &t)
    for t > 0 {
        t--
        solve()
    }
    output.Flush()
}

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

func ok(v, d int) bool {
    if v >= 10*d {return true}
    if v <= 0 { return false }
    if v % 10 == d { return true }
    return ok((v - d), d)
}

func solve() {
    var (
        q, d int
    )
    fmt.Fscan(input, &q, &d)
    a := make([]int, q)
    for i := 0; i < len(a); i++ {
        fmt.Fscan(input, &a[i])
    }
    for _, v := range a {
        if ok(v, d) {
            fmt.Fprintln(output, "Yes")
        } else {
            fmt.Fprintln(output, "No")
        }
    }
}

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, d := readTwoNums(reader)
		A := readNNums(reader, n)
		res := solve(d, A)
		for i := 0; i < n; i++ {
			if res[i] {
				buf.WriteString("YES\n")
			} else {
				buf.WriteString("NO\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(d int, A []int) []bool {
	n := len(A)

	res := make([]bool, n)
	for i := 0; i < n; i++ {
		res[i] = check(A[i], d)
	}

	return res
}

func check(num, d int) bool {
	x, y := num/d, num%d
	if y == 0 {
		return true
	}
	if x >= 10 {
		return true
	}

	// a * d + y = 10 + d
	// x < 10
	for i := 1; i <= x; i++ {
		tmp := i*d + y
		for tmp > 0 {
			r := tmp % 10
			if r == d {
				return true
			}
			tmp /= 10
		}
	}
	return false
}

package main

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

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

func scan(a ...interface{}) (n int, err error)             { return fmt.Fscan(in, a...) }
func scanf(f string, a ...interface{}) (n int, err error)  { return fmt.Fscanf(in, f, a...) }
func printf(f string, a ...interface{}) (n int, err error) { return fmt.Fprintf(out, f, a...) }

//https://codeforces.com/problemset/problem/1478/B
// dp

func main() {
	defer out.Flush()

	var t, n, d, a int
	scanf("%d\n", &t)
	for i := 0; i < t; i++ {
		scanf("%d %d\n", &n, &d)
		dp := make([]bool, d*10)
		dp[0] = true
		for i := 0; i < len(dp); i++ {
			for j := 0; j < d && i-j*10 >= d; j++ {
				dp[i] = dp[i] || dp[i-j*10-d]
			}
		}
		for j := 0; j < n; j++ {
			scan(&a)
			if j == n-1 {
				scanf("\n")
			}
			if a >= d*10 || dp[a] {
				printf("YES\n")
			} else {
				printf("NO\n")
			}
		}
	}
}

package main

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

func main(){
	var t, q, d int;
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &t)
	for (t > 0){
		t--
		fmt.Fscan(in, &q, &d)
		m := make([]int, d*10)
		for i:=0; i<d; i++{
			m[i*10+d] = 1
		}

		for i:=1; i<d*10; i++{
			if m[i] > 0{
				for j:=0; j<d; j++{
					t := j*10+d
					cur := i+t
					if cur < d*10{
						m[cur] = 1
					}
				}
			}
		}

		var x int
		for i:=0; i<q; i++{
			fmt.Fscan(in, &x)
			if x/d >= 10 {
				fmt.Println("YES")
			}else if m[x] > 0{
				fmt.Println("YES")
			}else{
				fmt.Println("NO")
			}
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	// . "testgo/helpers"
)

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

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

func main() {
	t := 1
	scan(&t)

	for T := 0; T < t; T++ {
		q, d := 0, 0
		scan(&q)
		scan(&d)

		a := make([]int, q)
		for i := range a {
			scan(&a[i])
		}

		solve(a, d)
	}

	writer.Flush()
}

func solve(q []int, d int) {
	check := func(x int) int {
		for x > 0 {
			if x%10 == d {
				return 1
			}
			x /= 10
		}
		return 0
	}

	dp := [100]int{1}
	for s := range dp {
		dp[s] = check(s)
		for x := 1; x < s; x++ {
			dp[s] |= dp[x] & dp[s-x]
		}
	}

	for i := range q {
		r := "NO"
		if q[i] >= 10*d || dp[q[i]] == 1 {
			r = "YES"
		}
		printf("%s\n", r)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var T, q, d, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &q, &d)
		f := make([]bool, d*10)
		f[0] = true
		for i := range f {
			for j := 0; j < d && 10*j+d <= i; j++ {
				f[i] = f[i] || f[i-10*j-d]
			}
		}
		for ; q > 0; q-- {
			Fscan(in, &v)
			if v >= d*10 || f[v] {
				Fprintln(out, "YES")
			} else {
				Fprintln(out, "NO")
			}
		}
	}
}

package main

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

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

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}
}

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

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {
		var q int
		var d int
		fmt.Fscan(input, &q)
		fmt.Fscan(input, &d)
		var m int64
		for i := 1; i < q+1; i++ {
			fmt.Fscan(input, &m)
			if d == 1 {
				fmt.Println("YES")
			}
			if d == 2 {
				if m%2 == 0 {
					fmt.Println("YES")
				} else {
					if m >= 21 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
			}
			if d == 3 {
				if m%3 == 0 {
					fmt.Println("YES")
				}
				if m%3 == 1 {
					if m >= 13 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
				if m%3 == 2 {
					if m >= 23 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
			}
			if d == 4 {
				if m%4 == 0 {
					fmt.Println("YES")

				}
				if m%4 == 1 {
					if m >= 41 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
				if m%4 == 2 {
					if m >= 14 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")

					}
				}
				if m%4 == 3 {
					if m >= 43 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
			}
			if d == 5 {
				if m%5 == 0 {
					fmt.Println("YES")
				} else {
					k := d % 5
					if m >= int64(50+k) {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}

				}

			}

			if d == 6 {
				if m%6 == 0 {
					fmt.Println("YES")
				}
				if m%2 == 1 {
					k := d % 6
					if m >= int64(60+k) {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
				if m%6 == 2 {
					if m >= 26 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
				if m%6 == 4 {
					if m >= 16 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
			}
			if d == 7 {
				if m%7 == 0 {
					fmt.Println("YES")
				}

				if m%7 == 1 {
					if m >= 57 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
				if m%7 == 2 {
					if m >= 37 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
				if m%7 == 3 {
					if m >= 17 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
				if m%7 == 4 {
					if m >= 67 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
				if m%7 == 5 {
					if m >= 47 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
				if m%7 == 6 {
					if m >= 27 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}

			}

			if d == 8 {
				if m%8 == 0 {
					fmt.Println("YES")
				}
				if m%2 == 1 {
					k := m % 8
					if m >= int64(80+k) {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")

					}
				}
				if m%8 == 2 {
					if m >= 18 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
				if m%8 == 4 {
					if m >= 28 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
				if m%8 == 6 {
					if m >= 38 {
						fmt.Println("YES")
					} else {
						fmt.Println("NO")
					}
				}
			}

			if d == 9 {
				if m%9 == 0 {
					fmt.Println("YES")
				} else {
					k := m % 9
					if m >= int64(k*10+9) {
						fmt.Println("YES")

					} else {
						fmt.Println("NO")

					}
				}

			}
		}
	}
}

package main

import (
	"fmt"
)

func calc(q int64, item int64) bool {
	if item%q == 0 {
		return true
	}
	if item < 10*q {
		for p := int64(1); p < q; p++ {
			temp := item
			for temp > 0 {
				temp -= q + p*10
				if temp >= 0 && temp%q == 0 {
					return true
				}
			}
		}

		return false
	}

	return true
}

func main() {
	var t int64
	fmt.Scanf("%d%c", &t)
	results := make([]bool, 0)
	for i := int64(0); i < t; i++ {
		var q, d int64
		fmt.Scanf("%d %d%c", &q, &d)
		for j := int64(0); j < q; j++ {
			var item int64
			fmt.Scanf("%d%c", &item)
			results = append(results, calc(d, item))
		}
	}

	for _, result := range results {
		if result {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

import (
	"fmt"
)

func calc(q int64, item int64) bool {
	if item%q == 0 {
		return true
	}
	if item < 10*q {
		for p := int64(1); p < q; p++ {
			temp := item
			for temp > 0 {
				temp -= q + p*10
				if temp >= 0 && temp%q == 0 {
					return true
				}
			}
		}

		return false
	}

	return true
}

func main() {
	var t int64
	fmt.Scanf("%d\n", &t)
	results := make([]bool, 0)
	for i := int64(0); i < t; i++ {
		var q, d int64
		fmt.Scanf("%d %d\n", &q, &d)
		for j := int64(0); j < q; j++ {
			var item int64
			fmt.Scanf("%d%c", &item)
			results = append(results, calc(d, item))
		}
	}

	for _, result := range results {
		if result {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

import (
	"fmt"
)

func calc(q int64, item int64) bool {
	if item%q == 0 {
		return true
	}
	if item < 10*q {
		for p := int64(1); p < q; p++ {
			temp := item
			for temp > 0 {
				temp -= q + p*10
				if temp >= 0 && temp%q == 0 {
					return true
				}
			}
		}

		return false
	}

	return true
}

func main() {
	var t int64
	fmt.Scanf("%d\n", &t)
	results := make([]bool, 0)
	for i := int64(0); i < t+1; i++ {
		var q, d int64
		fmt.Scanf("%d %d\n", &q, &d)
		for j := int64(0); j < q; j++ {
			var item int64
			fmt.Scanf("%d", &item)
			results = append(results, calc(d, item))
		}
	}

	for _, result := range results {
		if result {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

import (
	"fmt"
)

func calc(q int64, item int64) bool {
	if item%q == 0 {
		return true
	}
	if item < 10*q {
		for p := int64(1); p < q; p++ {
			temp := item
			for temp > 0 {
				temp -= q + p*10
				if temp >= 0 && temp%q == 0 {
					return true
				}
			}
		}

		return false
	}

	return true
}

func main() {
	var t int64
	fmt.Scanf("%d\n", &t)
	results := make([]bool, 0)
	for i := int64(0); i < t; i++ {
		var q, d int64
		fmt.Scanf("%d %d\n", &q, &d)
		for j := int64(0); j < q; j++ {
			var item int64
			fmt.Scanf("%d", &item)
			results = append(results, calc(d, item))
		}
	}

	fmt.Println(results)

	for _, result := range results {
		if result {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

import (
	"fmt"
)

func calc(q int64, item int64) bool {
	if item%q == 0 {
		return true
	}
	if item < 10*q {
		for p := int64(1); p < q; p++ {
			temp := item
			for temp > 0 {
				temp -= q + p*10
				if temp >= 0 && temp%q == 0 {
					return true
				}
			}
		}

		return false
	}

	return true
}

func main() {
	var t int64
	fmt.Scanf("%d\n", &t)
	results := make([]bool, 0)
	for i := int64(0); i < t; i++ {
		var q, d int64
		fmt.Scanf("%d %d\n", &q, &d)
		for j := int64(0); j < q; j++ {
			var item int64
			fmt.Scanf("%d", &item)
			results = append(results, calc(d, item))
		}
	}

	fmt.Println(t)

	for _, result := range results {
		if result {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

import (
	"fmt"
)

func calc(q int64, item int64) bool {
	if item%q == 0 {
		return true
	}
	if item < 10*q {
		for p := int64(1); p < q; p++ {
			temp := item
			for temp > 0 {
				temp -= q + p*10
				if temp >= 0 && temp%q == 0 {
					return true
				}
			}
		}

		return false
	}

	return true
}

func main() {
	var t int64
	fmt.Scanf("%d\n", &t)
	results := make([]bool, 0)
	for i := int64(0); i < t; i++ {
		var q, d int64
		fmt.Scanf("%d %d\n", &q, &d)
		for j := int64(0); j < q; j++ {
			var item int64
			fmt.Scanf("%d", &item)
			results = append(results, calc(d, item))
		}
	}

	for _, result := range results {
		if result {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
	t   int
	q   int
	d   int
	a   int
)

func main() {

	defer out.Flush()

	fmt.Fscan(in, &t)

	for ; t > 0; t-- {

		fmt.Fscan(in, &q, &d)

		for ; q > 0; q-- {

			fmt.Fscan(in, &a)

			fmt.Fprintln(out, solve2(a, d))

		}

	}

}

func solve2(a int, d int) string {

	for a > 0 {

		if a%d == 0 {
			return "YES"
		}

		a -= 10

	}

	return "NO"

}

func solve(a int, d int) string {

	n := 1

	for d*n <= a {

		if (a-d*n)%10 == 0 {
			return "YES"
		}

		n++

	}

	return "NO"

}

package main

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

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
	t   int
	q   int
	d   int
	a   int
)

func main() {

	defer out.Flush()

	fmt.Fscan(in, &t)

	for ; t > 0; t-- {

		fmt.Fscan(in, &q, &d)

		for ; q > 0; q-- {

			fmt.Fscan(in, &a)

			fmt.Fprintln(out, solve(a, d))

		}

	}

}

func solve(a int, d int) string {

	n := 1

	for d*n <= a {

		if (a-d*n)%10 == 0 {
			return "YES"
		}

		n++

	}

	return "NO"

}

package main

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

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

	var t, q, d, a int
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
		fmt.Fscan(in, &q, &d)
	Loop:
		for i := 0; i < q; i++ {
			fmt.Fscan(in, &a)
			if a >= 11*d {
				fmt.Println("YES")
				continue
			}
			for ; a > 0; a -= 10 {
				if a%d == 0 {
					fmt.Println("YES")
					continue Loop
				}
			}
			fmt.Println("NO")
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)
var (
    input = bufio.NewReader(os.Stdin)
    output = bufio.NewWriter(os.Stdout)
)

func assert(test bool) {
    if !test {panic("assertion!")}
}

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)
func main() {
    var t int
	fmt.Fscan(input, &t)
    for t > 0 {
        t--
        solve()
    }
    output.Flush()
}

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

func ok(v, d int) bool {
    if v <= 0 { return false }
    if v % 10 == d { return true }
    return ok(v - d, d)
}

func solve() {
    var (
        q, d int
    )
    fmt.Fscan(input, &q, &d)
    a := make([]int, q)
    for i := 0; i < len(a); i++ {
        fmt.Fscan(input, &a[i])
    }
    for _, v := range a {
        if ok(v, d) {
            fmt.Fprintln(output, "Yes")
        } else {
            fmt.Fprintln(output, "No")
        }
    }
}


The Little Elephant loves sortings.He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1 ≤ l ≤ r ≤ n) and increase ai by 1 for all i such that l ≤ i ≤ r.Help the Little Elephant find the minimum number of moves he needs to convert array a to an arbitrary array sorted in the non-decreasing order. Array a, consisting of n elements, is sorted in the non-decreasing order if for any i (1 ≤ i < n) ai ≤ ai + 1 holds.

The first line contains a single integer n (1 ≤ n ≤ 105) — the size of array a. The next line contains n integers, separated by single spaces — array a (1 ≤ ai ≤ 109). The array elements are listed in the line in the order of their index's increasing.

In a single line print a single integer — the answer to the problem. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the array is already sorted in the non-decreasing order, so the answer is 0.In the second sample you need to perform two operations: first increase numbers from second to third (after that the array will be: [3, 3, 2]), and second increase only the last element (the array will be: [3, 3, 3]).In the third sample you should make at least 6 steps. The possible sequence of the operations is: (2; 3), (2; 3), (2; 3), (3; 3), (3; 3), (3; 3). After that the array converts to [7, 7, 7, 47].

package main

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

func scanInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	x, _ := strconv.Atoi(scanner.Text())
	return x
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	n := scanInt(scanner)
	count := int64(0)
	prev := scanInt(scanner)
	for i := 1; i < n; i++ {
		curr := scanInt(scanner)
		if curr < prev {
			count += int64(prev-curr)
		}
		prev = curr
	}
	writer.WriteString(fmt.Sprintf("%d\n", count))
}

package main

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

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

	n := io.NextInt()
	A := io.NextInts(n)

	R := make([]int, n)

	mx := 0
	prv := 0
	ans := int64(0)
	for i := 0; i < n; i++ {
		mx = max(mx, A[i])
		R[i] = mx
		d := R[i] - A[i]
		// io.Println(A[i], R[i])
		// io.Println(d, prv)
		if prv < d {
			ans += int64(d - prv)
		}
		prv = d
	}
	io.Println(ans)
}

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

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) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, f.c[0])
	}
	return string(s)
}

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

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

func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}

func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}

//205B
package main
import (
	"fmt"
	"os"
	"bufio"
	"strconv"
)

func main() {
	var nn, aa, n, x int64
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	r.Scan()
	nn, _ = strconv.ParseInt(r.Text(), 0, 64)
	r.Scan()
	n, _ = strconv.ParseInt(r.Text(), 0, 64)
	x=0
	for i:=1; int64(i)<nn; i++ {
		r.Scan()
		aa, _ = strconv.ParseInt(r.Text(), 0, 64)
		if aa<n {
			x=x+(n-aa)
		}
		n=aa
	}
	fmt.Println(x)
}

// 205B
package main

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

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

func main() {
	var a, b, i, k, n int64
	in := bufio.NewReader(os.Stdin)
	fmt.Scan(&n)
	for i = 0; i < n; i++ {
		fmt.Fscan(in, &k)
		b += max(0, a-k)
		a = k
	}
	fmt.Print(b)
}

package main

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

func scanInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	x, _ := strconv.Atoi(scanner.Text())
	return x
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	n := scanInt(scanner)
	count := 0
	prev := scanInt(scanner)
	for i := 1; i < n; i++ {
		curr := scanInt(scanner)
		if curr < prev {
			count += prev-curr
		}
		prev = curr
	}
	writer.WriteString(fmt.Sprintf("%d\n", count))
}

package main

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

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

	n := io.NextInt()
	A := io.NextInts(n)

	R := make([]int, n)

	mx := 0
	prv := 0
	ans := 0
	for i := 0; i < n; i++ {
		mx = max(mx, A[i])
		R[i] = mx
		d := R[i] - A[i]
		// io.Println(A[i], R[i])
		// io.Println(d, prv)
		if prv < d {
			ans += d - prv
		}
		prv = d
	}
	io.Println(ans)
}

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

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) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, f.c[0])
	}
	return string(s)
}

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

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

func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}

func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}

//192B
package main
import (
	"fmt"
	"os"
	"bufio"
	"strconv"
)

func main() {
	var nn, aa, n, x int64
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	r.Scan()
	nn, _ = strconv.ParseInt(r.Text(), 0, 64)
	r.Scan()
	n, _ = strconv.ParseInt(r.Text(), 0, 64)
	x=0
	for i:=1; int64(i)<nn; i++ {
		r.Scan()
		aa, _ = strconv.ParseInt(r.Text(), 0, 64)
		if aa<n {
			x=x+n-aa
			n=aa
		}
	}
	fmt.Println(x)
}