You are given an array $$$a$$$ of length $$$n$$$. Let $$$cnt_x$$$ be the number of elements from the array which are equal to $$$x$$$. Let's also define $$$f(x, y)$$$ as $$$(cnt_x + cnt_y) \cdot (x + y)$$$.Also you are given $$$m$$$ bad pairs $$$(x_i, y_i)$$$. Note that if $$$(x, y)$$$ is a bad pair, then $$$(y, x)$$$ is also bad.Your task is to find the maximum value of $$$f(u, v)$$$ over all pairs $$$(u, v)$$$, such that $$$u \neq v$$$, that this pair is not bad, and also that $$$u$$$ and $$$v$$$ each occur in the array $$$a$$$. It is guaranteed that such a pair exists.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$0 \le m \le 3 \cdot 10^5$$$) — the length of the array and the number of bad pairs. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i < y_i \le 10^9$$$), which represent a bad pair. It is guaranteed that no bad pair occurs twice in the input. It is also guaranteed that $$$cnt_{x_i} > 0$$$ and $$$cnt_{y_i} > 0$$$. It is guaranteed that for each test case there is a pair of integers $$$(u, v)$$$, $$$u \ne v$$$, that is not bad, and such that both of these numbers occur in $$$a$$$. It is guaranteed that the total sum of $$$n$$$ and the total sum of $$$m$$$ don't exceed $$$3 \cdot 10^5$$$.

For each test case print a single integer — the answer to the problem.

package main

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

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

func flush()                            { out.Flush() }
func scan(a ...interface{})             { fmt.Fscan(in, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(out, f, a...) }
func assert(f bool) {
	if !f {
		panic("gg")
	}
}

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

func unique(a []int) []int {
	j := 1
	for i := 1; i < len(a); i++ {
		if a[i] != a[i-1] {
			a[j] = a[i]
			j++
		}
	}
	return a[:j]
}

// ----------------------------- TEMPLATE END ----------------------------------

type Pair struct {
	value int
	i     int
	j     int
}

func NewPair(i, j, value int) Pair {
	return Pair{
		value: value,
		i:     i,
		j:     j,
	}
}

type PairHeap []Pair

func (h PairHeap) Len() int {
	return len(h)
}
func (h PairHeap) Less(i, j int) bool {
	return h[i].value > h[j].value
}
func (h PairHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *PairHeap) Push(x interface{}) {
	*h = append(*h, x.(Pair))
}

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

func (h PairHeap) Peek() interface{} {
	return h[len(h)-1]
}

var nBad int
var bad [][2]int

func isBad(x, y int) bool {
	lo := 0
	hi := nBad
	mi := 0
	for lo < hi {
		mi = (lo + hi) / 2
		if x > bad[mi][0] || (x == bad[mi][0] && y > bad[mi][1]) {
			lo = mi + 1
		} else {
			hi = mi
		}
	}
	return lo < nBad && x == bad[lo][0] && y == bad[lo][1]
}

func solve1(cntx int, xs []int) int64 {
	// printf("solve1: %d - %v\n", cntx, xs)
	n := len(xs)
	if n < 2 {
		return 0
	}

	var ans int = 0
	var h PairHeap
	heap.Init(&h)
	heap.Push(&h, NewPair(n-1, n-2, xs[n-1]+xs[n-2]))
	for h.Len() > 0 {
		var top Pair = heap.Pop(&h).(Pair)
		if !isBad(xs[top.i], xs[top.j]) {
			// printf("found %d,%d, is not bad\n", xs[top.i], xs[top.j])
			ans = top.value
			break
		}
		if top.j > 0 {
			heap.Push(&h, NewPair(top.i, top.j-1, xs[top.i]+xs[top.j-1]))
		}
		if top.j+1 == top.i && top.i > 1 {
			heap.Push(&h, NewPair(top.i-1, top.i-2, xs[top.i-1]+xs[top.i-2]))
		}
	}
	// printf(" -> %d * %d\n", cntx, ans)
	return int64(ans) * int64(cntx*2)
}

func solve2(cntx int, cnty int, xs []int, ys []int) int64 {
	var ans int = 0
	var h PairHeap
	heap.Init(&h)
	heap.Push(&h, NewPair(len(xs)-1, len(ys)-1, xs[len(xs)-1]+ys[len(ys)-1]))
	for h.Len() > 0 {
		var top Pair = heap.Pop(&h).(Pair)
		if !isBad(xs[top.i], ys[top.j]) {
			ans = top.value
			break
		}
		if top.j > 0 {
			heap.Push(&h, NewPair(top.i, top.j-1, xs[top.i]+ys[top.j-1]))
		}
		if top.j+1 == len(ys) && top.i > 0 {
			heap.Push(&h, NewPair(top.i-1, len(ys)-1, xs[top.i-1]+ys[len(ys)-1]))
		}
	}
	return int64(ans) * int64(cntx+cnty)
}

func main() {
	defer flush()

	var ntc int
	scan(&ntc)
	for t := 0; t < ntc; t++ {
		var n int
		scan(&n, &nBad)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			scan(&a[i])
		}
		var v [][]int = make([][]int, n+1)
		var cntValues []int = []int{}
		sort.Ints(a)
		for i := 0; i < n; {
			j := i + 1
			for j < n && a[j] == a[i] {
				j++
			}
			cnt := j - i
			v[cnt] = append(v[cnt], a[i])
			cntValues = append(cntValues, cnt)
			i = j
		}
		sort.Ints(cntValues)
		cntValues = unique(cntValues)

		bad = make([][2]int, 2*nBad)
		for i := 0; i < nBad; i++ {
			scan(&bad[i][0], &bad[i][1])
			bad[i+nBad][0] = bad[i][1]
			bad[i+nBad][1] = bad[i][0]
		}
		nBad *= 2
		sort.Slice(bad, func(i, j int) bool {
			if bad[i][0] != bad[j][0] {
				return bad[i][0] < bad[j][0]
			}
			return bad[i][1] < bad[j][1]
		})

		// for _, cntx := range cntValues {
		// 	printf("v[%d] = %d\n", cntx, v[cntx])
		// }

		var ans int64 = 0
		nCntValues := len(cntValues)
		for i := 0; i < nCntValues; i++ {
			sort.Ints(v[cntValues[i]])
		}
		for i := 0; i < nCntValues; i++ {
			cntx := cntValues[i]
			ans = max(ans, solve1(cntx, v[cntx]))
			for j := i + 1; j < nCntValues; j++ {
				cnty := cntValues[j]
				ans = max(ans, solve2(cntx, cnty, v[cntx], v[cnty]))
			}
		}
		printf("%d\n", ans)
	}
}


Polycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity.A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with length not exceeding 10 and version — positive integer from 1 to 106. Each project (keep in mind that it is determined by both its name and version) might depend on other projects. For sure, there are no cyclic dependencies.You're given a list of project descriptions. The first of the given projects is the one being developed by Polycarp at this moment. Help Polycarp determine all projects that his project depends on (directly or via a certain chain). It's possible that Polycarp's project depends on two different versions of some project. In this case collision resolving is applied, i.e. for each such project the system chooses the version that minimizes the distance from it to Polycarp's project. If there are several options, the newer (with the maximum version) is preferred. This version is considered actual; other versions and their dependencies are ignored.More formal, choose such a set of projects of minimum possible size that the following conditions hold:   Polycarp's project is chosen;  Polycarp's project depends (directly or indirectly) on all other projects in the set;  no two projects share the name;  for each project x that some other project in the set depends on we have either x or some y with other version and shorter chain to Polycarp's project chosen. In case of ties the newer one is chosen. Output all Polycarp's project's dependencies (Polycarp's project itself should't be printed) in lexicographical order.

The first line contains an only integer n (1 ≤ n ≤ 1 000) — the number of projects in Vaja. The following lines contain the project descriptions. Each project is described by a line consisting of its name and version separated by space. The next line gives the number of direct dependencies (from 0 to n - 1) and the dependencies themselves (one in a line) in arbitrary order. Each dependency is specified by its name and version. The projects are also given in arbitrary order, but the first of them is always Polycarp's. Project descriptions are separated by one empty line. Refer to samples for better understanding. It's guaranteed that there are no cyclic dependencies.

Output all Polycarp's project's dependencies in lexicographical order.

9
codehorses 5
3
webfrmk 6
mashadb 1
mashadb 2

commons 2
0

mashadb 3
0

webfrmk 6
2
mashadb 3
commons 2

extra 4
1
extra 3

extra 3
0

extra 1
0

mashadb 1
1
extra 3

mashadb 2
1
extra 1

