Graph constructive problems are back! This time the graph you are asked to build should match the following properties.The graph is connected if and only if there exists a path between every pair of vertices.The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.The degree of a vertex is the number of edges incident to it.Given a sequence of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ construct a connected undirected graph of $$$n$$$ vertices such that:  the graph contains no self-loops and no multiple edges;  the degree $$$d_i$$$ of the $$$i$$$-th vertex doesn't exceed $$$a_i$$$ (i.e. $$$d_i \le a_i$$$);  the diameter of the graph is maximum possible. Output the resulting graph or report that no solution exists.

The first line contains a single integer $$$n$$$ ($$$3 \le n \le 500$$$) — the number of vertices in the graph. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n - 1$$$) — the upper limits to vertex degrees.

Print "NO" if no graph can be constructed under the given conditions. Otherwise print "YES" and the diameter of the resulting graph in the first line. The second line should contain a single integer $$$m$$$ — the number of edges in the resulting graph. The $$$i$$$-th of the next $$$m$$$ lines should contain two integers $$$v_i, u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$v_i \neq u_i$$$) — the description of the $$$i$$$-th edge. The graph should contain no multiple edges — for each pair $$$(x, y)$$$ you output, you should output no more pairs $$$(x, y)$$$ or $$$(y, x)$$$.

package main

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

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

	var n, d int
	Fscan(in, &n)
	d1 := []int{}
	d2 := [][2]int{}
	for i := 1; i <= n; i++ {
		Fscan(in, &d)
		if d == 1 {
			d1 = append(d1, i)
		} else {
			d2 = append(d2, [2]int{i, d})
		}
	}
	for len(d1) < 2 {
		d1 = append(d1, d2[0][0])
		d2 = d2[1:]
	}
	if len(d2) == 0 {
		Fprint(out, "NO")
		return
	}
	ans := make([][2]int, 0, n-1)
	ans = append(ans,
		[2]int{d1[0], d2[0][0]},
		[2]int{d1[1], d2[len(d2)-1][0]},
	)
	for i := 1; i < len(d2); i++ {
		ans = append(ans, [2]int{d2[i-1][0], d2[i][0]})
	}
o:
	for _, v := range d1[2:] {
		for i, p := range d2 {
			if p[1] > 2 {
				ans = append(ans, [2]int{v, p[0]})
				d2[i][1]--
				continue o
			}
		}
		Fprintln(out, "NO")
		return
	}
	Fprintln(out, "YES", len(d2)+1)
	Fprintln(out, n-1)
	for _, v := range ans {
		Fprintln(out, v[0], v[1])
	}
}

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

package main

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

type Cin struct {
	scanner *bufio.Scanner
}

func (c *Cin) NextInt() int {
	c.scanner.Scan()
	line := c.scanner.Text()
	return c.convertInt(line)
}

func (c *Cin) NextIntSlice() []int {
	c.scanner.Scan()
	line := strings.Split(c.scanner.Text(), " ")
	var ret []int
	for _, s := range line {
		ret = append(ret, c.convertInt(s))
	}
	return ret
}

func (c *Cin) NextTwoInt() (int, int) {
	line := c.NextIntSlice()
	return line[0], line[1]
}

func (c *Cin) convertInt(data string) int {
	i, _ := strconv.Atoi(data)
	return i
}

var cin = &Cin{
	scanner: bufio.NewScanner(os.Stdin),
}

type Node struct {
	idx int
	rst int
}
type NodeSlice []Node

func (n NodeSlice) Len() int           { return len(n) }
func (n NodeSlice) Less(i, j int) bool { return n[i].rst < n[j].rst }
func (n NodeSlice) Swap(i, j int)      { n[i], n[j] = n[j], n[i] }

func gao(n int, a []Node) {
	var vis [512]bool
	var edges [][2]int
	lastNode := -1
	diameter := 0
	for i := 0; i < n; i++ {
		if a[i].rst >= 2 {
			if lastNode != -1 {
				diameter++
				edges = append(edges, [2]int{a[lastNode].idx, a[i].idx})
				vis[a[lastNode].idx] = true
				vis[a[i].idx] = true
				a[i].rst -= 1
				a[lastNode].rst -= 1
			}
			lastNode = i
		}
	}
	var singleNodes, rest []int
	restEdges := 0
	for i := 0; i < n; i++ {
		if vis[a[i].idx] || a[i].rst > 1 {
			rest = append(rest, i)
			restEdges += a[i].rst
		} else {
			singleNodes = append(singleNodes, i)
		}
	}
	//fmt.Printf("a=%+v\nrestEdges=%v, singldeNodes=%v\n", a, restEdges, singleNodes)
	if restEdges < len(singleNodes) {
		fmt.Println("NO")
		return
	}
	if len(singleNodes) >= 2 {
		diameter += 2
	} else if len(singleNodes) == 1 {
		diameter++
	}
	fmt.Printf("YES %v\n", diameter)
	ptr := len(singleNodes) - 1
	if ptr >= 0 {
		edges = append(edges, [2]int{a[rest[len(rest)-1]].idx, a[singleNodes[ptr]].idx})
		ptr--
		a[rest[len(rest)-1]].rst--
	}
	for _, node := range rest {
		if ptr < 0 {
			break
		}
		//fmt.Printf("edges=%+v, node=%v, singdleNodes=%+v, ptr=%v\n", edges, node, singleNodes, ptr)
		for a[node].rst > 0 && ptr >= 0 {
			edges = append(edges, [2]int{a[node].idx, a[singleNodes[ptr]].idx})
			a[node].rst--
			ptr--
		}
	}
	fmt.Printf("%v\n", len(edges))
	for _, e := range edges {
		fmt.Printf("%v %v\n", e[0]+1, e[1]+1)
	}
}

func main() {
	n := cin.NextInt()
	a := cin.NextIntSlice()
	var g NodeSlice
	for i, v := range a {
		g = append(g, Node{i, v})
	}
	sort.Sort(NodeSlice(g))
	for i := 0; i < n-2; i++ {
		if g[i].rst > 1 {
			g[i], g[n-2] = g[n-2], g[i]
		}
	}
	gao(n, g)
}

package main

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

type Cin struct {
	scanner *bufio.Scanner
}

func (c *Cin) NextInt() int {
	c.scanner.Scan()
	line := c.scanner.Text()
	return c.convertInt(line)
}

func (c *Cin) NextIntSlice() []int {
	c.scanner.Scan()
	line := strings.Split(c.scanner.Text(), " ")
	var ret []int
	for _, s := range line {
		ret = append(ret, c.convertInt(s))
	}
	return ret
}

func (c *Cin) NextTwoInt() (int, int) {
	line := c.NextIntSlice()
	return line[0], line[1]
}

func (c *Cin) convertInt(data string) int {
	i, _ := strconv.Atoi(data)
	return i
}

var cin = &Cin{
	scanner: bufio.NewScanner(os.Stdin),
}

func gao(n int, a []int) {
	var vis [512]bool
	var edges [][2]int
	lastNode := -1
	diameter := 0
	for i := 0; i < n; i++ {
		if a[i] >= 2 {
			if lastNode != -1 {
				diameter++
				edges = append(edges, [2]int{lastNode, i})
				vis[lastNode] = true
				vis[i] = true
				a[i] -= 1
				a[lastNode] -= 1
			}
			lastNode = i
		}
	}
	var singleNodes, rest []int
	restEdges := 0
	for i := 0; i < n; i++ {
		if vis[i] || a[i] > 1 {
			rest = append(rest, i)
			restEdges += a[i]
		} else {
			singleNodes = append(singleNodes, i)
		}
	}
	//fmt.Printf("restEdges=%v, singldeNodes=%v\n", restEdges, singleNodes)
	if restEdges < len(singleNodes) {
		fmt.Println("NO")
		return
	}
	if len(singleNodes) >= 2 {
		diameter += 2
	}
	fmt.Printf("YES %v\n", diameter)
	ptr := len(singleNodes) - 1
	for _, node := range rest {
		if ptr < 0 {
			break
		}
		//fmt.Printf("edges=%+v, node=%v, singdleNodes=%+v, ptr=%v\n", edges, node, singleNodes, ptr)
		for a[node] > 0 && ptr >= 0 {
			edges = append(edges, [2]int{node, singleNodes[ptr]})
			a[node]--
			ptr--
		}
	}
	fmt.Printf("%v\n", len(edges))
	for _, e := range edges {
		fmt.Printf("%v %v\n", e[0]+1, e[1]+1)
	}
}

func main() {
	n := cin.NextInt()
	a := cin.NextIntSlice()
	gao(n, a)
}

package main

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

type Cin struct {
	scanner *bufio.Scanner
}

func (c *Cin) NextInt() int {
	c.scanner.Scan()
	line := c.scanner.Text()
	return c.convertInt(line)
}

func (c *Cin) NextIntSlice() []int {
	c.scanner.Scan()
	line := strings.Split(c.scanner.Text(), " ")
	var ret []int
	for _, s := range line {
		ret = append(ret, c.convertInt(s))
	}
	return ret
}

func (c *Cin) NextTwoInt() (int, int) {
	line := c.NextIntSlice()
	return line[0], line[1]
}

func (c *Cin) convertInt(data string) int {
	i, _ := strconv.Atoi(data)
	return i
}

var cin = &Cin{
	scanner: bufio.NewScanner(os.Stdin),
}

type Node struct {
	idx int
	rst int
}
type NodeSlice []Node

func (n NodeSlice) Len() int           { return len(n) }
func (n NodeSlice) Less(i, j int) bool { return n[i].rst < n[j].rst }
func (n NodeSlice) Swap(i, j int)      { n[i], n[j] = n[j], n[i] }