NoteThe first sample is given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «a» (version 3) depends on are painted black.  The second sample is again given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «codehorses» (version 5) depends on are paint it black. Note that «extra 1» is chosen instead of «extra 3» since «mashadb 1» and all of its dependencies are ignored due to «mashadb 2».

package main

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

type Project struct {
	Name    string
	Version int
}

type SelectedProject struct {
	Project
	Path int
}

var (
	dependencies     map[Project][]Project
	currentProjects  []Project
	nextProjects     map[string]Project
	selectedProjects map[string]SelectedProject
)

func main() {
	readProjects()

	selectedProjects = make(map[string]SelectedProject, len(dependencies)-1)

	selectedProjects[currentProjects[0].Name] = SelectedProject{currentProjects[0], -1}

	doWork(0)

	print()
}

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

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

	dependencies = make(map[Project][]Project, projectsCount)

	for i := 0; i < projectsCount; i++ {
		var (
			project             Project
			dependenciesCount   int
			currentDependencies []Project
		)

		scanner.Scan()
		input := strings.Split(scanner.Text(), " ")
		project.Name = input[0]
		project.Version, _ = strconv.Atoi(input[1])

		scanner.Scan()
		dependenciesCount, _ = strconv.Atoi(scanner.Text())

		currentDependencies = make([]Project, dependenciesCount)
		dependencies[project] = currentDependencies

		for j := 0; j < dependenciesCount; j++ {
			scanner.Scan()
			input := strings.Split(scanner.Text(), " ")
			currentDependencies[j].Name = input[0]
			currentDependencies[j].Version, _ = strconv.Atoi(input[1])
		}

		if i != projectsCount-1 {
			scanner.Scan()
		}

		if i == 0 {
			currentProjects = make([]Project, 1)
			currentProjects[0] = project
		}
	}

	return
}

func doWork(path int) {
	nextProjects = make(map[string]Project)

	for _, project := range currentProjects {
		for _, candidate := range dependencies[project] {
			selectProject(candidate, path)
		}
	}

	if l := len(nextProjects); l != 0 {
		currentProjects = make([]Project, l)
		for _, project := range nextProjects {
			l--
			currentProjects[l] = project
		}

		doWork(path + 1)
	}
}

func selectProject(current Project, path int) {
	selected, present := selectedProjects[current.Name]

	if !present || (selected.Path == path && selected.Version < current.Version) {
		nextProjects[current.Name] = current
		selectedProjects[current.Name] = SelectedProject{current, path}
	}
}

func print() {
	selected := make([]Project, len(selectedProjects)-1)

	i := 0
	for _, project := range selectedProjects {
		if project.Path != -1 {
			selected[i] = project.Project
			i++
		}
	}

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

	fmt.Println(i)
	for _, project := range selected {
		fmt.Printf("%s %d\n", project.Name, project.Version)
	}
}

package main

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

type Project struct {
	Name    string
	Version int
}

type SelectedProject struct {
	Project
	Path int
}

var (
	dependencies     map[Project][]Project
	currentProjects  []Project
	nextProjects     map[string]Project
	selectedProjects map[string]SelectedProject
)

func main() {
	readProjects()

	fmt.Println(dependencies)

	selectedProjects = make(map[string]SelectedProject, len(dependencies)-1)

	selectedProjects[currentProjects[0].Name] = SelectedProject{currentProjects[0], -1}

	doWork(0)

	print()
}

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

	scanner.Scan()

	projectsCount, err := strconv.Atoi(scanner.Text())

	fmt.Println(projectsCount)
	fmt.Println(err)

	dependencies = make(map[Project][]Project, projectsCount)

	for i := 0; i < projectsCount; i++ {
		var (
			project             Project
			dependenciesCount   int
			currentDependencies []Project
		)

		scanner.Scan()
		input := strings.Split(scanner.Text(), " ")
		project.Name = input[0]
		project.Version, _ = strconv.Atoi(input[1])

		scanner.Scan()
		dependenciesCount, _ = strconv.Atoi(scanner.Text())

		currentDependencies = make([]Project, dependenciesCount)
		dependencies[project] = currentDependencies

		for j := 0; j < dependenciesCount; j++ {
			scanner.Scan()
			input := strings.Split(scanner.Text(), " ")
			currentDependencies[j].Name = input[0]
			currentDependencies[j].Version, _ = strconv.Atoi(input[1])
		}

		if i != projectsCount-1 {
			scanner.Scan()
		}

		if i == 0 {
			currentProjects = make([]Project, 1)
			currentProjects[0] = project
		}
	}

	return
}

func doWork(path int) {
	nextProjects = make(map[string]Project)

	for _, project := range currentProjects {
		for _, candidate := range dependencies[project] {
			selectProject(candidate, path)
		}
	}

	if l := len(nextProjects); l != 0 {
		currentProjects = make([]Project, l)
		for _, project := range nextProjects {
			l--
			currentProjects[l] = project
		}

		doWork(path + 1)
	}
}

func selectProject(current Project, path int) {
	selected, present := selectedProjects[current.Name]

	if !present || (selected.Path == path && selected.Version < current.Version) {
		nextProjects[current.Name] = current
		selectedProjects[current.Name] = SelectedProject{current, path}
	}
}

func print() {
	selected := make([]Project, len(selectedProjects)-1)

	i := 0
	for _, project := range selectedProjects {
		if project.Path != -1 {
			selected[i] = project.Project
			i++
		}
	}

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

	fmt.Println(i)
	for _, project := range selected {
		fmt.Printf("%s %d\n", project.Name, project.Version)
	}
}

package main

import (
	"fmt"
	"sort"
)

type Project struct {
	Name    string
	Version int
}

type SelectedProject struct {
	Project
	Path int
}

var (
	dependencies     map[Project][]Project
	currentProjects  []Project
	nextProjects     map[string]Project
	selectedProjects map[string]SelectedProject
)

func main() {
	readProjects()

	selectedProjects = make(map[string]SelectedProject, len(dependencies)-1)

	selectedProjects[currentProjects[0].Name] = SelectedProject{currentProjects[0], -1}

	doWork(0)

	print()
}

func readProjects() {
	var projectsCount int
	fmt.Scanf("%d", &projectsCount)
	dependencies = make(map[Project][]Project, projectsCount)

	for i := 0; i < projectsCount; i++ {
		var (
			project             Project
			dependenciesCount   int
			currentDependencies []Project
		)

		fmt.Scanf("%s %d", &project.Name, &project.Version)
		fmt.Scanf("%d", &dependenciesCount)
		currentDependencies = make([]Project, dependenciesCount)
		dependencies[project] = currentDependencies

		for j := 0; j < dependenciesCount; j++ {
			fmt.Scanf("%s %d", &currentDependencies[j].Name, &currentDependencies[j].Version)
		}

		if i != projectsCount-1 {
			fmt.Scanf("%s")
		}

		if i == 0 {
			currentProjects = make([]Project, 1)
			currentProjects[0] = project
		}
	}

	return
}

func doWork(path int) {
	nextProjects = make(map[string]Project)

	for _, project := range currentProjects {
		for _, candidate := range dependencies[project] {
			selectProject(candidate, path)
		}
	}

	if l := len(nextProjects); l != 0 {
		currentProjects = make([]Project, l)
		for _, project := range nextProjects {
			l--
			currentProjects[l] = project
		}

		doWork(path + 1)
	}
}

func selectProject(current Project, path int) {
	selected, present := selectedProjects[current.Name]

	if !present || (selected.Path == path && selected.Version < current.Version) {
		nextProjects[current.Name] = current
		selectedProjects[current.Name] = SelectedProject{current, path}
	}
}

func print() {
	selected := make([]Project, len(selectedProjects)-1)

	i := 0
	for _, project := range selectedProjects {
		if project.Path != -1 {
			selected[i] = project.Project
			i++
		}
	}

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

	fmt.Println(i)
	for _, project := range selected {
		fmt.Printf("%s %d\n", project.Name, project.Version)
	}
}

package main

import (
	"fmt"
	"sort"
)

type Project struct {
	Name    string
	Version int
}

type SelectedProject struct {
	Project
	Path int
}

var (
	dependencies     map[Project][]Project
	currentProjects  []Project
	nextProjects     map[string]Project
	selectedProjects map[string]SelectedProject
)

func main() {
	readProjects()

	fmt.Println(dependencies)

	selectedProjects = make(map[string]SelectedProject, len(dependencies)-1)

	selectedProjects[currentProjects[0].Name] = SelectedProject{currentProjects[0], -1}

	doWork(0)

	print()
}

func readProjects() {
	var projectsCount int
	fmt.Scanf("%d", &projectsCount)
	dependencies = make(map[Project][]Project, projectsCount)

	for i := 0; i < projectsCount; i++ {
		var (
			project             Project
			dependenciesCount   int
			currentDependencies []Project
		)

		fmt.Scanf("%s %d", &project.Name, &project.Version)
		fmt.Scanf("%d", &dependenciesCount)
		currentDependencies = make([]Project, dependenciesCount)
		dependencies[project] = currentDependencies

		for j := 0; j < dependenciesCount; j++ {
			fmt.Scanf("%s %d", &currentDependencies[j].Name, &currentDependencies[j].Version)
		}

		if i != projectsCount-1 {
			fmt.Scanf("%s")
		}

		if i == 0 {
			currentProjects = make([]Project, 1)
			currentProjects[0] = project
		}
	}

	return
}

func doWork(path int) {
	nextProjects = make(map[string]Project)

	for _, project := range currentProjects {
		for _, candidate := range dependencies[project] {
			selectProject(candidate, path)
		}
	}

	if l := len(nextProjects); l != 0 {
		currentProjects = make([]Project, l)
		for _, project := range nextProjects {
			l--
			currentProjects[l] = project
		}

		doWork(path + 1)
	}
}

func selectProject(current Project, path int) {
	selected, present := selectedProjects[current.Name]

	if !present || (selected.Path == path && selected.Version < current.Version) {
		nextProjects[current.Name] = current
		selectedProjects[current.Name] = SelectedProject{current, path}
	}
}

func print() {
	selected := make([]Project, len(selectedProjects)-1)

	i := 0
	for _, project := range selectedProjects {
		if project.Path != -1 {
			selected[i] = project.Project
			i++
		}
	}

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

	fmt.Println(i)
	for _, project := range selected {
		fmt.Printf("%s %d\n", project.Name, project.Version)
	}
}


A total of $$$n$$$ depots are located on a number line. Depot $$$i$$$ lies at the point $$$x_i$$$ for $$$1 \le i \le n$$$.You are a salesman with $$$n$$$ bags of goods, attempting to deliver one bag to each of the $$$n$$$ depots. You and the $$$n$$$ bags are initially at the origin $$$0$$$. You can carry up to $$$k$$$ bags at a time. You must collect the required number of goods from the origin, deliver them to the respective depots, and then return to the origin to collect your next batch of goods.Calculate the minimum distance you need to cover to deliver all the bags of goods to the depots. You do not have to return to the origin after you have delivered all the bags.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$). It is possible that some depots share the same position. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer denoting the minimum distance you need to cover to deliver all the bags of goods to the depots.

NoteIn the first test case, you can carry only one bag at a time. Thus, the following is a solution sequence that gives a minimum travel distance: $$$0 \to 2 \to 0 \to 4 \to 0 \to 3 \to 0 \to 1 \to 0 \to 5$$$, where each $$$0$$$ means you go the origin and grab one bag, and each positive integer means you deliver the bag to a depot at this coordinate, giving a total distance of $$$25$$$ units. It must be noted that there are other sequences that give the same distance.In the second test case, you can follow the following sequence, among multiple such sequences, to travel minimum distance: $$$0 \to 6 \to 8 \to 7 \to 0 \to 5 \to 4 \to 3 \to 0 \to (-5) \to (-10) \to (-15)$$$, with distance $$$41$$$. It can be shown that $$$41$$$ is the optimal distance for this test case.

package main

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

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := 0; i < t; i++ {
		solve()
	}
}
func solve() {
	n, k := ReadInt(), ReadInt()
	a := ReadInts(n)
	a1 := make([]int, 0)
	a2 := make([]int, 0)
	for _, v := range a {
		if v < 0 {
			a1 = append(a1, -v)
		} else if v > 0 {
			a2 = append(a2, v)
		}
	}

	max := 0
	ans := int64(0)
	for i := 0; i < 2; i++ {
		sort.Ints(a1)
		remain := k
		if len(a1)%k > 0 {
			remain = len(a1) % k
		}
		for _, v := range a1 {
			remain--
			if remain == 0 {
				ans += int64(v) * 2
				if max < v {
					max = v
				}
				remain = k
			}
		}
		if remain < k && len(a1) > 0 {
			v := a1[len(a1)-1]
			ans += int64(v) * 2
			if max < v {
				max = v
			}
		}
		a1, a2 = a2, a1
	}
	println(ans - int64(max))
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func ReadString() (s string) { fmt.Fscan(_r, &s); return }
func ReadInt() (i int)       { fmt.Fscan(_r, &i); return }
func ReadInts(n int) (a []int) {
	for ; n > 0; n-- {
		a = append(a, ReadInt())
	}
	return
}
func print(a ...interface{})   { fmt.Fprint(_w, a...) }
func println(a ...interface{}) { fmt.Fprintln(_w, a...) }
func prints(s []int)           { v := fmt.Sprint(s); println(v[1 : len(v)-1]) }

package main

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

const MOD int64 = 1000000007

var n, k int

var x[]int

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

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

func main() {

	read := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(read, &t)

	for i := 0; i < t; i++ {

		fmt.Fscan(read, &n, &k)

		x = make([]int, n)

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

		fmt.Println(solve())
	}
}

type pair struct {
	v int
	idx []int
}

func solve() int64 {

	var d int64

	var pos []int
	var neg []int

	for i := 0; i < n; i++ {
		if x[i] > 0 {
			pos = append(pos, x[i])
		}
		if x[i] < 0 {
			neg = append(neg, -x[i])
		}
	}

	sort.Ints(pos)
	sort.Ints(neg)

	for i := len(pos) - 1; i >= 0; i-=k {
		p := pos[i]

		d += int64(p)

		if i != len(pos) - 1 {
			d += int64(p)
		}
	}

	for i := len(neg) - 1; i >= 0; i-=k {
		p := neg[i]

		d += int64(p)

		if i != len(neg) - 1 {
			d += int64(p)
		}
	}

	if len(neg) > 0 && len(pos) > 0 {
		d += int64(min(neg[len(neg) - 1], pos[len(pos) - 1]))
	}

	return d
}

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

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

package main

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

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

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

func main() {
    defer output.Flush()
    //solve()
    //return
	var t int64
	fmt.Fscan(input, &t)
    for t > 0 {
        t--
        solve()
    }
}

type pair struct {a, b int}

func solve() {
    var n, k int
    fmt.Fscan(input, &n, &k)
    a, b := make([]int, 0), make([]int, 0)
    for i := 0; i < n; i++ {
        var t int
        fmt.Fscan(input, &t)
        if t > 0 {
            b = append(b, t)
        } else {
            a = append(a, abs(t))
        }
    }

    sort.Ints(a)
    sort.Ints(b)

    total := int64(0)
    ln := len(a)
    for ln > 0 {
        total += int64(2 * a[ln - 1])
        ln -= k
    }

    ln = len(b)
    for ln > 0 {
        total += int64(2 * b[ln - 1])
        ln -= k
    }

    if len(b) == 0 || (len(a) > 0 && a[len(a) - 1] > b[len(b) - 1]) {
        total -= int64(a[len(a) - 1])
    } else {
        total -= int64(b[len(b) - 1])
    }

    fmt.Fprintln(output, total)
}

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

package main

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

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := 0; i < t; i++ {
		solve()
	}
}
func solve() {
	n, k := ReadInt(), ReadInt()
	a := ReadInts(n)
	a1 := make([]int, 0)
	a2 := make([]int, 0)
	for _, v := range a {
		if v < 0 {
			a1 = append(a1, -v)
		} else if v > 0 {
			a2 = append(a2, v)
		}
	}

	max := 0
	ans := 0
	for i := 0; i < 2; i++ {
		sort.Ints(a1)
		remain := k
		if len(a1)%k > 0 {
			remain = len(a1) % k
		}
		for _, v := range a1 {
			remain--
			if remain == 0 {
				ans += v * 2
				if max < v {
					max = v
				}
				remain = k
			}
		}
		if remain < k && len(a1) > 0 {
			v := a1[len(a1)-1]
			ans += v * 2
			if max < v {
				max = v
			}
		}
		a1, a2 = a2, a1
	}
	println(ans - max)
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func ReadString() (s string) { fmt.Fscan(_r, &s); return }
func ReadInt() (i int)       { fmt.Fscan(_r, &i); return }
func ReadInts(n int) (a []int) {
	for ; n > 0; n-- {
		a = append(a, ReadInt())
	}
	return
}
func print(a ...interface{})   { fmt.Fprint(_w, a...) }
func println(a ...interface{}) { fmt.Fprintln(_w, a...) }
func prints(s []int)           { v := fmt.Sprint(s); println(v[1 : len(v)-1]) }


As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.

The first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n).