func gao(n int, a []Node) {
	var vis [512]bool
	var edges [][2]int
	lastNode := -1
	diameter := 0
	for i := 0; i < n; i++ {
		if a[i].rst >= 2 {
			if lastNode != -1 {
				diameter++
				edges = append(edges, [2]int{lastNode, a[i].idx})
				vis[lastNode] = true
				vis[a[i].idx] = true
				a[i].rst -= 1
				a[lastNode].rst -= 1
			}
			lastNode = a[i].idx
		}
	}
	var singleNodes, rest []int
	restEdges := 0
	for i := 0; i < n; i++ {
		if vis[i] || a[i].rst > 1 {
			rest = append(rest, i)
			restEdges += a[i].rst
		} else {
			singleNodes = append(singleNodes, i)
		}
	}
	//fmt.Printf("a=%+v\nrestEdges=%v, singldeNodes=%v\n", a, restEdges, singleNodes)
	if restEdges < len(singleNodes) {
		fmt.Println("NO")
		return
	}
	if len(singleNodes) >= 2 {
		diameter += 2
	} else if len(singleNodes) == 1 {
		diameter++
	}
	fmt.Printf("YES %v\n", diameter)
	ptr := len(singleNodes) - 1
	if ptr >= 0 {
		edges = append(edges, [2]int{a[rest[len(rest)-1]].idx, singleNodes[ptr]})
		ptr--
		a[rest[len(rest)-1]].rst--
	}
	for _, node := range rest {
		if ptr < 0 {
			break
		}
		//fmt.Printf("edges=%+v, node=%v, singdleNodes=%+v, ptr=%v\n", edges, node, singleNodes, ptr)
		for a[node].rst > 0 && ptr >= 0 {
			edges = append(edges, [2]int{a[node].idx, singleNodes[ptr]})
			a[node].rst--
			ptr--
		}
	}
	fmt.Printf("%v\n", len(edges))
	for _, e := range edges {
		fmt.Printf("%v %v\n", e[0]+1, e[1]+1)
	}
}

func main() {
	n := cin.NextInt()
	a := cin.NextIntSlice()
	var g NodeSlice
	for i, v := range a {
		g = append(g, Node{i, v})
	}
	sort.Sort(NodeSlice(g))
	for i := 0; i < n-2; i++ {
		if g[i].rst > 1 {
			g[i], g[n-2] = g[n-2], g[i]
		}
	}
	gao(n, g)
}

package main

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

type Cin struct {
	scanner *bufio.Scanner
}

func (c *Cin) NextInt() int {
	c.scanner.Scan()
	line := c.scanner.Text()
	return c.convertInt(line)
}

func (c *Cin) NextIntSlice() []int {
	c.scanner.Scan()
	line := strings.Split(c.scanner.Text(), " ")
	var ret []int
	for _, s := range line {
		ret = append(ret, c.convertInt(s))
	}
	return ret
}

func (c *Cin) NextTwoInt() (int, int) {
	line := c.NextIntSlice()
	return line[0], line[1]
}

func (c *Cin) convertInt(data string) int {
	i, _ := strconv.Atoi(data)
	return i
}

var cin = &Cin{
	scanner: bufio.NewScanner(os.Stdin),
}

func gao(n int, a []int) {
	var vis [512]bool
	var edges [][2]int
	lastNode := -1
	diameter := 0
	for i := 0; i < n; i++ {
		if a[i] >= 2 {
			if lastNode != -1 {
				diameter++
				edges = append(edges, [2]int{lastNode, i})
				vis[lastNode] = true
				vis[i] = true
				a[i] -= 1
				a[lastNode] -= 1
			}
			lastNode = i
		}
	}
	var singleNodes, rest []int
	restEdges := 0
	for i := 0; i < n; i++ {
		if vis[i] || a[i] > 1 {
			rest = append(rest, i)
			restEdges += a[i]
		} else {
			singleNodes = append(singleNodes, i)
		}
	}
	//fmt.Printf("restEdges=%v, singldeNodes=%v\n", restEdges, singleNodes)
	if restEdges < len(singleNodes) {
		fmt.Println("NO")
		return
	}
	if len(edges) == 0 {
		if len(singleNodes) >= 2 {
			diameter = 2
		}
	} else if len(singleNodes) > 0 {
		diameter++
	}
	if len(rest) >= 2 {
		diameter++
	}
	fmt.Printf("YES %v\n", diameter)
	ptr := len(singleNodes) - 1
	for _, node := range rest {
		if ptr < 0 {
			break
		}
		//fmt.Printf("edges=%+v, node=%v, singdleNodes=%+v, ptr=%v\n", edges, node, singleNodes, ptr)
		for a[node] > 0 && ptr >= 0 {
			edges = append(edges, [2]int{node, singleNodes[ptr]})
			a[node]--
			ptr--
		}
	}
	fmt.Printf("%v\n", len(edges))
	for _, e := range edges {
		fmt.Printf("%v %v\n", e[0]+1, e[1]+1)
	}
}

func main() {
	n := cin.NextInt()
	a := cin.NextIntSlice()
	gao(n, a)
}

package main

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

type Cin struct {
	scanner *bufio.Scanner
}

func (c *Cin) NextInt() int {
	c.scanner.Scan()
	line := c.scanner.Text()
	return c.convertInt(line)
}

func (c *Cin) NextIntSlice() []int {
	c.scanner.Scan()
	line := strings.Split(c.scanner.Text(), " ")
	var ret []int
	for _, s := range line {
		ret = append(ret, c.convertInt(s))
	}
	return ret
}

func (c *Cin) NextTwoInt() (int, int) {
	line := c.NextIntSlice()
	return line[0], line[1]
}

func (c *Cin) convertInt(data string) int {
	i, _ := strconv.Atoi(data)
	return i
}

var cin = &Cin{
	scanner: bufio.NewScanner(os.Stdin),
}

func gao(n int, a []int) {
	var vis [512]bool
	var edges [][2]int
	lastNode := -1
	diameter := 0
	for i := 0; i < n; i++ {
		if a[i] >= 2 {
			if lastNode != -1 {
				diameter++
				edges = append(edges, [2]int{lastNode, i})
				vis[lastNode] = true
				vis[i] = true
				a[i] -= 1
				a[lastNode] -= 1
			}
			lastNode = i
		}
	}
	var singleNodes, rest []int
	restEdges := 0
	for i := 0; i < n; i++ {
		if vis[i] || a[i] > 1 {
			rest = append(rest, i)
			restEdges += a[i]
		} else {
			singleNodes = append(singleNodes, i)
		}
	}
	//fmt.Printf("restEdges=%v, singldeNodes=%v\n", restEdges, singleNodes)
	if restEdges < len(singleNodes) {
		fmt.Println("NO")
		return
	}
	if len(singleNodes) > 0 {
		diameter++
	}
	fmt.Printf("YES %v\n", diameter)
	ptr := len(singleNodes) - 1
	for _, node := range rest {
		if ptr < 0 {
			break
		}
		//fmt.Printf("edges=%+v, node=%v, singdleNodes=%+v, ptr=%v\n", edges, node, singleNodes, ptr)
		for a[node] > 0 && ptr >= 0 {
			edges = append(edges, [2]int{node, singleNodes[ptr]})
			a[node]--
			ptr--
		}
	}
	fmt.Printf("%v\n", len(edges))
	for _, e := range edges {
		fmt.Printf("%v %v\n", e[0]+1, e[1]+1)
	}
}

func main() {
	n := cin.NextInt()
	a := cin.NextIntSlice()
	gao(n, a)
}

package main

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

type Cin struct {
	scanner *bufio.Scanner
}

func (c *Cin) NextInt() int {
	c.scanner.Scan()
	line := c.scanner.Text()
	return c.convertInt(line)
}

func (c *Cin) NextIntSlice() []int {
	c.scanner.Scan()
	line := strings.Split(c.scanner.Text(), " ")
	var ret []int
	for _, s := range line {
		ret = append(ret, c.convertInt(s))
	}
	return ret
}

func (c *Cin) NextTwoInt() (int, int) {
	line := c.NextIntSlice()
	return line[0], line[1]
}

func (c *Cin) convertInt(data string) int {
	i, _ := strconv.Atoi(data)
	return i
}

var cin = &Cin{
	scanner: bufio.NewScanner(os.Stdin),
}

type Node struct {
	idx int
	rst int
}
type NodeSlice []Node

func (n NodeSlice) Len() int           { return len(n) }
func (n NodeSlice) Less(i, j int) bool { return n[i].rst < n[j].rst }
func (n NodeSlice) Swap(i, j int)      { n[i], n[j] = n[j], n[i] }

func gao(n int, a []Node) {
	var vis [512]bool
	var edges [][2]int
	lastNode := -1
	diameter := 0
	for i := 0; i < n; i++ {
		if a[i].rst >= 2 {
			if lastNode != -1 {
				diameter++
				edges = append(edges, [2]int{a[lastNode].idx, a[i].idx})
				vis[a[lastNode].idx] = true
				vis[a[i].idx] = true
				a[i].rst -= 1
				a[lastNode].rst -= 1
			}
			lastNode = i
		}
	}
	var singleNodes, rest []int
	restEdges := 0
	for i := 0; i < n; i++ {
		if vis[i] || a[i].rst > 1 {
			rest = append(rest, i)
			restEdges += a[i].rst
		} else {
			singleNodes = append(singleNodes, i)
		}
	}
	//fmt.Printf("a=%+v\nrestEdges=%v, singldeNodes=%v\n", a, restEdges, singleNodes)
	if restEdges < len(singleNodes) {
		fmt.Println("NO")
		return
	}
	if len(singleNodes) >= 2 {
		diameter += 2
	} else if len(singleNodes) == 1 {
		diameter++
	}
	fmt.Printf("YES %v\n", diameter)
	ptr := len(singleNodes) - 1
	if ptr >= 0 {
		edges = append(edges, [2]int{a[rest[len(rest)-1]].idx, a[singleNodes[ptr]].idx})
		ptr--
		a[rest[len(rest)-1]].rst--
	}
	for _, node := range rest {
		if ptr < 0 {
			break
		}
		//fmt.Printf("edges=%+v, node=%v, singdleNodes=%+v, ptr=%v\n", edges, node, singleNodes, ptr)
		for a[node].rst > 0 && ptr >= 0 {
			edges = append(edges, [2]int{a[node].idx, a[singleNodes[ptr]].idx})
			a[node].rst--
			ptr--
		}
	}
	fmt.Printf("%v\n", len(edges))
	for _, e := range edges {
		fmt.Printf("%v %v\n", e[0]+1, e[1]+1)
	}
}

func main() {
	n := cin.NextInt()
	a := cin.NextIntSlice()
	var g NodeSlice
	for i, v := range a {
		g = append(g, Node{i, v})
	}
	sort.Sort(NodeSlice(g))
	for i := 0; i < n-2; i++ {
		if g[i].rst > 1 {
			g[i], g[n-2] = g[n-2], g[i]
		}
	}
	gao(n, g)
}

package main

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

type Cin struct {
	scanner *bufio.Scanner
}

func (c *Cin) NextInt() int {
	c.scanner.Scan()
	line := c.scanner.Text()
	return c.convertInt(line)
}

func (c *Cin) NextIntSlice() []int {
	c.scanner.Scan()
	line := strings.Split(c.scanner.Text(), " ")
	var ret []int
	for _, s := range line {
		ret = append(ret, c.convertInt(s))
	}
	return ret
}

func (c *Cin) NextTwoInt() (int, int) {
	line := c.NextIntSlice()
	return line[0], line[1]
}

func (c *Cin) convertInt(data string) int {
	i, _ := strconv.Atoi(data)
	return i
}

var cin = &Cin{
	scanner: bufio.NewScanner(os.Stdin),
}

func gao(n int, a []int) {
	var vis [512]bool
	var edges [][2]int
	lastNode := -1
	diameter := 0
	for i := 0; i < n; i++ {
		if a[i] >= 2 {
			if lastNode != -1 {
				diameter++
				edges = append(edges, [2]int{lastNode, i})
				vis[lastNode] = true
				vis[i] = true
				a[i] -= 1
				a[lastNode] -= 1
			}
			lastNode = i
		}
	}
	var singleNodes, rest []int
	restEdges := 0
	for i := 0; i < n; i++ {
		if vis[i] || a[i] > 1 {
			rest = append(rest, i)
			restEdges += a[i]
		} else {
			singleNodes = append(singleNodes, i)
		}
	}
	//fmt.Printf("restEdges=%v, singldeNodes=%v\n", restEdges, singleNodes)
	if restEdges < len(singleNodes) {
		fmt.Println("NO")
		return
	}
	if len(edges) == 0 {
		if len(singleNodes) >= 2 {
			diameter = 2
		}
	} else if len(singleNodes) > 0 {
		diameter++
	}
	fmt.Printf("YES %v\n", diameter)
	ptr := len(singleNodes) - 1
	for _, node := range rest {
		if ptr < 0 {
			break
		}
		//fmt.Printf("edges=%+v, node=%v, singdleNodes=%+v, ptr=%v\n", edges, node, singleNodes, ptr)
		for a[node] > 0 && ptr >= 0 {
			edges = append(edges, [2]int{node, singleNodes[ptr]})
			a[node]--
			ptr--
		}
	}
	fmt.Printf("%v\n", len(edges))
	for _, e := range edges {
		fmt.Printf("%v %v\n", e[0]+1, e[1]+1)
	}
}

func main() {
	n := cin.NextInt()
	a := cin.NextIntSlice()
	gao(n, a)
}

package main

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

type Cin struct {
	scanner *bufio.Scanner
}

func (c *Cin) NextInt() int {
	c.scanner.Scan()
	line := c.scanner.Text()
	return c.convertInt(line)
}

func (c *Cin) NextIntSlice() []int {
	c.scanner.Scan()
	line := strings.Split(c.scanner.Text(), " ")
	var ret []int
	for _, s := range line {
		ret = append(ret, c.convertInt(s))
	}
	return ret
}

func (c *Cin) NextTwoInt() (int, int) {
	line := c.NextIntSlice()
	return line[0], line[1]
}

func (c *Cin) convertInt(data string) int {
	i, _ := strconv.Atoi(data)
	return i
}

var cin = &Cin{
	scanner: bufio.NewScanner(os.Stdin),
}

func gao(n int, a []int) {
	var vis [512]bool
	var edges [][2]int
	lastNode := -1
	diameter := 0
	for i := 0; i < n; i++ {
		if a[i] >= 2 {
			if lastNode != -1 {
				diameter++
				edges = append(edges, [2]int{lastNode, i})
				vis[lastNode] = true
				vis[i] = true
				a[i] -= 1
				a[lastNode] -= 1
			}
			lastNode = i
		}
	}
	var singleNodes, rest []int
	restEdges := 0
	for i := 0; i < n; i++ {
		if vis[i] || a[i] > 1 {
			rest = append(rest, i)
			restEdges += a[i]
		} else {
			singleNodes = append(singleNodes, i)
		}
	}
	//fmt.Printf("restEdges=%v, singldeNodes=%v\n", restEdges, singleNodes)
	if restEdges < len(singleNodes) {
		fmt.Println("NO")
		return
	}
	if len(singleNodes) >= 2 {
		diameter += 2
	}
	fmt.Printf("YES %v\n", diameter)
	ptr := len(singleNodes) - 1
	if ptr >= 0 {
		edges = append(edges, [2]int{rest[len(rest)-1], singleNodes[ptr]})
		ptr--
		a[rest[len(rest)-1]]--
	}
	for _, node := range rest {
		if ptr < 0 {
			break
		}
		//fmt.Printf("edges=%+v, node=%v, singdleNodes=%+v, ptr=%v\n", edges, node, singleNodes, ptr)
		for a[node] > 0 && ptr >= 0 {
			edges = append(edges, [2]int{node, singleNodes[ptr]})
			a[node]--
			ptr--
		}
	}
	fmt.Printf("%v\n", len(edges))
	for _, e := range edges {
		fmt.Printf("%v %v\n", e[0]+1, e[1]+1)
	}
}

func main() {
	n := cin.NextInt()
	a := cin.NextIntSlice()
	gao(n, a)
}


Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.

The first line contains two space-separated integers x1, y1 ( - 106 ≤ x1, y1 ≤ 106) — the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≤ x2, y2 ≤ 106) — the coordinates of the university you are studying at. The third line contains an integer n (1 ≤ n ≤ 300) — the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≤ ai, bi, ci ≤ 106; |ai| + |bi| > 0) — the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).

NotePictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors):

package main

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

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

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	x1, y1, x2, y2 := int64(nextInt()), int64(nextInt()), int64(nextInt()), int64(nextInt())
	n := nextInt()
	count := 0

	for ; n > 0; n-- {
		a, b, c := int64(nextInt()), int64(nextInt()), int64(nextInt())

		sign1 := a * x1 + b * y1 + c
		sign2 := a * x2 + b * y2 + c

		if (sign1 > 0 && sign2 < 0) || (sign1 < 0 && sign2 > 0) {
			count++
		}
	}

	println(count)
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

package main

import (
	"fmt"
)

type Line struct {
	a, b, c float64
}

type Point struct {
	x, y float64
}

func (line Line) Intersect(p1, p2 Point) bool {
	if line.b == 0 {
		var l float64 = float64(-1*line.c) / float64(line.a)
		return (p1.x < l && p2.x > l) || (p1.x > l && p2.x < l)
	} else {
		var y1, y2 float64
		y1 = (float64(-1*line.c) - float64(line.a*p1.x)) / float64(line.b)
		y2 = (float64(-1*line.c) - float64(line.a*p2.x)) / float64(line.b)
		return (p1.y > y1 && p2.y < y2) || (p1.y < y1 && p2.y > y2)
	}
}

var (
	n       int
	home    Point
	univ    Point
	streets []Line
	result  int
)

func in() {
	var x, y float64
	fmt.Scanf("%f %f\n", &x, &y)
	home = Point{x, y}
	fmt.Scanf("%f %f\n", &x, &y)
	univ = Point{x, y}

	fmt.Scanln(&n)
	streets = make([]Line, n)
	for i := 0; i < n; i++ {
		streets[i] = *new(Line)
		_, err := fmt.Scanf("%f %f %f\n", &streets[i].a, &streets[i].b, &streets[i].c)
		if err != nil {
			fmt.Println(err)
		}
	}

}

func out() {
	fmt.Println(result)
}

func run() {
	result = 0
	for _, street := range streets {
		if street.Intersect(home, univ) {
			result++
		}
	}
}

func main() {
	in()
	run()
	out()
}

package main

import (
	"fmt"
)

func main() {
	var x1, y1, x2, y2 int64
	var n int
	fmt.Scan(&x1, &y1, &x2, &y2, &n)
	step := 0
	for i := 0; i < n; i++ {
		var a, b, c int64
		fmt.Scan(&a, &b, &c)
		z1 := a*x1 + b*y1 + c
		z2 := a*x2 + b*y2 + c
		if z1 < 0 && z2 > 0 || z1 > 0 && z2 < 0 {
			step++
		}
	}
	fmt.Println(step)
}

package main

import (
	"fmt"
)

func main() {
	var x1, y1, x2, y2 int64
	var n int
	fmt.Scan(&x1, &y1, &x2, &y2, &n)
	step := 0
	for i := 0; i < n; i++ {
		var a, b, c int64
		fmt.Scan(&a, &b, &c)
		z1 := a*x1 + b*y1 + c
		z2 := a*x2 + b*y2 + c
		if z1*z2 < 0 {
			step++
		}
	}
	fmt.Println(step)
}


You have a bag which contains $$$n$$$ cards. There is a number written on each card; the number on $$$i$$$-th card is $$$a_i$$$.You are playing the following game. During each turn, you choose and remove a random card from the bag (all cards that are still left inside the bag are chosen equiprobably). Nothing else happens during the first turn — but during the next turns, after removing a card (let the number on it be $$$x$$$), you compare it with the card that was removed during the previous turn (let the number on it be $$$y$$$). Possible outcomes are:   if $$$x < y$$$, the game ends and you lose;  if $$$x = y$$$, the game ends and you win;  if $$$x > y$$$, the game continues. If there are no cards left in the bag, you lose. Cards are not returned into the bag after you remove them.You have to calculate the probability of winning in this game. It can be shown that it is in the form of $$$\frac{P}{Q}$$$ where $$$P$$$ and $$$Q$$$ are non-negative integers and $$$Q \neq 0$$$, $$$P \le Q$$$. Output the value of $$$P \cdot Q^{−1} ~(mod ~~ 998244353)$$$.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of cards in the bag. The second live contains $$$n$$$ integers $$$a_1, a_2, \dots a_n$$$ ($$$1 \le a_i \le n$$$) — the $$$i$$$-th integer is the number written on the $$$i$$$-th card.

Print one integer — the probability of winning in this game modulo $$$998244353$$$.

NoteIn the first test case the probability of winning is $$$\frac{1}{10}$$$.In the second test case the probability of winning is $$$1$$$.In the third test case the probability of winning is $$$0$$$.In the fourth test case the probability of winning is $$$\frac{1}{4}$$$.

package main

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

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

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

const (
	N int = 5e3+1
	MOD int64 = 998244353
)

var (
	n int
	a, nums [N]int
	fact, invf [N]int64
)

func inverse(x int64) (res int64) {
	res = 1
	for e:=MOD-2; e>0; e/=2 {
		if e%2 == 1 {
			res = res*x % MOD
		}
		x = x*x % MOD
	}
	return
}