package main

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

// github.com/EndlessCheng/codeforces-go
func CF14D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, v, w, ans int
	Fscan(in, &n)
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	d := func(u, no int) (maxD int) {
		var f func(v, fa, d int)
		f = func(v, fa, d int) {
			if d > maxD {
				maxD = d
				u = v
			}
			for _, w := range g[v] {
				if w != fa && w != no {
					f(w, v, d+1)
				}
			}
		}
		maxD = -1
		f(u, -1, 0)
		maxD = -1
		f(u, -1, 0)
		return
	}
	var f func(v, fa int)
	f = func(v, fa int) {
		for _, w := range g[v] {
			if w != fa {
				if s := d(v, w) * d(w, v); s > ans {
					ans = s
				}
				f(w, v)
			}
		}
	}
	f(0, -1)
	Fprint(out, ans)
}

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

package main

// Solution for https://codeforces.com/problemset/problem/14/D

import "fmt"

var neighbors [][]int

type pair struct {
	i1, i2 int
}

var cache = make(map[pair]pair)

// Inspects subgraph connected to c2, but not c1.
// Returns the length of the longest path and the
// length of the longest path involving c2.
func longestPath(c1, c2 int) (resultMaxInternal, resultMaxConnected int) {
	if len(neighbors[c2]) == 1 {
		// c2 is only connected to c1.
		return 0, 0
	}
	if v, has := cache[pair{c1, c2}]; has {
		return v.i1, v.i2
	}
	maxInternal := 0
	maxConnected := 0
	nextMaxConnected := 0
	for _, c3 := range neighbors[c2] {
		if c3 == c1 {
			continue
		}
		internal, connected := longestPath(c2, c3)
		connected++
		if internal > maxInternal {
			maxInternal = internal
		}
		if connected > maxConnected {
			nextMaxConnected = maxConnected
			maxConnected = connected
		} else if connected > nextMaxConnected {
			nextMaxConnected = connected
		}
	}
	resultMaxConnected = maxConnected
	resultMaxInternal = maxInternal
	connection := maxConnected + nextMaxConnected
	if connection > resultMaxInternal {
		resultMaxInternal = connection
	}
	cache[pair{c1, c2}] = pair{resultMaxInternal, resultMaxConnected}
	return
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	neighbors = make([][]int, n)
	var edges []pair
	for i := 0; i < n-1; i++ {
		var c1, c2 int
		fmt.Scanf("%d %d\n", &c1, &c2)
		c1--
		c2--
		neighbors[c1] = append(neighbors[c1], c2)
		neighbors[c2] = append(neighbors[c2], c1)
		edges = append(edges, pair{c1, c2})
	}
	maxProduct := 0
	for _, edge := range edges {
		l1, _ := longestPath(edge.i1, edge.i2)
		l2, _ := longestPath(edge.i2, edge.i1)
		product := l1 * l2
		if product > maxProduct {
			maxProduct = product
		}
	}
	fmt.Println(maxProduct)
}


We define a spanning tree of a graph to be a BFS tree rooted at vertex $$$s$$$ if and only if for every node $$$t$$$ the shortest distance between $$$s$$$ and $$$t$$$ in the graph is equal to the shortest distance between $$$s$$$ and $$$t$$$ in the spanning tree. Given a graph, we define $$$f(x,y)$$$ to be the number of spanning trees of that graph that are BFS trees rooted at vertices $$$x$$$ and $$$y$$$ at the same time.You are given an undirected connected graph with $$$n$$$ vertices and $$$m$$$ edges. Calculate $$$f(i,j)$$$ for all $$$i$$$, $$$j$$$ by modulo $$$998\,244\,353$$$.

The first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n \le 400$$$, $$$0 \le m \le 600$$$) — the number of vertices and the number of edges in the graph. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i < b_i$$$), representing an edge connecting $$$a_i$$$ and $$$b_i$$$. It is guaranteed that all edges are distinct and the graph is connected.

Print $$$n$$$ lines, each consisting of $$$n$$$ integers. The integer printed in the row $$$i$$$ and the column $$$j$$$ should be $$$f(i,j) \bmod 998\,244\,353$$$.

NoteThe following picture describes the first example.The tree with red edges is a BFS tree rooted at both $$$1$$$ and $$$2$$$.Similarly, the BFS tree for other adjacent pairs of vertices can be generated in this way.

package main