func main() {
	// code GOes here

	fact[0] = 1
	invf[0] = 1
	for i:=1; i<N; i++ {
		fact[i] = int64(i)*fact[i-1] % MOD
		invf[i] = inverse(fact[i])
	}

	scan(&n)
	for i:=0; i<n; i++ {
		scan(&a[i])
	}
	sort.Ints(a[:n])

	inv := int64(1)
	pre := 0
	cnt := 1
	for i:=0; i<=n; i++ {
		if a[i] != pre {
			inv = inv * invf[cnt] % MOD
			nums[pre] = cnt
			cnt = 1
		} else {
			cnt++
		}
		pre = a[i]
	}

	ans := int64(0)
	gf := []int64 {1}
	for i:=1; i<=n; i++ {
		if nums[i] >= 2 {
			cur := int64(0)
			for j,k := range gf {
				l := n-(len(gf)-1-j)-2
				cur += fact[l] * k % MOD
			}
			cur = (cur%MOD) * int64(nums[i]*(nums[i]-1)) % MOD
			ans += cur * inv % MOD
		}
		if nums[i] > 0 {
			gf = append(gf, 0)
			for j:=len(gf)-1; j>=0; j-- {
				gf[j] = gf[j]*int64(nums[i])
				if j > 0 {
					gf[j] += gf[j-1]
				}
				gf[j] %= MOD
			}
		}
	}

	ans = (ans % MOD) * inverse(fact[n] * inv % MOD) % MOD
	print(ans, "\n")

	writer.Flush()
	return
}

package main

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

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

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

const (
	N int = 5e3+1
	MOD int64 = 998244353
)

var (
	n int
	a [N]int
	fact, invf [N]int64
)

func inverse(x int64) (res int64) {
	res = 1
	for e:=MOD-2; e>0; e/=2 {
		if e%2 == 1 {
			res = res*x % MOD
		}
		x = x*x % MOD
	}
	return
}

func mult(a []int64, b []int64) []int64 {
	c := []int64{}
	for i:=0; i<len(a)+len(b)-1; i++ {
		cur := int64(0)
		for j:=0; j<=i; j++ {
			if j<len(a) && i-j<len(b) {
				cur += a[j]*b[i-j] % MOD
			}
		}
		c = append(c, cur%MOD)
	}
	return c
}

func main() {
	// code GOes here

	fact[0] = 1
	invf[0] = 1
	for i:=1; i<N; i++ {
		fact[i] = int64(i)*fact[i-1] % MOD
		invf[i] = inverse(fact[i])
	}

	scan(&n)
	for i:=0; i<n; i++ {
		scan(&a[i])
	}
	sort.Ints(a[:n])

	inv := int64(1)
	pre := 0
	cnt := 1
	nums := make(map[int]int)
	for i:=0; i<=n; i++ {
		if a[i] != pre {
			inv = inv * invf[cnt] % MOD
			nums[pre] = cnt
			cnt = 1
		} else {
			cnt++
		}
		pre = a[i]
	}

	ans := int64(0)
	gf := []int64 {1}
	for i:=1; i<=n; i++ {
		if nums[i] >= 2 {
			cur := int64(0)
			for j,k := range gf {
				cur += (fact[n-j-2] * k % MOD) * inv % MOD
			}
			cur = (cur%MOD) * (int64(nums[i])*int64(nums[i]-1)%MOD) % MOD
			ans += cur
		}
		if nums[i] > 0 {
			gf = mult(gf, []int64 {int64(i), 1})
		}
	}

	ans = (ans % MOD) * inverse(fact[n] * inv % MOD) % MOD
	print(ans, "\n")

	writer.Flush()
	return
}

package main

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

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

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

const (
	N int = 5e3+1
	MOD int64 = 998244353
)

var (
	n int
	a, nums [N]int
	fact, invf [N]int64
)

func inverse(x int64) (res int64) {
	res = 1
	for e:=MOD-2; e>0; e/=2 {
		if e%2 == 1 {
			res = res*x % MOD
		}
		x = x*x % MOD
	}
	return
}

func main() {
	// code GOes here

	fact[0] = 1
	invf[0] = 1
	for i:=1; i<N; i++ {
		fact[i] = int64(i)*fact[i-1] % MOD
		invf[i] = inverse(fact[i])
	}

	scan(&n)
	for i:=0; i<n; i++ {
		scan(&a[i])
	}
	sort.Ints(a[:n])

	inv := int64(1)
	pre := 0
	cnt := 1
	for i:=0; i<=n; i++ {
		if a[i] != pre {
			inv = inv * invf[cnt] % MOD
			nums[pre] = cnt
			cnt = 1
		} else {
			cnt++
		}
		pre = a[i]
	}

	ans := int64(0)
	gf := []int64 {1}
	for i:=1; i<=n; i++ {
		if nums[i] >= 2 {
			cur := int64(0)
			for j,k := range gf {
				cur += (fact[n-j-2] * k % MOD) * inv % MOD
			}
			cur = (cur%MOD) * int64(nums[i]*(nums[i]-1)) % MOD
			ans += cur
		}
		if nums[i] > 0 {
			gf = append(gf, 0)
			for j:=len(gf)-1; j>=0; j-- {
				gf[j] = gf[j]*int64(nums[i]) % MOD
				if j > 0 {
					gf[j] += gf[j-1]
				}
			}
		}
	}

	ans = (ans % MOD) * inverse(fact[n] * inv % MOD) % MOD
	print(ans, "\n")

	writer.Flush()
	return
}

package main

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

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

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

const (
	N int = 5e3+1
	MOD int64 = 998244353
)

var (
	n int
	a, nums [N]int
	fact, invf [N]int64
)

func inverse(x int64) (res int64) {
	res = 1
	for e:=MOD-2; e>0; e/=2 {
		if e%2 == 1 {
			res = res*x % MOD
		}
		x = x*x % MOD
	}
	return
}

func main() {
	// code GOes here

	fact[0] = 1
	invf[0] = 1
	for i:=1; i<N; i++ {
		fact[i] = int64(i)*fact[i-1] % MOD
		invf[i] = inverse(fact[i])
	}

	scan(&n)
	for i:=0; i<n; i++ {
		scan(&a[i])
	}
	sort.Ints(a[:n])

	inv := int64(1)
	pre := 0
	cnt := 1
	for i:=0; i<=n; i++ {
		if a[i] != pre {
			inv = inv * invf[cnt] % MOD
			nums[pre] = cnt
			cnt = 1
		} else {
			cnt++
		}
		pre = a[i]
	}

	ans := int64(0)
	gf := []int64 {1}
	for i:=1; i<=n; i++ {
		if nums[i] >= 2 {
			cur := int64(0)
			for j,k := range gf {
				cur += fact[n-j-2] * k % MOD
			}
			cur = (cur%MOD) * int64(nums[i]*(nums[i]-1)) % MOD
			ans += cur * inv % MOD
		}
		if nums[i] > 0 {
			gf = append(gf, 0)
			for j:=len(gf)-1; j>=0; j-- {
				gf[j] = gf[j]*int64(nums[i])
				if j > 0 {
					gf[j] += gf[j-1]
				}
				gf[j] %= MOD
			}
		}
	}

	ans = (ans % MOD) * inverse(fact[n] * inv % MOD) % MOD
	print(ans, "\n")

	writer.Flush()
	return
}


You are given an integer $$$n$$$ and an integer $$$k$$$.In one step you can do one of the following moves:   decrease $$$n$$$ by $$$1$$$;  divide $$$n$$$ by $$$k$$$ if $$$n$$$ is divisible by $$$k$$$. For example, if $$$n = 27$$$ and $$$k = 3$$$ you can do the following steps: $$$27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.You are asked to calculate the minimum number of steps to reach $$$0$$$ from $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of queries. The only line of each query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^{18}$$$, $$$2 \le k \le 10^{18}$$$).

For each query print the minimum number of steps to reach $$$0$$$ from $$$n$$$ in single line.

NoteSteps for the first test case are: $$$59 \rightarrow 58 \rightarrow 57 \rightarrow 19 \rightarrow 18 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.In the second test case you have to divide $$$n$$$ by $$$k$$$ $$$18$$$ times and then decrease $$$n$$$ by $$$1$$$.

package main

import (
	"fmt"
)

func main() {
	var t int
	var n, k int64

	fmt.Scanf("%d\n", &t)

	for i := 0; i < t; i++ {
		fmt.Scanf("%d%d\n", &n, &k)
		var sol int64 = 0
		for n > 0 {
			if n%k == 0 {
				n /= k
				sol += 1
			} else {
				sol += n % k
				n -= n % k
			}
		}
		fmt.Println(sol)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scan(&t)
	for i:=0;i<t;i++ {
		var n,k int64
		fmt.Scan(&n,&k)
		var res int64
		res = 0
		for n>0 {
			res+=n%k
			n/=k
			res+=1
		}
		fmt.Println(res-1)
	}
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	for ; t > 0; t-- {
		var n, k, cnt int64
		fmt.Scan(&n, &k)
		for n > 0 {
			cnt += n%k + 1
			n /= k
		}
		fmt.Println(cnt - 1)
	}
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	for ; t > 0; t-- {
		var n, k, cnt int64
		fmt.Scan(&n, &k)
		for n > 0 {
			if n%k == 0 {
				cnt++
				n /= k
			} else {
				cnt += n % k
				n -= n % k
			}
		}
		fmt.Println(cnt)
	}
}

package main

import "fmt"

func main() {
	var t int
	_, _ = fmt.Scanf("%d\n", &t)
	for t > 0 {
		t--
		var n, k uint64
		_, _ = fmt.Scanf("%d%d\n", &n, &k)
		var cnt uint64 = 0
		for n > 0 {
			cnt += (n % k) + 1
			n /= k
		}
		fmt.Println(cnt - 1)
	}
}

package main

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

type inputReader struct {
    *bufio.Scanner
}

func initInput() *inputReader {
    input := inputReader{ bufio.NewScanner(os.Stdin) }
    input.Split(bufio.ScanWords)
    return &input
}

func (input *inputReader) readInt64() int64 {
    input.Scan()
    result, _ := strconv.ParseInt(input.Text(), 10, 64)
    return result
}

func main() {
    input := initInput()

    t := int(input.readInt64())
    for kase := 1; kase <= t; kase++ {
        n := input.readInt64()
        k := input.readInt64()

        ans := int64(0)
        for n > 0 {
            if n % k == 0 {
                ans++
                n /= k
            } else {
                ans += n % k
                n -= n % k
            }
        }

        fmt.Println(ans)
    }
}

package main

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

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

	var T, n, k int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k)
		ans := int64(-1)
		for n > 0 {
			ans += n%k + 1
			n /= k
		}
		Fprintln(out, ans)
	}
}

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := int64(0)
	fmt.Fscanf(in, "%d\n", &t)
	for tt := int64(0); tt < t; tt++ {
		n, k := int64(0), int64(0)
		fmt.Fscanf(in, "%d %d\n", &n, &k)
		ans := int64(0)
		for n != 0 {
			if n%k == 0 {
				n /= k
				ans++
			} else {
				ans += n % k
				n -= n % k
			}
		}
		fmt.Fprintf(out, "%d\n", ans)
	}
	return
}

package main

import (
	"fmt"
)

func main() {
	var t int // size of input
	var n, k int64
	fmt.Scan(&t)
	for t > 0 {
		var ctr int64
		fmt.Scan(&n, &k)
		for n >= k {
			r := n % k
			if r == 0 {
				n = n / k
				ctr++
			} else {
				n = n - r
				ctr += r
			}
		}
		ctr += n
		fmt.Println(ctr)
		t = t - 1
	}
}

// Author: sighduck
// URL: https://codeforces.com/contest/1175/problem/A

package main

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

func _Solve(n int64, k int64, acc int64) int64 {
	if n == 0 {
		return acc
	} else if k > n {
		return _Solve(0, k, acc+n)
	} else if n%k == 0 {
		return _Solve(n/k, k, acc+1)
	}
	return _Solve(n-n%k, k, acc+n%k)
}

func Solve(n int64, k int64) int64 {
	return _Solve(n, k, 0)
}

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

	var t int
	var n int64
	var k int64

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

package main

import (
	"fmt"
)

func main() {
	var t, n, k int

	fmt.Scanf("%d\n", &t)

	for i := 0; i < t; i++ {
		fmt.Scanf("%d%d\n", &n, &k)
		sol := 0
		for n > 0 {
			if n%k == 0 {
				n /= k
			} else {
				n -= 1
			}
			sol += 1
		}
		fmt.Println(sol)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	var n, k int64

	fmt.Scanf("%d\n", &t)

	for i := 0; i < t; i++ {
		fmt.Scanf("%d%d\n", &n, &k)
		var sol int64 = 0
		for n > 0 {
			if n%k == 0 {
				n /= k
				sol += 1
			} else {
				n -= n % k
				sol += n % k
			}
		}
		fmt.Println(sol)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t, n, k int

	fmt.Scanf("%d\n", &t)

	for i := 0; i < t; i++ {
		fmt.Scanf("%d %d\n", &n, &k)
		sol := 0
		for n > 0 {
			if n%k == 0 {
				n /= k
			} else {
				n -= 1
			}
			sol += 1
		}
		fmt.Println(sol)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scanf("%d",&t)
	for i:=0;i<t;i++ {
		var n,k int64
		fmt.Scanf("%d %d",&n,&k)
		var res int64
		res = 0
		for n>0 {
			res+=n%k
			n/=k
			res+=1
		}
		fmt.Println(res-1)
	}
}

package main

import "fmt"

func main() {
	var t int
	_, _ = fmt.Scanf("%d", &t)
	for t > 0 {
		t--
		var n, k uint64
		_, _ = fmt.Scanf("%d%d", &n, &k)
		cnt := 0
		for n > 0 {
			if n % k == 0 {
				n /= k
			} else {
				n--
			}
			cnt++
		}
		fmt.Println(cnt)
	}
}

package main

import (
    "fmt"
    "math"
)

func main() {
    var n,k float64
    var t int
    fmt.Scan(&t)
    for t > 0 {
        fmt.Scan(&n)
        fmt.Scan(&k)
        if n >= k {
            p := math.Floor(math.Log10(n) / math.Log10(k))
            r := int(n) % int(math.Pow(k,p))
            if r == 0 {
                r = 1
            }
            fmt.Println(int(p) + r)
        } else {
            fmt.Println(n)
        }
        t = t - 1
    }
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int // size of input
	var n, k int64
	fmt.Scan(&t)
	for t > 0 {
		fmt.Scan(&n, &k)
		if n >= k {
			p := math.Floor(math.Log10(float64(n)) / math.Log10(float64(k)))
			r := int(n) % int(math.Pow(float64(k), float64(p)))
			if r == 0 {
				r = 1
			}
			fmt.Println(p + float64(r))
		} else {
			fmt.Println(n)
		}
		t = t - 1
	}
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int // size of input
	var n, k int64
	fmt.Scan(&t)
	for t > 0 {
		fmt.Scan(&n, &k)
		if n >= k {
			p := int64(math.Log10(float64(n)) / math.Log10(float64(k)))
			r := int64(n) % int64(math.Pow(float64(k), float64(p)))
			if r == 0 {
				r = 1
			}
			fmt.Println(p + r)
		} else {
			fmt.Println(n)
		}
		t = t - 1
	}
}

package main

import (
    "fmt"
    "math"
)

func main() {
    var n,k float64
    var t int
    fmt.Scan(&t)
    for t > 0 {
        fmt.Scan(&n)
        fmt.Scan(&k)
        p := math.Floor(math.Log10(n) / math.Log10(k))
        r := int(n) % int(math.Pow(k,p))
        if r == 0 {
            r = 1
        }
        fmt.Println(int(p) + r)
        t = t - 1
    }
}


Lee is going to fashionably decorate his house for a party, using some regular convex polygons...Lee thinks a regular $$$n$$$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $$$OX$$$-axis and at least one of its edges is parallel to the $$$OY$$$-axis at the same time.Recall that a regular $$$n$$$-sided polygon is a convex polygon with $$$n$$$ vertices such that all the edges and angles are equal.Now he is shopping: the market has $$$t$$$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of polygons in the market.  Each of the next $$$t$$$ lines contains a single integer $$$n_i$$$ ($$$3 \le n_i \le 10^9$$$): it means that the $$$i$$$-th polygon is a regular $$$n_i$$$-sided polygon.

For each polygon, print YES if it's beautiful or NO otherwise (case insensitive).

NoteIn the example, there are $$$4$$$ polygons in the market. It's easy to see that an equilateral triangle (a regular $$$3$$$-sided polygon) is not beautiful, a square (a regular $$$4$$$-sided polygon) is beautiful and a regular $$$12$$$-sided polygon (is shown below) is beautiful as well.

package main

import (
  . "fmt"
)

var t int
func main() {
  Scan(&t)
  for tc := 0; tc < t; tc++ {
  	var n int
    Scan(&n)
    if n % 4 == 0 {
        Println("YES")
    } else {
        Println("NO")
    }
  }
}

package main

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

func main() {
	var t, n int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(in, &n)
		if n%4 == 0 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanLines)
	scanner.Scan()
	tc, _ := strconv.Atoi(scanner.Text())
	for tc > 0  {
		tc--
		scanner.Scan()
		n, _ := strconv.Atoi(scanner.Text())
		if n%4 == 0 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

import "fmt"

func isBeautiful(a int) string {
	if a%4 == 0 {
		return "YES"
	} else {
		return "NO"
	}
}

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

	for tests > 0 {
		var a int
		fmt.Scan(&a)

		fmt.Println(isBeautiful(a))
		tests--
	}
}

package main

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

func isBeautiful(a int) string {
	if a%4 == 0 {
		return "YES"
	} else {
		return "NO"
	}
}

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

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

	for tests > 0 {
		scanner.Scan()
		a, _ := strconv.Atoi(scanner.Text())
		cout := &a

		fmt.Println(isBeautiful(*cout))
		tests--
	}
}

package main

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

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 main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)
		res := solve(n)
		if res {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func solve(n int) bool {
	if n < 4 {
		return false
	}
	if n == 4 {
		return true
	}

	if n < 12 {
		return false
	}
	//2 * 4 + x * 4 == n
	m := n - 8
	return m%4 == 0
}

package main

import (
	"fmt"
)

func main() {
    	var n int
    	fmt.Scanln(&n)
	a := make([]int, n)
  	for i := 0; i < n; i++ {
      		fmt.Scan(&a[i])
    	}
	for _, value := range a {
		if value%4 == 0 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buffer := make([]byte, 1024*1024)
	scanner.Buffer(buffer, 1024*1024)

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

	var t, n int
	t = input()

	for ; t > 0; t-- {
		n = input()

		if n%4 == 0 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

import (
	"bufio"
	"fmt"
)

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	for i := 0; i < cases; i++ {
		var n int64
		fmt.Scanf("%d\n", &n)
		if n % 4 == 0 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

package main

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

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		n := reader.NextInt64()
		writer.Printf("%s\n", sol(n))
	}
}

func sol(x int64) string {
	if(x%4==0){
		return "YES"
	}
  return "NO"
}

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}
/*********************** Utils ***********************/

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func SArr64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func MnMx(args ...int64) (int64, int64) {
	minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64)
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int64) int64 { mn, _ := MnMx(args...); return mn }
func Mx(args ...int64) int64 { _, mx := MnMx(args...); return mx }
func LCM(a, b int64) int64   { return a / GCD(a, b) * b }
func GCD(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

// cf1 project main.go
package main

import (
	"fmt"
)

func main() {
	var n, i int
	fmt.Scanln(&n)
	for j := 0; j < n; j++ {
		fmt.Scan(&i)
		if i%4 == 0 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

/*
URL:
https://codeforces.com/contest/1369/problem/A
*/

package main

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

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

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

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

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

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

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

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

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

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

var (
	t int
	n int
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n = ReadInt()

		solve()
	}
}

func solve() {
	if n%4 == 0 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

package main

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

var nTest, n int

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

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

		if (n-4)%4 == 0 {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}

	out.Flush()
}

package main

import "fmt"

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

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

		if n%4 == 0 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

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

	var num int
	for i := 0 ; i < count; i++ {
		scanner.Scan()
		num ,  _ = strconv.Atoi(scanner.Text())

		if num %4 == 0 {
			fmt.Println("YES")

			continue
		}

		fmt.Println("NO")
	}
}

package main

import "fmt"

func main(){
	var t int32
	var n int32
	fmt.Scan(&t)

	for ;t>0;t-- {
		fmt.Scan(&n)
		if n%4 == 0 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	var t int
	con.Scan(&t)
	for i := 0; i < t; i++ {
		var n int
		con.Scan(&n)
		if n%4 == 0 {
			con.Println("YES")
		} else {
			con.Println("NO")
		}
	}
	return nil
}

package main

import (
	"fmt"
)

func main() {
	var tc,n int
	fmt.Scanf("%d", &tc)
	for tc > 0  {
		tc--
		fmt.Scanf("%d", &n)
		if n%4 == 0 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		n := reader.NextInt64()
		writer.Printf("%d\n", sol(n))
	}
}

func sol(x int64) string {
	if(x%4==0){
		return "YES"
	}
  return "NO"
}

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}
/*********************** Utils ***********************/

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func SArr64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func MnMx(args ...int64) (int64, int64) {
	minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64)
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int64) int64 { mn, _ := MnMx(args...); return mn }
func Mx(args ...int64) int64 { _, mx := MnMx(args...); return mx }
func LCM(a, b int64) int64   { return a / GCD(a, b) * b }
func GCD(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

package main

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

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		n := reader.NextInt64()
		writer.Printf("%d\n", sol(n))
	}
}

func sol(x int64) string {
	if(x%2==0){
		return "YES"
	}
  return "NO"
}

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

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

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

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}
/*********************** Utils ***********************/

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func SArr64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func MnMx(args ...int64) (int64, int64) {
	minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64)
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int64) int64 { mn, _ := MnMx(args...); return mn }
func Mx(args ...int64) int64 { _, mx := MnMx(args...); return mx }
func LCM(a, b int64) int64   { return a / GCD(a, b) * b }
func GCD(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

// cf1 project main.go
package main

import (
	"fmt"
	"os"
)

func main() {
	var i int
	fmt.Fscan(os.Stdin, &i)
	fmt.Println(i)
	if i%2 == 0 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

// cf1 project main.go
package main

import (
	"fmt"
)

func main() {
	var n, i int
	fmt.Scanln(&n)
	for j := 0; j < n; j++ {
		fmt.Scan(&i)
		if i%2 == 0 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

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

	var num int
	for i := 0 ; i < count; i++ {
		scanner.Scan()
		num ,  _ = strconv.Atoi(scanner.Text())

		if num %2 == 0 {
			fmt.Println("YES")

			continue
		}

		fmt.Println("NO")
	}
}

package main

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

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	var t int
	con.Scan(&t)
	for i := 0; i < t; i++ {
		var n int
		con.Scan(&n)
		if n%2 == 0 {
			con.Println("YES")
		} else {
			con.Println("NO")
		}
	}
	return nil
}


Petya is a math teacher. $$$n$$$ of his students has written a test consisting of $$$m$$$ questions. For each student, it is known which questions he has answered correctly and which he has not.If the student answers the $$$j$$$-th question correctly, he gets $$$p_j$$$ points (otherwise, he gets $$$0$$$ points). Moreover, the points for the questions are distributed in such a way that the array $$$p$$$ is a permutation of numbers from $$$1$$$ to $$$m$$$.For the $$$i$$$-th student, Petya knows that he expects to get $$$x_i$$$ points for the test. Petya wonders how unexpected the results could be. Petya believes that the surprise value of the results for students is equal to $$$\sum\limits_{i=1}^{n} |x_i - r_i|$$$, where $$$r_i$$$ is the number of points that the $$$i$$$-th student has got for the test.Your task is to help Petya find such a permutation $$$p$$$ for which the surprise value of the results is maximum possible. If there are multiple answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10$$$; $$$1 \le m \le 10^4$$$) — the number of students and the number of questions, respectively. The second line contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i \le \frac{m(m+1)}{2}$$$), where $$$x_i$$$ is the number of points that the $$$i$$$-th student expects to get. This is followed by $$$n$$$ lines, the $$$i$$$-th line contains the string $$$s_i$$$ ($$$|s_i| = m; s_{i, j} \in \{0, 1\}$$$), where $$$s_{i, j}$$$ is $$$1$$$ if the $$$i$$$-th student has answered the $$$j$$$-th question correctly, and $$$0$$$ otherwise. The sum of $$$m$$$ for all test cases does not exceed $$$10^4$$$.