import . "fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	var n, m, v, w int
	Scan(&n, &m)
	g := make([][]int, n)
	for ; m > 0; m-- {
		Scan(&v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}
	dis := make([][]int, n)
	for i := range dis {
		d := make([]int, n)
		for j := range d {
			d[j] = -1
		}
		d[i] = 0
		q := []int{i}
		for len(q) > 0 {
			v, q = q[0], q[1:]
			for _, w = range g[v] {
				if d[w] < 0 {
					d[w] = d[v] + 1
					q = append(q, w)
				}
			}
		}
		dis[i] = d
	}
	for i, d := range dis {
		for j, x := range d {
			c := make([]bool, n)
			m := int64(1)
			for k, y := range d {
				if k == i || k == j {
					continue
				}
				if y+dis[j][k] == x {
					if c[y] {
						m = 0
						break
					}
					c[y] = true
				} else {
					c := 0
					for _, w = range g[k] {
						if d[w]+1 == y && dis[j][w]+1 == dis[j][k] {
							c++
						}
					}
					m = m * int64(c) % 998244353
				}
			}
			Print(m, " ")
		}
		Println()
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	out := bufio.NewWriter(os.Stdout)
	var n, m, v, w int
	Scan(&n, &m)
	g := make([][]int, n)
	for ; m > 0; m-- {
		Scan(&v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}
	dis := make([][]int, n)
	for i := range dis {
		d := make([]int, n)
		for j := range d {
			d[j] = -1
		}
		d[i] = 0
		q := []int{i}
		for len(q) > 0 {
			v, q = q[0], q[1:]
			for _, w = range g[v] {
				if d[w] < 0 {
					d[w] = d[v] + 1
					q = append(q, w)
				}
			}
		}
		dis[i] = d
	}
	for i, d := range dis {
		for j, x := range d {
			c := make([]bool, n)
			m := int64(1)
			for k, y := range d {
				if k == i || k == j {
					continue
				}
				if y+dis[j][k] == x {
					if c[y] {
						m = 0
						break
					}
					c[y] = true
				} else {
					c := 0
					for _, w = range g[k] {
						if d[w]+1 == y && dis[j][w]+1 == dis[j][k] {
							c++
						}
					}
					m = m * int64(c) % 998244353
				}
			}
			Fprint(out, m, " ")
		}
		Fprintln(out)
	}
	out.Flush()
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1495D(_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)
	g := make([][]int, n)
	for ; m > 0; m-- {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}
	dis := make([][]int, n)
	for i := range dis {
		d := make([]int, n)
		for j := range d {
			d[j] = -1
		}
		d[i] = 0
		q := []int{i}
		for len(q) > 0 {
			v, q = q[0], q[1:]
			for _, w = range g[v] {
				if d[w] < 0 {
					d[w] = d[v] + 1
					q = append(q, w)
				}
			}
		}
		dis[i] = d
	}
	for i, d := range dis {
		for j, x := range d {
			c := make([]bool, n)
			m := int64(1)
			for k, y := range d {
				if k == i || k == j {
					continue
				}
				if y+dis[j][k] == x {
					if c[y] {
						m = 0
						break
					}
					c[y] = true
				} else {
					c := 0
					for _, w = range g[k] {
						if d[w]+1 == y && dis[j][w]+1 == dis[j][k] {
							c++
						}
					}
					m = m * int64(c) % 998244353
				}
			}
			Fprint(out, m, " ")
		}
		Fprintln(out)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	out := bufio.NewWriter(os.Stdout)
	var n, m, v, w int
	Scan(&n, &m)
	g := make([][]int, n)
	for ; m > 0; m-- {
		Scan(&v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}
	dis := make([][]int, n)
	for v = range dis {
		d := make([]int, n)
		for i := range d {
			d[i] = -1
		}
		d[v] = 0
		q := []int{v}
		for len(q) > 0 {
			v, q = q[0], q[1:]
			for _, w = range g[v] {
				if d[w] < 0 {
					d[w] = d[v] + 1
					q = append(q, w)
				}
			}
		}
		dis[v] = d
	}
	for i, d := range dis {
		for j, x := range d {
			c := make([]bool, n)
			m := int64(1)
			for k, y := range d {
				if k == i || k == j {
					continue
				}
				if y+dis[j][k] == x {
					if c[y] {
						m = 0
						break
					}
					c[y] = true
				} else {
					c := 0
					for _, w = range g[k] {
						if d[w]+1 == y && dis[j][w]+1 == dis[j][k] {
							c++
						}
					}
					m = m * int64(c) % 998244353
				}
			}
			Fprint(out, m, " ")
		}
		Fprintln(out)
	}
	out.Flush()
}


You are given a board of size $$$2 \times n$$$ ($$$2$$$ rows, $$$n$$$ columns). Some cells of the board contain chips. The chip is represented as '*', and an empty space is represented as '.'. It is guaranteed that there is at least one chip on the board.In one move, you can choose any chip and move it to any adjacent (by side) cell of the board (if this cell is inside the board). It means that if the chip is in the first row, you can move it left, right or down (but it shouldn't leave the board). Same, if the chip is in the second row, you can move it left, right or up.If the chip moves to the cell with another chip, the chip in the destination cell disappears (i. e. our chip captures it).Your task is to calculate the minimum number of moves required to leave exactly one chip on the board.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the board. The second line of the test case contains the string $$$s_1$$$ consisting of $$$n$$$ characters '*' (chip) and/or '.' (empty cell). The third line of the test case contains the string $$$s_2$$$ consisting of $$$n$$$ characters '*' (chip) and/or '.' (empty cell). Additional constraints on the input:   in each test case, there is at least one chip on a board;  the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print one integer — the minimum number of moves required to leave exactly one chip on the board.

package main

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

func acc(op func(int, int) int, c ...int) int {
	res := c[0]
	for _, i := range c {
		res = op(res, i)
	}
	return res
}

func max(c ...int) int {
	return acc(func(a int, b int) int {
		if a < b {
			return b
		}
		return a
	}, c...)
}

func min(c ...int) int {
	return acc(func(a int, b int) int {
		if a > b {
			return b
		}
		return a
	}, c...)
}

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

func btoI(a bool) int {
	if a {
		return 1
	}
	return 0
}

func solve(inout io.ReadWriter) {
	scan := func(inp ...interface{}) {
		fmt.Fscan(inout, inp...)
	}
	printf := func(format string, outp ...interface{}) {
		fmt.Fprintf(inout, format, outp...)
	}

	var n int
	var s [2]string
	scan(&n)
	scan(&s[0], &s[1])

	var pre, suf [2][]int
	pre[0] = make([]int, n+2)
	pre[1] = make([]int, n+2)
	suf[0] = make([]int, n+2)
	suf[1] = make([]int, n+2)

	left, right := 1, 1
	for i := 1; i <= n; i++ {
		if s[0][i-1] == '.' && s[1][i-1] == '.' {
			if left == i {
				left = i + 1
			}
		} else {
			right = i
		}
	}

	for j := left + 1; j <= n; j++ {
		for i := 0; i != 2; i++ {
			pre[i][j] = min(pre[i][j-1]+1+btoI(s[i^1][j-2] == '*'), pre[i^1][j-1]+2)
		}
	}

	for j := right - 1; j > 0; j-- {
		for i := 0; i != 2; i++ {
			suf[i][j] = min(suf[i][j+1]+1+btoI(s[i^1][j] == '*'), suf[i^1][j+1]+2)
		}
	}

	var ans int = math.MaxInt32
	for j := left; j <= right; j++ {
		for i := 0; i != 2; i++ {
			if s[i][j-1] == '*' {
				ans = min(ans, pre[i][j]+suf[i][j]+btoI(s[i^1][j-1] == '*'), pre[i^1][j]+suf[i^1][j]+1)
			}
		}
	}
	if ans == math.MaxInt32 {
		ans = 0
	}
	printf("%d\n", ans)
}

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

	var T int = 1
	fmt.Fscan(inout, &T)
	for ; T > 0; T-- {
		solve(inout)
	}
}

package main

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

func acc(op func(int, int) int, c ...int) int {
	res := c[0]
	for _, i := range c {
		res = op(res, i)
	}
	return res
}

func max(c ...int) int {
	return acc(func(a int, b int) int {
		if a < b {
			return b
		}
		return a
	}, c...)
}

func min(c ...int) int {
	return acc(func(a int, b int) int {
		if a > b {
			return b
		}
		return a
	}, c...)
}

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

func btoI(a bool) int {
	if a {
		return 1
	}
	return 0
}

func solve(inout io.ReadWriter) {
	scan := func(inp ...interface{}) {
		fmt.Fscan(inout, inp...)
	}
	printf := func(format string, outp ...interface{}) {
		fmt.Fprintf(inout, format, outp...)
	}

	var n int
	var s [2]string
	scan(&n)
	scan(&s[0], &s[1])

	var pre, suf [2][]int
	pre[0] = make([]int, n+2)
	pre[1] = make([]int, n+2)
	suf[0] = make([]int, n+2)
	suf[1] = make([]int, n+2)

	left, right := 1, 1
	for i := 1; i <= n; i++ {
		if s[0][i-1] == '.' && s[1][i-1] == '.' {
			if left == i-1 {
				left = i
			}
		} else {
			right = i
		}
	}

	for j := left + 1; j <= n; j++ {
		for i := 0; i != 2; i++ {
			pre[i][j] = min(pre[i][j-1]+1+btoI(s[i^1][j-2] == '*'), pre[i^1][j-1]+2)
		}

	}

	for j := right - 1; j > 0; j-- {
		for i := 0; i != 2; i++ {
			suf[i][j] = min(suf[i][j+1]+1+btoI(s[i^1][j] == '*'), suf[i^1][j+1]+2)
		}
	}

	var ans int = math.MaxInt32
	for j := left + 1; j <= right; j++ {
		for i := 0; i != 2; i++ {
			if s[i][j-1] == '*' {
				ans = min(ans, pre[i][j]+suf[i][j]+btoI(s[i^1][j-1] == '*'), pre[i^1][j]+suf[i^1][j]+1)
			}
		}
	}
	if ans == math.MaxInt32 {
		ans = 0
	}
	printf("%d\n", ans)
}

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

	var T int = 1
	fmt.Fscan(inout, &T)
	for ; T > 0; T-- {
		solve(inout)
	}
}

package main

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

func acc(op func(int, int) int, c ...int) int {
	res := c[0]
	for _, i := range c {
		res = op(res, i)
	}
	return res
}

func max(c ...int) int {
	return acc(func(a int, b int) int {
		if a < b {
			return b
		}
		return a
	}, c...)
}

func min(c ...int) int {
	return acc(func(a int, b int) int {
		if a > b {
			return b
		}
		return a
	}, c...)
}

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

func btoI(a bool) int {
	if a {
		return 1
	}
	return 0
}

func solve(inout io.ReadWriter) {
	scan := func(inp ...interface{}) {
		fmt.Fscan(inout, inp...)
	}
	printf := func(format string, outp ...interface{}) {
		fmt.Fprintf(inout, format, outp...)
	}

	var n int
	var s [2]string
	scan(&n)
	scan(&s[0], &s[1])

	var pre, suf [2][]int
	pre[0] = make([]int, n+2)
	pre[1] = make([]int, n+2)
	suf[0] = make([]int, n+2)
	suf[1] = make([]int, n+2)

	left, right := 1, 1
	for i := 1; i <= n; i++ {
		if s[0][i-1] == '.' && s[1][i-1] == '.' {
			if left == i-1 {
				left = i
			}
		} else {
			right = i
		}
	}

	for j := left + 1; j <= n; j++ {
		for i := 0; i != 2; i++ {
			pre[i][j] = min(pre[i][j-1]+1+btoI(s[i^1][j-2] == '*'), pre[i^1][j-1]+2)
		}

	}

	for j := right - 1; j > 0; j-- {
		for i := 0; i != 2; i++ {
			suf[i][j] = min(suf[i][j+1]+1+btoI(s[i^1][j] == '*'), suf[i^1][j+1]+2)
		}
	}

	var ans int = math.MaxInt32
	for j := left; j <= right; j++ {
		for i := 0; i != 2; i++ {
			if s[i][j-1] != '*' {
				continue
			}
			ans = min(ans, pre[i][j]+suf[i][j]+btoI(s[i^1][j-1] == '*'), pre[i^1][j]+suf[i^1][j]+1)
		}
	}
	if ans == math.MaxInt32 {
		ans = 0
	}
	printf("%d\n", ans)
}

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

	var T int = 1
	fmt.Fscan(inout, &T)
	for ; T > 0; T-- {
		solve(inout)
	}
}

package main

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

func acc(op func(int, int) int, c ...int) int {
	res := c[0]
	for _, i := range c {
		res = op(res, i)
	}
	return res
}

func max(c ...int) int {
	return acc(func(a int, b int) int {
		if a < b {
			return b
		}
		return a
	}, c...)
}

func min(c ...int) int {
	return acc(func(a int, b int) int {
		if a > b {
			return b
		}
		return a
	}, c...)
}

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

func btoI(a bool) int {
	if a {
		return 1
	}
	return 0
}

func solve(inout io.ReadWriter) {
	scan := func(inp ...interface{}) {
		fmt.Fscan(inout, inp...)
	}
	printf := func(format string, outp ...interface{}) {
		fmt.Fprintf(inout, format, outp...)
	}

	var n int
	var s [2]string
	scan(&n)
	scan(&s[0], &s[1])

	var pre, suf [2][]int
	pre[0] = make([]int, n+2)
	pre[1] = make([]int, n+2)
	suf[0] = make([]int, n+2)
	suf[1] = make([]int, n+2)

	left, right := 1, 1
	for i := 1; i <= n; i++ {
		if s[0][i-1] == '.' && s[1][i-1] == '.' {
			if left == i-1 {
				left = i
			}
		} else {
			right = i
		}
	}

	for j := left + 1; j <= n; j++ {
		for i := 0; i != 2; i++ {
			pre[i][j] = min(pre[i][j-1]+1+btoI(s[i^1][j-2] == '*'), pre[i^1][j-1]+2)
		}

	}

	for j := right - 1; j > 0; j-- {
		for i := 0; i != 2; i++ {
			suf[i][j] = min(suf[i][j+1]+1+btoI(s[i^1][j] == '*'), suf[i^1][j+1]+2)
		}
	}

	var ans int = math.MaxInt32
	for j := left; j <= right; j++ {
		for i := 0; i != 2; i++ {
			if s[i][j-1] != '*' {
				continue
			}
			ans = min(ans, pre[i][j]+suf[i][j]+btoI(s[i^1][j-1] == '*'), pre[i^1][j]+suf[i^1][j]+1)
		}
	}
	printf("%d\n", ans)
}

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

	var T int = 1
	fmt.Fscan(inout, &T)
	for ; T > 0; T-- {
		solve(inout)
	}
}

package main

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

func acc(op func(int, int) int, c ...int) int {
	res := c[0]
	for _, i := range c {
		res = op(res, i)
	}
	return res
}

func max(c ...int) int {
	return acc(func(a int, b int) int {
		if a < b {
			return b
		}
		return a
	}, c...)
}

func min(c ...int) int {
	return acc(func(a int, b int) int {
		if a > b {
			return b
		}
		return a
	}, c...)
}

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

func btoI(a bool) int {
	if a {
		return 1
	}
	return 0
}

func solve(inout io.ReadWriter) {
	scan := func(inp ...interface{}) {
		fmt.Fscan(inout, inp...)
	}
	printf := func(format string, outp ...interface{}) {
		fmt.Fprintf(inout, format, outp...)
	}

	var n int
	var s [2]string
	scan(&n)
	scan(&s[0], &s[1])

	var pre, suf [2][]int
	pre[0] = make([]int, n+2)
	pre[1] = make([]int, n+2)
	suf[0] = make([]int, n+2)
	suf[1] = make([]int, n+2)

	left, right := 1, 1
	for i := 1; i <= n; i++ {
		if s[0][i-1] == '.' && s[1][i-1] == '.' {
			if left == i-1 {
				left = i
			}
		} else {
			right = i
		}
	}

	for j := left + 1; j <= n; j++ {
		for i := 0; i != 2; i++ {
			pre[i][j] = min(pre[i][j-1]+1+btoI(s[i^1][j-2] == '*'), pre[i^1][j-1]+2)
		}

	}

	for j := right - 1; j > 0; j-- {
		for i := 0; i != 2; i++ {
			suf[i][j] = min(suf[i][j+1]+1+btoI(s[i^1][j] == '*'), suf[i^1][j+1]+2)
		}
	}

	var ans int = math.MaxInt32
	for j := left; j <= right; j++ {
		for i := 0; i != 2; i++ {
			if s[i][j-1] != '*' {
				continue
			}
			printf("%d %d %d %d\n", i, j, pre[i][j]+suf[i][j]+btoI(s[i^1][j-1] == '*'), pre[i^1][j]+suf[i^1][j]+1)
			ans = min(ans, pre[i][j]+suf[i][j]+btoI(s[i^1][j-1] == '*'), pre[i^1][j]+suf[i^1][j]+1)
		}
	}
	printf("%d\n", ans)
}

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

	var T int = 1
	fmt.Fscan(inout, &T)
	for ; T > 0; T-- {
		solve(inout)
	}
}

package main

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

func acc(op func(int, int) int, c ...int) int {
	res := c[0]
	for _, i := range c {
		res = op(res, i)
	}
	return res
}

func max(c ...int) int {
	return acc(func(a int, b int) int {
		if a < b {
			return b
		}
		return a
	}, c...)
}

func min(c ...int) int {
	return acc(func(a int, b int) int {
		if a > b {
			return b
		}
		return a
	}, c...)
}

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

func solve(inout io.ReadWriter) {
	scan := func(inp ...interface{}) {
		fmt.Fscan(inout, inp...)
	}
	printf := func(format string, outp ...interface{}) {
		fmt.Fprintf(inout, format, outp...)
	}

	var n int
	var s [2]string
	scan(&n)
	scan(&s[0], &s[1])

	var pre, suf [2][]int
	pre[0] = make([]int, n+2)
	pre[1] = make([]int, n+2)
	suf[0] = make([]int, n+2)
	suf[1] = make([]int, n+2)

	left, right := 1, 1
	for i := 1; i <= n; i++ {
		if s[0][i-1] == '.' && s[1][i-1] == '.' {
			if left == i-1 {
				left = i
			}
		} else {
			right = i
		}
	}

	for j := left + 1; j <= n; j++ {
		for i := 0; i != 2; i++ {
			p := pre[i][j-1] + 1
			if s[i^1][j-2] == '*' {
				p++
			}
			pre[i][j] = min(p, pre[i^1][j-1]+2)
		}

	}

	for j := right - 1; j > 0; j-- {
		for i := 0; i != 2; i++ {
			nx := suf[i][j+1] + 1
			if j < n && s[i^1][j] == '*' {
				nx++
			}
			suf[i][j] = min(nx, suf[i^1][j+1]+2)
		}
	}

	var ans int = math.MaxInt32
	for j := left; j <= right; j++ {
		for i := 0; i != 2; i++ {
			if s[i][j-1] != '*' {
				continue
			}
			sum := pre[i][j] + suf[i][j]
			if s[i^1][j-1] == '*' {
				sum++
			}
			ans = min(ans, sum, pre[i^1][j]+suf[i^1][j]+1)
		}
	}
	printf("%d\n", ans)
}

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

	var T int = 1
	fmt.Fscan(inout, &T)
	for ; T > 0; T-- {
		solve(inout)
	}
}


Ashish has an array $$$a$$$ of size $$$n$$$.A subsequence of $$$a$$$ is defined as a sequence that can be obtained from $$$a$$$ by deleting some elements (possibly none), without changing the order of the remaining elements.Consider a subsequence $$$s$$$ of $$$a$$$. He defines the cost of $$$s$$$ as the minimum between:   The maximum among all elements at odd indices of $$$s$$$.  The maximum among all elements at even indices of $$$s$$$. Note that the index of an element is its index in $$$s$$$, rather than its index in $$$a$$$. The positions are numbered from $$$1$$$. So, the cost of $$$s$$$ is equal to $$$min(max(s_1, s_3, s_5, \ldots), max(s_2, s_4, s_6, \ldots))$$$.For example, the cost of $$$\{7, 5, 6\}$$$ is $$$min( max(7, 6), max(5) ) = min(7, 5) = 5$$$.Help him find the minimum cost of a subsequence of size $$$k$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq k \leq n \leq 2 \cdot 10^5$$$)  — the size of the array $$$a$$$ and the size of the subsequence. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$)  — the elements of the array $$$a$$$.

Output a single integer  — the minimum cost of a subsequence of size $$$k$$$.

NoteIn the first test, consider the subsequence $$$s$$$ = $$$\{1, 3\}$$$. Here the cost is equal to $$$min(max(1), max(3)) = 1$$$.In the second test, consider the subsequence $$$s$$$ = $$$\{1, 2, 4\}$$$. Here the cost is equal to $$$min(max(1, 4), max(2)) = 2$$$.In the fourth test, consider the subsequence $$$s$$$ = $$$\{3, 50, 2, 4\}$$$. Here the cost is equal to $$$min(max(3, 2), max(50, 4)) = 3$$$.

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n, k := readTwoNums(reader)
	A := readNNums(reader, n)
	fmt.Println(solve(n, k, A))
}

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
}