For each test case, print $$$m$$$ integers — a permutation $$$p$$$ for which the surprise value of the results is maximum possible. If there are multiple answers, print any of them.

package main

import (
	"bufio"
	. "fmt"
	"log"
	"os"
	"sort"
	"strconv"
	//"container/heap"
)

var _ = Scan // reference fmt

type ll int64

const _0 ll = 0
const _1 ll = 1
const INF ll = 1e18 + 7

type Sll []ll

func (s Sll) Sort() {
	sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
}

func btoi(b bool) ll {
	if b {
		return 1
	} else {
		return 0
	}
}

func max(i1 ll, i2 ll) ll { return Sll{i1, i2}[btoi(i1 < i2)] }
func min(i1 ll, i2 ll) ll { return Sll{i2, i1}[btoi(i1 < i2)] }
func abs(i1 ll) ll        { return max(i1, -i1) }
func absi(i1 int) int {
	if i1 > 0 {
		return i1
	} else {
		return -i1
	}
}

func makeii(n ll, m ll) []Sll {
	a := make([]Sll, n)
	for i := _0; i < n; i++ {
		a[i] = make(Sll, m)
	}
	return a
}

var r *bufio.Reader
var wr *bufio.Writer
var er *bufio.Writer

func cini() ll {
	s := cins()
	ans, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		log.Panic("cini failed, s=", s)
	}
	return ll(ans)
}
func cinai(n ll) Sll {
	ans := make(Sll, n)
	for i := range ans {
		ans[i] = cini()
	}
	return ans
}

// read a WS delimited word, works also on atcoder with long strings
func cinb() []byte {
	s := make([]byte, 0)
	for {
		b, err := r.ReadByte()
		if err != nil {
			return s
		}
		if b == 10 || b == 13 || b == '\t' || b == ' ' {
			continue
		} else {
			s = append(s, b)
			break
		}
	}
	for {
		b, err := r.ReadByte()
		if err != nil || b == 10 || b == 13 || b == '\t' || b == ' ' {
			break
		}
		s = append(s, b)
	}

	return s
}
func cins() string {
	return string(cinb())
}

// Each value p[i] adds p[i] points to the studends j having s[j][i]==true
// There are only 10 students, consider we want to
// maximize/minimize each one, 1024 configurations.
// Then each question has a min/max scoring, order the questions by that,
// and assign the p[i] according to that ordering.
// One of the 2^10 configurations gives max ans.
func solve() {
	var n, m int
	Fscan(r, &n, &m)

	x := make([]int, n)
	for i := range x {
		Fscan(r, &x[i])
	}

	vis := make([]string, n)
	for i := range vis {
		Fscan(r, &vis[i])
	}

	var ansp []int
	ans := int(-1e9)
	for i := 0; i < (1 << n); i++ {
		sc := make([]ll, m) // score of the m questions
		for k := 0; k < m; k++ {
			for j := 0; j < n; j++ {
				if i&(1<<j) > 0 { // student j should be maximized
					if vis[j][k] == '1' {
						sc[k]++
					}
				} else { // student j should be minimized
					if vis[j][k] == '1' {
						sc[k]--
					}
				}
			}
		}

		p := make([]ll, m)
		for j := range p {
			p[j] = ll(j)
		}
		sort.Slice(p, func(i, j int) bool { return sc[p[i]] < sc[p[j]] })

		pp := make([]int, m)
		for j := range pp {
			pp[p[j]] = j + 1
		}

		xx := make([]int, n)
		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				xx[j] += pp[k] * int(vis[j][k]-'0')
			}
		}
		lans := 0
		for j := 0; j < n; j++ {
			lans += absi(xx[j] - x[j])
		}
		if lans > ans {
			ans = lans
			ansp = pp
		}
	}
	for i := range ansp {
		Fprintf(wr, "%d ", ansp[i])
	}
	Fprintln(wr)
}

func main() {
	r = bufio.NewReader(os.Stdin)
	wr = bufio.NewWriter(os.Stdout)
	er = bufio.NewWriter(os.Stderr)
	defer wr.Flush()
	defer er.Flush()
	for t := cini(); t > 0; t-- {
		solve()
	}
}

package main

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

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

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n, m := readTwoNums(reader)
		X := readNNums(reader, n)
		A := make([]string, n)
		for i := 0; i < n; i++ {
			A[i], _ = reader.ReadString('\n')
		}
		res := solve(n, m, X, A)
		for i := 0; i < m; i++ {
			buf.WriteString(fmt.Sprintf("%d ", res[i]))
		}
		buf.WriteByte('\n')
	}
	fmt.Print(buf.String())
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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

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

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

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

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

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

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

	return i
}

func solve(n int, m int, X []int, A []string) []int {

	var ans int = -1
	best := make([]int, m)

	for mask := 0; mask < 1<<n; mask++ {

		val := make([]int, m)

		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				if A[i][j] == '1' {
					if (mask>>i)&1 == 1 {
						val[j]++
					} else {
						val[j]--
					}
				}
			}
		}

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

		var tmp int
		for i := 0; i < n; i++ {
			if (mask>>i)&1 == 1 {
				tmp -= X[i]
			} else {
				tmp += X[i]
			}
		}

		for i := 0; i < m; i++ {
			tmp += val[p[i]] * (i + 1)
		}

		if tmp > ans {
			ans = tmp
			copy(best, p)
		}
	}
	res := make([]int, m)
	for i := 0; i < m; i++ {
		res[best[i]] = i + 1
	}

	return res
}

package main

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

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

var n int
var m int
var expected []int
var test []string
var coef []int

type Coef struct {
	coef  int
	index int
}

var path []Coef
var ansPath []int

func solveCoef() int {
	for i := 0; i < m; i++ {
		path[i] = Coef{coef: coef[i], index: i + 1}
	}
	sort.Slice(path, func(i, j int) bool {
		return path[i].coef < path[j].coef
	})

	var ans = 0
	for i := 0; i < m; i++ {
		ans += (i + 1) * path[i].coef
	}

	return ans
}

func solve() {
	var ans = -1
	for mask := 0; mask < (1 << n); mask++ {
		for i := 0; i < m; i++ {
			coef[i] = 0
		}
		var ansMask = 0
		for i := 0; i < n; i++ {
			var sign = -1
			if ((mask >> i) & 1) > 0 {
				sign = 1
			}
			for j := 0; j < m; j++ {
				if test[i][j] == '1' {
					coef[j] -= sign
				}
			}
			ansMask += sign * expected[i]
		}
		ansMask += solveCoef()
		if ansMask > ans {
			ans = ansMask
			// fmt.Fprintf(out, "mask = %d, path = %v\n", mask, path)
			for i := 0; i < m; i++ {
				ansPath[path[i].index-1] = i + 1
			}
		}
	}
}