const MAX_A = 1000000001

// 236411286

func solve(N, K int, A []int) int {

	count := func(parity int, x int) int {
		var j int
		for i := 0; i < N; i++ {
			if j&1 != parity || A[i] <= x {
				j++
			}
		}
		return j
	}

	check := func(x int) bool {
		return count(0, x) >= K || count(1, x) >= K
	}

	var left, right = 1, MAX_A

	for left < right {
		mid := (left + right) / 2
		if check(mid) {
			right = mid
		} else {
			left = mid + 1
		}
	}
	return right
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1370D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, k int
	Fscan(in, &n, &k)
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
	}
	f := func(c, up int) bool {
		for i := c; i < n; {
			for ; i < n && a[i] > up; i++ {
			}
			if i < n {
				c++
				i++
			}
			if i < n {
				c++
				i++
			}
		}
		return c >= k
	}
	Fprint(out, sort.Search(1e9, func(up int) bool { return f(0, up) || f(1, up) }))
}

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

package main

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

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

func main() {
	defer out.Flush()
	inn.Buffer([]byte{}, 10000000)
	inn.Split(bufio.ScanWords)
	//prep
	n, k := rd(), rd()
	a := make([]int, n)
	for i := range a {
		a[i] = rd()
	}
	l, r := 1, int(1e9)
	check := func(x, cur int) bool {
		var res int
		for _, it := range a {
			if cur == 0 || it <= x {
				res++
				cur ^= 1
			}
		}
		return res >= k
	}
	for l <= r {
		mid := (l + r) / 2
		if check(mid, 0) || check(mid, 1) {
			r = mid - 1
		} else {
			l = mid + 1
		}
	}
	Fprint(out, l)
}

//-------------------template------------------
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func maxll(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func minll(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func rd() (x int) {
	inn.Scan()
	x, _ = strconv.Atoi(string(inn.Bytes()))
	return x
}
func rdll() (x int64) {
	inn.Scan()
	x, _ = strconv.ParseInt(string(inn.Bytes()), 10, 64)
	return x
}
func rds() string {
	inn.Scan()
	return string(inn.Bytes())
}

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 n, k int
	con.Scan(&n, &k)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		con.Scan(&a[i])
	}
	hi := 1000000000
	lo := 1
	for hi > lo {
		mid := (hi + lo) / 2
		ok := false
		if !ok {
			j := 0
			for i := 0; i < n && j < k; i++ {
				if j%2 == 0 {
					if a[i] <= mid {
						j++
					}
				} else {
					j++
				}
			}
			ok = j == k
		}
		if !ok {
			j := 0
			for i := 0; i < n && j < k; i++ {
				if j%2 != 0 {
					if a[i] <= mid {
						j++
					}
				} else {
					j++
				}
			}
			ok = j == k
		}
		if ok {
			hi = mid
		} else if lo == mid {
			lo = mid + 1
		} else {
			lo = mid
		}
	}
	con.Println(lo)
	return nil
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n, k := readTwoNums(reader)
	A := readNNums(reader, n)
	fmt.Println(solve(n, k, A))
}

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
}

const MAX_A = 1000000001

func solve(N, K int, A []int) int {
	count := func(i int, x int) int {
		var cnt int
		for i < N {
			// from index 1, to make sure this arr is the less-half one
			if A[i] <= x {
				j := i
				for j < N && A[j] <= x {
					j++
				}
				cnt += (j - i + 1) / 2
				i = j - 1
			}
			i++
		}
		return cnt
	}

	check := func(x int) bool {
		//find a array of size H that <= x and not consective to each other
		cnt := count(1, x)
		if cnt >= K/2 {
			return true
		}
		if A[0] > x {
			return false
		}
		// consider A[0]
		cnt = count(0, x)
		return cnt >= (K+1)/2
	}

	var left, right = 1, MAX_A

	for left < right {
		mid := (left + right) / 2
		if check(mid) {
			right = mid
		} else {
			left = mid + 1
		}
	}
	return right
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n, k := readTwoNums(reader)
	A := readNNums(reader, n)
	fmt.Println(solve(n, k, A))
}

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
}

const MAX_A = 1000000001

// 236411286

func solve(N, K int, A []int) int {
	count := func(begin, end int, x int) int {
		var cnt int
		for i := begin; i < end; i++ {
			if A[i] <= x {
				j := i
				for j < N && A[j] <= x {
					j++
				}
				cnt += (j - i + 1) / 2
				i = j - 1
			}
		}
		return cnt
	}

	check := func(x int) bool {
		if K&2 == 0 {
			return count(0, N-1, x) >= K/2 || count(1, N, x) >= K/2
		}
		return count(0, N, x) >= (K+1)/2 || count(1, N-1, x) >= K/2
	}

	var left, right = 1, MAX_A

	for left < right {
		mid := (left + right) / 2
		if check(mid) {
			right = mid
		} else {
			left = mid + 1
		}
	}
	return right
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n, k := readTwoNums(reader)
	A := readNNums(reader, n)
	fmt.Println(solve(n, k, A))
}

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
}

const MAX_A = 1000000001

// 236411286

func solve(N, K int, A []int) int {
	count := func(begin, end int, x int) int {
		var cnt int
		for i := begin; i < end; i++ {
			if A[i] <= x {
				j := i
				for j < N && A[j] <= x {
					j++
				}
				cnt += (j - i + 1) / 2
				i = j - 1
			}
		}
		return cnt
	}

	check := func(x int) bool {
		cnt := count(0, N, x)
		if K&2 == 0 {
			return cnt >= K/2
		}
		if cnt >= (K+1)/2 {
			return true
		}
		return count(1, N-1, x) >= K/2
	}

	var left, right = 1, MAX_A

	for left < right {
		mid := (left + right) / 2
		if check(mid) {
			right = mid
		} else {
			left = mid + 1
		}
	}
	return right
}


Initially Ildar has an empty array. He performs $$$n$$$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset $$$[0, 2, 3]$$$ is $$$1$$$, while the mex of the multiset $$$[1, 2, 1]$$$ is $$$0$$$.More formally, on the step $$$m$$$, when Ildar already has an array $$$a_1, a_2, \ldots, a_{m-1}$$$, he chooses some subset of indices $$$1 \leq i_1 < i_2 < \ldots < i_k < m$$$ (possibly, empty), where $$$0 \leq k < m$$$, and appends the $$$mex(a_{i_1}, a_{i_2}, \ldots a_{i_k})$$$ to the end of the array.After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $$$a_1, a_2, \ldots, a_n$$$ the minimum step $$$t$$$ such that he has definitely made a mistake on at least one of the steps $$$1, 2, \ldots, t$$$, or determine that he could have obtained this array without mistakes.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — the number of steps Ildar made. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array Ildar obtained.

If Ildar could have chosen the subsets on each step in such a way that the resulting array is $$$a_1, a_2, \ldots, a_n$$$, print $$$-1$$$. Otherwise print a single integer $$$t$$$ — the smallest index of a step such that a mistake was made on at least one step among steps $$$1, 2, \ldots, t$$$.

NoteIn the first example it is possible that Ildar made no mistakes. Here is the process he could have followed.  $$$1$$$-st step. The initial array is empty. He can choose an empty subset and obtain $$$0$$$, because the mex of an empty set is $$$0$$$. Appending this value to the end he gets the array $$$[0]$$$.  $$$2$$$-nd step. The current array is $$$[0]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1]$$$.  $$$3$$$-rd step. The current array is $$$[0,1]$$$. He can choose a subset $$$[0,1]$$$ and obtain an integer $$$2$$$, because $$$mex(0,1) = 2$$$. Appending this value to the end he gets the array $$$[0,1,2]$$$.  $$$4$$$-th step. The current array is $$$[0,1,2]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1,2,1]$$$. Thus, he can get the array without mistakes, so the answer is $$$-1$$$.In the second example he has definitely made a mistake on the very first step, because he could not have obtained anything different from $$$0$$$.In the third example he could have obtained $$$[0, 1, 2]$$$ without mistakes, but $$$239$$$ is definitely wrong.

package main

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

func main() {
	r := bufio.NewReaderSize(os.Stdin, 100*1024*1024)
	nums := readInts(r, readInt(r))

	max := -1
	for i := 0; i < len(nums); i++ {
		if nums[i] >= 0 && nums[i] <= max + 1 {
			if nums[i] > max {
				max = nums[i]
			}
		} else {
			fmt.Print(i+1)
			return
		}
	}
	fmt.Print(-1)
}