func main() {
	var ntc int
	fmt.Fscan(in, &ntc)
	for t := 0; t < ntc; t++ {
		fmt.Fscan(in, &n, &m)
		expected = make([]int, n)
		test = make([]string, n)
		coef = make([]int, m)
		path = make([]Coef, m)
		ansPath = make([]int, m)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &expected[i])
		}
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &test[i])
		}
		solve()
		for i := 0; i < m; i++ {
			fmt.Fprintf(out, "%d ", ansPath[i])
		}
		fmt.Fprintln(out)
	}
	out.Flush()
}

package main

import (
	"bufio"
	. "fmt"
	"log"
	"os"
	"sort"
	"strconv"
	//"container/heap"
)

var _ = Scan // reference fmt

type ll int64

const _0 ll = 0
const _1 ll = 1
const INF ll = 1e18 + 7

type Sll []ll

func (s Sll) Sort() {
	sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
}

func btoi(b bool) ll {
	if b {
		return 1
	} else {
		return 0
	}
}

func max(i1 ll, i2 ll) ll { return Sll{i1, i2}[btoi(i1 < i2)] }
func min(i1 ll, i2 ll) ll { return Sll{i2, i1}[btoi(i1 < i2)] }
func abs(i1 ll) ll        { return max(i1, -i1) }

func makeii(n ll, m ll) []Sll {
	a := make([]Sll, n)
	for i := _0; i < n; i++ {
		a[i] = make(Sll, m)
	}
	return a
}

var r *bufio.Reader
var wr *bufio.Writer
var er *bufio.Writer

func cini() ll {
	s := cins()
	ans, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		log.Panic("cini failed, s=", s)
	}
	return ll(ans)
}
func cinai(n ll) Sll {
	ans := make(Sll, n)
	for i := range ans {
		ans[i] = cini()
	}
	return ans
}

// read a WS delimited word, works also on atcoder with long strings
func cinb() []byte {
	s := make([]byte, 0)
	for {
		b, err := r.ReadByte()
		if err != nil {
			return s
		}
		if b == 10 || b == 13 || b == '\t' || b == ' ' {
			continue
		} else {
			s = append(s, b)
			break
		}
	}
	for {
		b, err := r.ReadByte()
		if err != nil || b == 10 || b == 13 || b == '\t' || b == ' ' {
			break
		}
		s = append(s, b)
	}

	return s
}
func cins() string {
	return string(cinb())
}

// Each value p[i] adds p[i] points to the studends j having s[j][i]==true
// There are only 10 students, consider we want to
// maximize/minimize each one, 1024 configurations.
// Then each question has a min/max scoring, order the questions by that,
// and assign the p[i] according to that ordering.
// One of the 2^10 configurations gives max ans.
func solve() {
	n := cini()
	m := cini()

	x := cinai(n)

	a := make([][]bool, n)
	for i := range a {
		a[i] = make([]bool, m)
	}
	for i := _0; i < n; i++ {
		b := cinb()
		for j := range b {
			if b[j] == '1' {
				a[i][j] = true
			}
		}
	}

	var ansp []ll
	ans := _0
	for i := 0; i < (1 << n); i++ {
		sc := make([][2]ll, m) // score of the m questions
		for k := _0; k < m; k++ {
			sc[k][1] = k
			for j := _0; j < n; j++ {
				if i&(1<<j) > 0 { // student j should be maximized
					if a[j][k] {
						sc[k][0]++
					}
				} else { // student j should be minimized
					if a[j][k] {
						sc[k][0]--
					}
				}
			}
		}

		sort.Slice(sc, func(i, j int) bool { return sc[i][0] < sc[j][0] })

		lans := _0
		for j := _0; j < n; j++ {
			if i&(1<<j) != 0 {
				lans -= x[j]
			} else {
				lans += x[j]
			}
		}

		for j := _0; j < m; j++ {
			lans += (j + 1) * sc[j][0]
		}

		if lans > ans {
			pp := make([]ll, m)
			for j := range pp {
				pp[sc[j][1]] = ll(j + 1)
			}

			ans = lans
			ansp = pp
		}
	}
	for i := range ansp {
		Print(ansp[i], " ")
	}
	Println()
}

func main() {
	r = bufio.NewReader(os.Stdin)
	wr = bufio.NewWriter(os.Stdout)
	er = bufio.NewWriter(os.Stderr)
	defer wr.Flush()
	defer er.Flush()
	for t := cini(); t > 0; t-- {
		solve()
	}
}

package main

import (
	"bufio"
	. "fmt"
	"log"
	"os"
	"sort"
	"strconv"
	//"container/heap"
)

var _ = Scan // reference fmt

type ll int64

const _0 ll = 0
const _1 ll = 1
const INF ll = 1e18 + 7

type Sll []ll

func (s Sll) Sort() {
	sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
}

func btoi(b bool) ll {
	if b {
		return 1
	} else {
		return 0
	}
}

func max(i1 ll, i2 ll) ll { return Sll{i1, i2}[btoi(i1 < i2)] }
func min(i1 ll, i2 ll) ll { return Sll{i2, i1}[btoi(i1 < i2)] }
func abs(i1 ll) ll        { return max(i1, -i1) }

func makeii(n ll, m ll) []Sll {
	a := make([]Sll, n)
	for i := _0; i < n; i++ {
		a[i] = make(Sll, m)
	}
	return a
}

var r *bufio.Reader
var wr *bufio.Writer
var er *bufio.Writer

func cini() ll {
	s := cins()
	ans, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		log.Panic("cini failed, s=", s)
	}
	return ll(ans)
}
func cinai(n ll) Sll {
	ans := make(Sll, n)
	for i := range ans {
		ans[i] = cini()
	}
	return ans
}

// read a WS delimited word, works also on atcoder with long strings
func cinb() []byte {
	s := make([]byte, 0)
	for {
		b, err := r.ReadByte()
		if err != nil {
			return s
		}
		if b == 10 || b == 13 || b == '\t' || b == ' ' {
			continue
		} else {
			s = append(s, b)
			break
		}
	}
	for {
		b, err := r.ReadByte()
		if err != nil || b == 10 || b == 13 || b == '\t' || b == ' ' {
			break
		}
		s = append(s, b)
	}

	return s
}
func cins() string {
	return string(cinb())
}

// Each value p[i] adds p[i] points to the studends j having s[j][i]==true
// There are only 10 students, consider we want to
// maximize/minimize each one, 1024 configurations.
// Then each question has a min/max scoring, order the questions by that,
// and assign the p[i] according to that ordering.
// One of the 2^10 configurations gives max ans.
func solve() {
	n := cini()
	m := cini()

	x := cinai(n)

	vis := make([][]bool, n)
	for i := range vis {
		vis[i] = make([]bool, m)
	}
	for i := _0; i < n; i++ {
		b := cinb()
		for j := range b {
			if b[j] == '1' {
				vis[i][j] = true
			}
		}
	}

	var ansp []ll
	ans := _0
	for i := 0; i < (1 << n); i++ {
		sc := make([][2]ll, m) // score of the m questions
		for k := _0; k < m; k++ {
			sc[k][1] = k
			for j := _0; j < n; j++ {
				if i&(1<<j) > 0 { // student j should be maximized
					if vis[j][k] {
						sc[k][0]++
					}
				} else { // student j should be minimized
					if vis[j][k] {
						sc[k][0]--
					}
				}
			}
		}

		sort.Slice(sc, func(i, j int) bool { return sc[i][0] < sc[j][0] })

		lans := _0
		for j := _0; j < n; j++ {
			if i&(1<<j) != 0 {
				lans += x[j]
			} else {
				lans -= x[j]
			}
		}

		for j := _0; j < m; j++ {
			lans += (j + 1) * sc[j][0]
		}

		if lans > ans {
			pp := make([]ll, m)
			for j := range pp {
				pp[sc[j][1]] = ll(j + 1)
			}

			ans = lans
			ansp = pp
		}
	}
	for i := range ansp {
		Print(ansp[i], " ")
	}
	Println()
}

func main() {
	r = bufio.NewReader(os.Stdin)
	wr = bufio.NewWriter(os.Stdout)
	er = bufio.NewWriter(os.Stderr)
	defer wr.Flush()
	defer er.Flush()
	for t := cini(); t > 0; t-- {
		solve()
	}
}

package main

import (
	"bufio"
	. "fmt"
	"log"
	"os"
	"sort"
	"strconv"
	//"container/heap"
)

var _ = Scan // reference fmt

type ll int64

const _0 ll = 0
const _1 ll = 1
const INF ll = 1e18 + 7

type Sll []ll

func (s Sll) Sort() {
	sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
}

func btoi(b bool) ll {
	if b {
		return 1
	} else {
		return 0
	}
}

func max(i1 ll, i2 ll) ll { return Sll{i1, i2}[btoi(i1 < i2)] }
func min(i1 ll, i2 ll) ll { return Sll{i2, i1}[btoi(i1 < i2)] }
func abs(i1 ll) ll        { return max(i1, -i1) }

func makeii(n ll, m ll) []Sll {
	a := make([]Sll, n)
	for i := _0; i < n; i++ {
		a[i] = make(Sll, m)
	}
	return a
}

var r *bufio.Reader
var wr *bufio.Writer
var er *bufio.Writer

func cini() ll {
	s := cins()
	ans, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		log.Panic("cini failed, s=", s)
	}
	return ll(ans)
}
func cinai(n ll) Sll {
	ans := make(Sll, n)
	for i := range ans {
		ans[i] = cini()
	}
	return ans
}

// read a WS delimited word, works also on atcoder with long strings
func cinb() []byte {
	s := make([]byte, 0)
	for {
		b, err := r.ReadByte()
		if err != nil {
			return s
		}
		if b == 10 || b == 13 || b == '\t' || b == ' ' {
			continue
		} else {
			s = append(s, b)
			break
		}
	}
	for {
		b, err := r.ReadByte()
		if err != nil || b == 10 || b == 13 || b == '\t' || b == ' ' {
			break
		}
		s = append(s, b)
	}

	return s
}
func cins() string {
	return string(cinb())
}