func readString(reader *bufio.Reader, l int) string {
	sTemp := readLine(reader)
	if len(sTemp) < l {
		l = len(sTemp)
	}
	return sTemp[:l]
}

func readInt(reader *bufio.Reader) int {
	tmpInt, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)
	return int(tmpInt)
}

func readInts(reader *bufio.Reader, n int) []int {
	tmpInts := strings.Split(readLine(reader), " ")

	var result []int
	for i := 0; i < n; i++ {
		tmpInt, err := strconv.ParseInt(tmpInts[i], 10, 64)
		checkError(err)
		result = append(result, int(tmpInt))
	}
	return result
}

func readLine(reader *bufio.Reader) string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}

	return strings.TrimRight(string(str), "\r\n")
}

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

package main

import (
	"bufio"
	"os"
	"fmt"
)
var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

func main() {
	defer writer.Flush()
	var n int
	scanf("%d\n", &n)
	a := make([]int,n)
	for i := 0;i<n;i++ {
		scanf("%d ",&a[i])
	}
	if a[0] != 0 {
		printf("%d\n",1)
	} else {
		flag := true
		r := 0
		c := 0
		b := 0
		for i :=1;i<n;i++ {
			if a[i]>=0  && (a[i]<c-1 || a[i]>b+1) {
				flag = false
				r = i+1
				break
			} else {
				if a[i]<c {
					c = a[i]
				}
				if a[i]>b {
					b= a[i]
				}
			}
		}
		if flag {
			printf("%d\n",-1)
		} else {
			printf("%d\n",r)
		}
	}

}

package main

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

func main() {
	r := bufio.NewReaderSize(os.Stdin, 100*1024*1024)
	nums := readInts(r, readInt(r))

	max := -1
	for i := 0; i < len(nums); i++ {
		if nums[i] >= 0 && nums[i] <= max + 1 {
			if nums[i] > max {
				max = nums[i]
			}
		} else {
			fmt.Print(i+1)
			return
		}
	}
	fmt.Print(-1)
}

func readString(reader *bufio.Reader, l int) string {
	sTemp := readLine(reader)
	if len(sTemp) < l {
		l = len(sTemp)
	}
	return sTemp[:l]
}

func readInt(reader *bufio.Reader) int {
	tmpInt, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)
	return int(tmpInt)
}

func readInts(reader *bufio.Reader, n int) []int {
	l := readLine(reader)
	fmt.Println(l)
	tmpInts := strings.Split(l, " ")

	var result []int
	for i := 0; i < n; i++ {
		tmpInt, err := strconv.ParseInt(tmpInts[i], 10, 64)
		checkError(err)
		result = append(result, int(tmpInt))
	}
	return result
}

func readLine(reader *bufio.Reader) string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}

	return strings.TrimRight(string(str), "\r\n")
}

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}


Evlampiy has found one more cool application to process photos. However the application has certain limitations.Each photo i has a contrast vi. In order for the processing to be truly of high quality, the application must receive at least k photos with contrasts which differ as little as possible.Evlampiy already knows the contrast vi for each of his n photos. Now he wants to split the photos into groups, so that each group contains at least k photos. As a result, each photo must belong to exactly one group.He considers a processing time of the j-th group to be the difference between the maximum and minimum values of vi in the group. Because of multithreading the processing time of a division into groups is the maximum processing time among all groups.Split n photos into groups in a such way that the processing time of the division is the minimum possible, i.e. that the the maximum processing time over all groups as least as possible.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3·105) — number of photos and minimum size of a group. The second line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109), where vi is the contrast of the i-th photo.

Print the minimal processing time of the division into groups.

NoteIn the first example the photos should be split into 2 groups: [40, 50] and [110, 120, 130]. The processing time of the first group is 10, and the processing time of the second group is 20. Maximum among 10 and 20 is 20. It is impossible to split the photos into groups in a such way that the processing time of division is less than 20.In the second example the photos should be split into four groups, each containing one photo. So the minimal possible processing time of a division is 0.

package main

import "sort"

// =============================================================================
// BEGIN template
// =============================================================================
import (
  "fmt"
  "bufio"
  "os"
)

// io
var stdin *bufio.Reader
var stdout *bufio.Writer
func fastio() {
  stdin = bufio.NewReader(os.Stdin)
  stdout = bufio.NewWriter(os.Stdout)
}
func scan(buf ...interface{}) {
  for _, a := range buf {
    fmt.Fscan(stdin, a)
  }
}
func dbg(x ...interface{}) {
  if os.Getenv("LOCAL") != "true" {
    return
  }
  fmt.Fprint(os.Stderr, ">>>>")
  for _, a := range x {
    fmt.Fprint(os.Stderr, " ", a)
  }
  fmt.Fprintln(os.Stderr)
}

// helpers
func min(x, y int64) int64 {
  if x < y {
    return x
  }
  return y
}

// constants
const oo int64  = 0x3f3f3f3f3f3f3f3f
const LGN int   = 25
const MOD int   = 1e9+7
const N int     = 3e5+5
// =============================================================================
// END template
// =============================================================================

var n, k int
var v, psum [N]int

func rangeSum(l, r int) int {
  if r < l {
    return 0
  }
  left := 0
  if l > 0 {
    left = psum[l-1]
  }
  return psum[r]-left
}

func solve(x int) bool {
  ans := false
  j := 0
  for i := k; i <= n; i++ {
    ans = false
    psum[i] = psum[i-1]
    if v[i]-v[i-k+1] > x {
      continue
    }
    for j <= n && v[i]-v[j] > x {
      j++
    }
    ans = rangeSum(j-1, i-k) > 0
    if ans {
      psum[i]++
    }
  }
  return ans
}

func find(l, r int) int {
  if r < l {
    return -1
  }
  m := (l+r)>>1
  if !solve(m) {
    return find(m+1,r)
  }
  ans := find(l,m-1)
  if ans < 0 {
    ans = m
  }
  return ans
}

func main() {
  fastio()

  scan(&n,&k)
  for i := 0; i < k; i++ {
    psum[i] = 1
  }
  for i := 1; i <= n; i++ {
    scan(&v[i])
  }
  sort.Ints(v[1:n+1])
  fmt.Fprintln(stdout, find(0,1e9))

  stdout.Flush()
}

package main

import "sort"

// =============================================================================
// BEGIN template
// =============================================================================
import (
  "fmt"
  "bufio"
  "os"
)

// io
var stdin *bufio.Reader
var stdout *bufio.Writer
func fastio() {
  stdin = bufio.NewReader(os.Stdin)
  stdout = bufio.NewWriter(os.Stdout)
}
func scan(buf ...interface{}) {
  for _, a := range buf {
    fmt.Fscan(stdin, a)
  }
}
func dbg(x ...interface{}) {
  if os.Getenv("LOCAL") != "true" {
    return
  }
  fmt.Fprint(os.Stderr, ">>>>")
  for _, a := range x {
    fmt.Fprint(os.Stderr, " ", a)
  }
  fmt.Fprintln(os.Stderr)
}

// helpers
func min(x, y int64) int64 {
  if x < y {
    return x
  }
  return y
}

// constants
const oo int64  = 0x3f3f3f3f3f3f3f3f
const LGN int   = 25
const MOD int   = 1e9+7
const N int     = 2e5+5
// =============================================================================
// END template
// =============================================================================

var n, k int
var v, psum [N]int

func rangeSum(l, r int) int {
  if r < l {
    return 0
  }
  left := 0
  if l > 0 {
    left = psum[l-1]
  }
  return psum[r]-left
}

func solve(x int) bool {
  ans := false
  j := 0
  for i := k; i <= n; i++ {
    psum[i] = psum[i-1]
    if v[i]-v[i-k+1] > x {
      continue
    }
    for j <= n && v[i]-v[j] > x {
      j++
    }
    ans = rangeSum(j-1, i-k) > 0
    if ans {
      psum[i]++
    }
  }
  return ans
}

func find(l, r int) int {
  if r < l {
    return -1
  }
  m := (l+r)>>1
  if !solve(m) {
    return find(m+1,r)
  }
  ans := find(l,m-1)
  if ans < 0 {
    ans = m
  }
  return ans
}

func main() {
  fastio()

  scan(&n,&k)
  for i := 0; i < k; i++ {
    psum[i] = 1
  }
  for i := 1; i <= n; i++ {
    scan(&v[i])
  }
  sort.Ints(v[1:n+1])
  fmt.Fprintln(stdout, find(0,1e9))

  stdout.Flush()
}