// Each value p[i] adds p[i] points to the studends j having s[j][i]==true
// There are only 10 students, consider we want to
// maximize/minimize each one, 1024 configurations.
// Then each question has a min/max scoring, order the questions by that,
// and assign the p[i] according to that ordering.
// One of the 2^10 configurations gives max ans.
func solve() {
	n := cini()
	m := cini()

	x := cinai(n)

	vis := make([][]bool, n)
	for i := range vis {
		vis[i] = make([]bool, m)
	}
	for i := _0; i < n; i++ {
		b := cinb()
		for j := range b {
			if b[j] == '1' {
				vis[i][j] = true
			}
		}
	}

	var ansp []ll
	ans := _0
	for i := 0; i < (1 << n); i++ {
		sc := make([][2]ll, m) // score of the m questions
		for k := _0; k < m; k++ {
			sc[k][1] = k
			for j := _0; j < n; j++ {
				if i&(1<<j) > 0 { // student j should be maximized
					if vis[j][k] {
						sc[k][0]++
					}
				} else { // student j should be minimized
					if vis[j][k] {
						sc[k][0]--
					}
				}
			}
		}

		sort.Slice(sc, func(i, j int) bool { return sc[i][0] < sc[j][0] })

		pp := make([]ll, m)
		for j := range pp {
			pp[sc[j][1]] = ll(j + 1)
		}

		xx := make([]ll, n)
		for k := _0; k < m; k++ {
			for j := _0; j < n; j++ {
				if vis[j][k] {
					xx[j] += pp[k]
				}
			}
		}
		lans := _0
		for j := _0; j < n; j++ {
			lans += abs(xx[j] - x[j])
		}
		if lans > ans {
			ans = lans
			ansp = pp
		}
	}
	for i := range ansp {
		Print(ansp[i], " ")
	}
	Println()
}

func main() {
	r = bufio.NewReader(os.Stdin)
	wr = bufio.NewWriter(os.Stdout)
	er = bufio.NewWriter(os.Stderr)
	defer wr.Flush()
	defer er.Flush()
	for t := cini(); t > 0; t-- {
		solve()
	}
}

package main

import (
	"bufio"
	. "fmt"
	"log"
	"os"
	"sort"
	"strconv"
	//"container/heap"
)

var _ = Scan // reference fmt

type ll int64

const _0 ll = 0
const _1 ll = 1
const INF ll = 1e18 + 7

type Sll []ll

func (s Sll) Sort() {
	sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
}

func btoi(b bool) ll {
	if b {
		return 1
	} else {
		return 0
	}
}

func max(i1 ll, i2 ll) ll { return Sll{i1, i2}[btoi(i1 < i2)] }
func min(i1 ll, i2 ll) ll { return Sll{i2, i1}[btoi(i1 < i2)] }
func abs(i1 ll) ll        { return max(i1, -i1) }

func makeii(n ll, m ll) []Sll {
	a := make([]Sll, n)
	for i := _0; i < n; i++ {
		a[i] = make(Sll, m)
	}
	return a
}

var r *bufio.Reader
var wr *bufio.Writer
var er *bufio.Writer

func cini() ll {
	s := cins()
	ans, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		log.Panic("cini failed, s=", s)
	}
	return ll(ans)
}
func cinai(n ll) Sll {
	ans := make(Sll, n)
	for i := range ans {
		ans[i] = cini()
	}
	return ans
}

// read a WS delimited word, works also on atcoder with long strings
func cinb() []byte {
	s := make([]byte, 0)
	for {
		b, err := r.ReadByte()
		if err != nil {
			return s
		}
		if b == 10 || b == 13 || b == '\t' || b == ' ' {
			continue
		} else {
			s = append(s, b)
			break
		}
	}
	for {
		b, err := r.ReadByte()
		if err != nil || b == 10 || b == 13 || b == '\t' || b == ' ' {
			break
		}
		s = append(s, b)
	}

	return s
}
func cins() string {
	return string(cinb())
}

// Each value p[i] adds p[i] points to the studends j having s[j][i]==true
// There are only 10 students, consider we want to
// maximize/minimize each one, 1024 configurations.
// Then each question has a min/max scoring, order the questions by that,
// and assign the p[i] according to that ordering.
// One of the 2^10 configurations gives max ans.
func solve() {
	n := cini()
	m := cini()

	x := cinai(n)

	vis := make([][]bool, n)
	for i := range vis {
		vis[i] = make([]bool, m)
	}
	for i := _0; i < n; i++ {
		b := cinb()
		for j := range b {
			if b[j] == '1' {
				vis[i][j] = true
			}
		}
	}

	var ansp []ll
	ans := _0
	for i := 0; i < (1 << n); i++ {
		sc := make([]ll, m) // score of the m questions
		for k := _0; k < m; k++ {
			for j := _0; j < n; j++ {
				if i&(1<<j) > 0 { // student j should be maximized
					if vis[j][k] {
						sc[k]++
					}
				} else { // student j should be minimized
					if vis[j][k] {
						sc[k]--
					}
				}
			}
		}

		p := make([]ll, m)
		for j := range p {
			p[j] = ll(j)
		}
		sort.Slice(p, func(i, j int) bool { return sc[p[i]] < sc[p[j]] })

		pp := make([]ll, m)
		for j := range pp {
			pp[p[j]] = ll(j + 1)
		}

		xx := make([]ll, n)
		for k := _0; k < m; k++ {
			for j := _0; j < n; j++ {
				if vis[j][k] {
					xx[j] += pp[k]
				}
			}
		}
		lans := _0
		for j := _0; j < n; j++ {
			lans += abs(xx[j] - x[j])
		}
		if lans > ans {
			ans = lans
			ansp = pp
		}
	}
	for i := range ansp {
		Print(ansp[i], " ")
	}
	Println()
}

func main() {
	r = bufio.NewReader(os.Stdin)
	wr = bufio.NewWriter(os.Stdout)
	er = bufio.NewWriter(os.Stderr)
	defer wr.Flush()
	defer er.Flush()
	for t := cini(); t > 0; t-- {
		solve()
	}
}

package main

import (
	"bufio"
	. "fmt"
	"log"
	"os"
	"sort"
	"strconv"
	//"container/heap"
)

var _ = Scan // reference fmt

type ll int64

const _0 ll = 0
const _1 ll = 1
const INF ll = 1e18 + 7

type Sll []ll

func (s Sll) Sort() {
	sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
}

func btoi(b bool) ll {
	if b {
		return 1
	} else {
		return 0
	}
}

func max(i1 ll, i2 ll) ll { return Sll{i1, i2}[btoi(i1 < i2)] }
func min(i1 ll, i2 ll) ll { return Sll{i2, i1}[btoi(i1 < i2)] }
func abs(i1 ll) ll        { return max(i1, -i1) }

func makeii(n ll, m ll) []Sll {
	a := make([]Sll, n)
	for i := _0; i < n; i++ {
		a[i] = make(Sll, m)
	}
	return a
}

var r *bufio.Reader
var wr *bufio.Writer
var er *bufio.Writer

func cini() ll {
	s := cins()
	ans, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		log.Panic("cini failed, s=", s)
	}
	return ll(ans)
}
func cinai(n ll) Sll {
	ans := make(Sll, n)
	for i := range ans {
		ans[i] = cini()
	}
	return ans
}

// read a WS delimited word, works also on atcoder with long strings
func cinb() []byte {
	s := make([]byte, 0)
	for {
		b, err := r.ReadByte()
		if err != nil {
			return s
		}
		if b == 10 || b == 13 || b == '\t' || b == ' ' {
			continue
		} else {
			s = append(s, b)
			break
		}
	}
	for {
		b, err := r.ReadByte()
		if err != nil || b == 10 || b == 13 || b == '\t' || b == ' ' {
			break
		}
		s = append(s, b)
	}

	return s
}
func cins() string {
	return string(cinb())
}

// Each value p[i] adds p[i] points to the studends j having s[j][i]==true
// There are only 10 students, consider we want to
// maximize/minimize each one, 1024 configurations.
// Then each question has a min/max scoring, order the questions by that,
// and assign the p[i] according to that ordering.
// One of the 2^10 configurations gives max ans.
func solve() {
	n := cini()
	m := cini()

	x := cinai(n)

	vis := make([][]bool, n)
	for i := range vis {
		vis[i] = make([]bool, m)
	}
	for i := _0; i < n; i++ {
		b := cinb()
		for j := range b {
			if b[j] == '1' {
				vis[i][j] = true
			}
		}
	}

	var ansp []ll
	ans := _0
	for i := 0; i < (1 << n); i++ {
		sc := make([]ll, m) // score of the m questions
		for k := _0; k < m; k++ {
			for j := _0; j < n; j++ {
				if i&(1<<j) > 0 { // student j should be maximized
					if vis[j][k] {
						sc[k]++
					}
				} else { // student j should be minimized
					if vis[j][k] {
						sc[k]--
					}
				}
			}
		}

		p := make([]ll, m)
		for j := range p {
			p[j] = ll(j + 1)
		}
		sort.Slice(p, func(i, j int) bool { return sc[i] < sc[j] })
		xx := make([]ll, n)
		for k := _0; k < m; k++ {
			for j := _0; j < n; j++ {
				if vis[j][k] {
					xx[j] += p[k]
				}
			}
		}
		lans := _0
		for j := _0; j < n; j++ {
			lans += abs(xx[j] - x[j])
		}
		if lans > ans {
			ans = lans
			ansp = p
		}
	}
	for i := range ansp {
		Print(ansp[i], " ")
	}
	Println()
}

func main() {
	r = bufio.NewReader(os.Stdin)
	wr = bufio.NewWriter(os.Stdout)
	er = bufio.NewWriter(os.Stderr)
	defer wr.Flush()
	defer er.Flush()
	for t := cini(); t > 0; t-- {
		solve()
	}
}

package main

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

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

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n, m := readTwoNums(reader)
		X := readNNums(reader, n)
		A := make([]string, n)
		for i := 0; i < n; i++ {
			A[i], _ = reader.ReadString('\n')
		}
		res := solve(n, m, X, A)
		for i := 0; i < m; i++ {
			buf.WriteString(fmt.Sprintf("%d ", res[i]))
		}
		buf.WriteByte('\n')
	}
	fmt.Print(buf.String())
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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

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

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

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

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

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

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

	return i
}

func solve(n int, m int, X []int, A []string) []int {

	var ans int
	best := make([]int, m)

	for mask := 0; mask < 1<<n; mask++ {

		val := make([]int, m)

		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				if A[i][j] == '1' {
					if (mask>>i)&1 == 1 {
						val[j]++
					} else {
						val[j]--
					}
				}
			}
		}

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

		var tmp int
		for i := 0; i < n; i++ {
			if (mask>>i)&1 == 1 {
				tmp -= X[i]
			} else {
				tmp += X[i]
			}
		}

		for i := 0; i < m; i++ {
			tmp += val[p[i]] * (i + 1)
		}

		if tmp > ans {
			ans = tmp
			copy(best, p)
		}
	}
	res := make([]int, m)
	for i := 0; i < m; i++ {
		res[best[i]] = i + 1
	}

	return res
}