You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers.

For each query print one integer: the answer to this query.

package main

import "fmt"

func main() {
	var n, l, r, d int
	fmt.Scan(&n)
	for ; n > 0; n-- {
		fmt.Scan(&l, &r, &d)
		if d < l {
			fmt.Println(d)
		} else {
			fmt.Println((r/d + 1) * d)
		}
	}
}

package main

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

type LRD struct {
	L, R, D uint64
}

type CaseInput struct {
	lrds []LRD
}

func readCaseInput(scanner *bufio.Scanner) CaseInput {
	size := readInt(scanner)
	nums := make([]LRD, size)
	for i := range nums {
		nums[i] = LRD{
			uint64(readInt64(scanner)),
			uint64(readInt64(scanner)),
			uint64(readInt64(scanner)),
		}
	}
	in := CaseInput{nums}
	return in
}

type caseOutput struct {
	xs []uint64
}

func writeCaseOutput(writer *bufio.Writer, out caseOutput) {
	for _, x := range out.xs {
		writef(writer, "%d\n", x)
	}
}

func solveCase(in CaseInput) caseOutput {
	xs := make([]uint64, len(in.lrds))
	for i, lrd := range in.lrds {
		if lrd.L <= lrd.D {
			xs[i] = lrd.R + lrd.D - (lrd.R % lrd.D)
		} else {
			xs[i] = lrd.D
		}
	}
	return caseOutput{xs}
}

func solveSequential(scanner *bufio.Scanner, writer *bufio.Writer) {
	writeCaseOutput(writer, solveCase(readCaseInput(scanner)))
}

func main() {
	var scanner *bufio.Scanner
	if len(os.Args) > 1 {
		reader, err := os.Open(os.Args[1])
		if err != nil {
			panic(err)
		}
		defer reader.Close()
		scanner = bufio.NewScanner(reader)
	} else {
		scanner = bufio.NewScanner(os.Stdin)
	}
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)

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

	solveSequential(scanner, writer)
}

func readInt64(sc *bufio.Scanner) int64 {
	if !sc.Scan() {
		panic("failed to scan next token")
	}

	res, err := strconv.ParseInt(sc.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}

func readInt(sc *bufio.Scanner) int {
	return int(readInt64(sc))
}

func writef(writer *bufio.Writer, formatStr string, values ...interface{}) {
	out := fmt.Sprintf(formatStr, values...)
	_, err := writer.WriteString(out)
	if err != nil {
		panic(err)
	}
}

package main

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

func main() {
	start := time.Now()
	defer func() {
		run := time.Since(start)
		_ = run
		// fmt.Println("Run in", run)
	}()

	var stdin *bufio.Reader
	// LOCAL
	f, _ := os.Open("input.txt")
	stdin = bufio.NewReader(f)

	// ONLINE JUDGE
	stdin = bufio.NewReader(os.Stdin)

	var l, r, d, n int64
	fmt.Fscan(stdin, &n)

	for n > 0 {
		n--
		fmt.Fscan(stdin, &l, &r, &d)

		if l <= d && d <= r {
			var tmp = r / d
			d = d + tmp*d
		}
		fmt.Println(d)
	}
}

package main

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

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

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

func init() {
	// const maxCapacity = SIZE
	// buf := make([]byte, maxCapacity)
	// scanner.Buffer(buf, maxCapacity)
	scanner.Split(bufio.ScanWords)
}

func main() {
	defer writer.Flush()

	n := ReadInt()

	for ; n > 0; n-- {
		l,r,d := int64(ReadInt()), int64(ReadInt()), int64(ReadInt())

		if d < l {
			writer.WriteString(strconv.FormatInt(d, 10))
    		writer.WriteString("\n")
    		continue
		}

		var ans int64

		ans = int64((r/d) + 1)

    	writer.WriteString(strconv.FormatInt(d*ans, 10))
    	writer.WriteString("\n")
	}

}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n := readOneInt64(reader)
	for i := int64(0); i < n; i++ {
		tmpSlice := readInt64Slice(reader, 3)
		l, r, d := tmpSlice[0], tmpSlice[1], tmpSlice[2]
		if l > d {
			fmt.Println(d)
			continue
		} else {
			fmt.Println(((r+d)/d)*d)
		}
	}
}

func readOneInt64(r *bufio.Reader) (n int64) {
	bytes, _ := r.ReadBytes('\n')
	n, _ = strconv.ParseInt(string(bytes[:len(bytes)-2]), 10, 64)
	return
}

func readInt64Slice(r *bufio.Reader, n int) (slice []int64) {
	var bytes []byte
	slice = make([]int64, n)
	n--
	for i := 0; i < n; i++ {
		bytes, _ = r.ReadBytes(' ')
		slice[i], _ = strconv.ParseInt(string(bytes[:len(bytes)-1]), 10, 64)
	}
	slice[n] = readOneInt64(r)
	return
}

func readOneString(r *bufio.Reader) []byte {
	bytes, _ := r.ReadBytes('\n')
	return bytes[:len(bytes)-2]
}

package main

import "fmt"

func main() {
	var n, l, r, d int
	fmt.Scan(&n)
	for ; n > 0; n-- {
		fmt.Scan(&l, &r, &d)
		fmt.Println((r/d + 1) * d)
	}
}


This is the easy version of the problem. The only difference is that in this version $$$k = 0$$$.There is an array $$$a_1, a_2, \ldots, a_n$$$ of $$$n$$$ positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square.Moreover, it is allowed to do at most $$$k$$$ such operations before the division: choose a number in the array and change its value to any positive integer. But in this version $$$k = 0$$$, so it is not important.What is the minimum number of continuous segments you should use if you will make changes optimally?

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$k = 0$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^7$$$). It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

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

NoteIn the first test case the division may be as follows:  $$$[18, 6]$$$  $$$[2, 4]$$$  $$$[1]$$$

package main

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

const N = 1e7 + 7
const mod = 1e9 + 7

var spf [N]int

func getOddFactors(x int) string {
	var s string
	var lst []int
	mp := make(map[int]int)
	for x != 1 {
		mp[spf[x]]++
		x /= spf[x]
	}
	for k, v := range mp {
		if v%2 == 1 {
			lst = append(lst, k)
		}
	}
	sort.Ints(lst)
	for i := 0; i < len(lst); i++ {
		s += Itoa(lst[i]) + ","
	}
	return s
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	for i := 1; i < N; i++ {
		spf[i] = i
	}
	for i := 2; i < N; i += 2 {
		spf[i] = 2
	}
	for i := 3; i*i < N; i++ {
		if spf[i] == i {
			for j := i * i; j < N; j += i {
				if spf[j] == j {
					spf[j] = i
				}
			}
		}
	}
	var T int
	Fscan(in, &T)
	for T > 0 {
		ans := 1
		var n, k int
		Fscan(in, &n, &k)
		mp := make(map[string]int)
		for i := 0; i < n; i++ {
			var x int
			Fscan(in, &x)
			s := getOddFactors(x)
			if mp[s] == 1 {
				ans++
				mp = make(map[string]int)
			}
			mp[s]++
		}
		T--
		Fprintln(out, ans)
	}
}

package main

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

const N = 1e7 + 7
const mod = 1e9 + 7

var spf [N]int

func getOddFactors(x int) int {
	c := 1
	mp := make(map[int]int)
	for x != 1 {
		mp[spf[x]]++
		x /= spf[x]
	}
	for k, v := range mp {
		if v%2 == 1 {
			c *= k
		}
	}
	return c
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	for i := 1; i < N; i++ {
		spf[i] = i
	}
	for i := 2; i < N; i += 2 {
		spf[i] = 2
	}
	for i := 3; i*i < N; i++ {
		if spf[i] == i {
			for j := i * i; j < N; j += i {
				if spf[j] == j {
					spf[j] = i
				}
			}
		}
	}
	var T int
	Fscan(in, &T)
	for T > 0 {
		ans := 1
		var n, k int
		Fscan(in, &n, &k)
		mp := make(map[int]int)
		for i := 0; i < n; i++ {
			var x int
			Fscan(in, &x)
			s := getOddFactors(x)
			if mp[s] == 1 {
				ans++
				mp = make(map[int]int)
			}
			mp[s]++
		}
		T--
		Fprintln(out, ans)
	}
}

package main

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

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

	const mx int = 1e7
	lpf := make([]int, mx+1)
	lpf[1] = 1
	for i := 2; i <= mx; i++ {
		if lpf[i] == 0 {
			for j := i; j <= mx; j += i {
				if lpf[j] == 0 {
					lpf[j] = i
				}
			}
		}
	}
	core := func(x int) int {
		c := 1
		for x > 1 {
			p := lpf[x]
			e := 1
			for x /= p; lpf[x] == p; x /= p {
				e ^= 1
			}
			if e > 0 {
				c *= p
			}
		}
		return c
	}

	solve := func(Case int) {
		var n, k int
		Fscan(in, &n, &k)
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
			a[i] = core(a[i])
		}
		ans := 0
		for i := 0; i < n; {
			has := map[int]bool{}
			for ; i < n && !has[a[i]]; i++ {
				has[a[i]] = true
			}
			ans++
		}
		Fprintln(out, ans)
	}

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

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

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

package main

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

const N = 1e7 + 7
const mod = 1e9 + 7

var spf [N]int

func getOddFactors(x int) string {
	var s string
	mp := make(map[int]int)
	for x != 1 {
		mp[spf[x]]++
		x /= spf[x]
	}
	for k, v := range mp {
		if v%2 == 1 {
			s += Itoa(k)
		}
	}
	return s
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	for i := 1; i < N; i++ {
		spf[i] = i
	}
	for i := 2; i < N; i += 2 {
		spf[i] = 2
	}
	for i := 3; i*i < N; i++ {
		if spf[i] == i {
			for j := i * i; j < N; j += i {
				if spf[j] == j {
					spf[j] = i
				}
			}
		}
	}
	var T int
	Fscan(in, &T)
	for T > 0 {
		ans := 1
		var n, k int
		Fscan(in, &n, &k)
		mp := make(map[string]int)
		for i := 0; i < n; i++ {
			var x int
			Fscan(in, &x)
			s := getOddFactors(x)
			if mp[s] == 1 {
				ans++
				mp = make(map[string]int)
			}
			mp[s]++
		}
		T--
		Fprintln(out, ans)
	}
}

package main

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

const N = 1e7 + 7
const mod = 1e9 + 7

var spf [N]int

func getOddFactors(x int) string {
	var s string
	mp := make(map[int]int)
	for x != 1 {
		mp[spf[x]]++
		x /= spf[x]
	}
	for k, v := range mp {
		if v%2 == 1 {
			s += Itoa(k) + ","
		}
	}
	return s
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	for i := 1; i < N; i++ {
		spf[i] = i
	}
	for i := 2; i < N; i += 2 {
		spf[i] = 2
	}
	for i := 3; i*i < N; i++ {
		if spf[i] == i {
			for j := i * i; j < N; j += i {
				if spf[j] == j {
					spf[j] = i
				}
			}
		}
	}
	var T int
	Fscan(in, &T)
	for T > 0 {
		ans := 1
		var n, k int
		Fscan(in, &n, &k)
		mp := make(map[string]int)
		for i := 0; i < n; i++ {
			var x int
			Fscan(in, &x)
			s := getOddFactors(x)
			if mp[s] == 1 {
				ans++
				mp = make(map[string]int)
			}
			mp[s]++
		}
		T--
		Fprintln(out, ans)
	}
}

package main

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

const N = 1e7 + 7
const mod = 1e9 + 7

var spf [N]int

func getOddFactors(x int) string {
	var s string
	mp := make(map[int]int)
	for x != 1 {
		mp[spf[x]]++
		x /= spf[x]
	}
	for k, v := range mp {
		if v%2 == 1 {
			s += Itoa(spf[k]) + ","
		}
	}
	return s
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	for i := 1; i < N; i++ {
		spf[i] = i
	}
	for i := 2; i < N; i += 2 {
		spf[i] = 2
	}
	for i := 3; i*i < N; i++ {
		if spf[i] == i {
			for j := i * i; j < N; j += i {
				if spf[j] == j {
					spf[j] = i
				}
			}
		}
	}
	var T int
	Fscan(in, &T)
	for T > 0 {
		ans := 1
		var n, k int
		Fscan(in, &n, &k)
		mp := make(map[string]int)
		for i := 0; i < n; i++ {
			var x int
			Fscan(in, &x)
			s := getOddFactors(x)
			if mp[s] == 1 {
				ans++
				mp = make(map[string]int)
			}
			mp[s]++
		}
		T--
		Fprintln(out, ans)
	}
}


Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:  There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.  The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.  After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.  The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.Write the code that calculates for each knight, the name of the knight that beat him.

The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight. It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.

Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.

NoteConsider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.

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

func main() {
	var knights,fight int
	var l, h, w int
	var prev,next,result [300100]int
	input := bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&knights,&fight)
	for i:=0;i<=knights;i++ {
		prev[i]=i-1
		next[i]=i+1
		result[i]=0
	}
	for i:=0;i<fight;i++ {
		input.Scan()
		aa,_:=strconv.Atoi(input.Text())
		l=aa
		input.Scan()
		bb,_:=strconv.Atoi(input.Text())
		h=bb
		input.Scan()
		cc,_:=strconv.Atoi(input.Text())
		w=cc
		for ;next[w]<=h;{
			result[next[w]]=w
			next[w]=next[next[w]]
		}
		prev[next[w]]=w
		for ;prev[w]>=l;{
			result[prev[w]]=w
			prev[w]=prev[prev[w]]
		}
		next[prev[w]]=w
	}
	out:=bufio.NewWriter(os.Stdout)
	for i:=1; i<=knights;i++ {
		out.WriteString(strconv.Itoa(result[i])+" ")
	}
	//out.WriteString("\n")
	out.Flush()
}

package main

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

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

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

    var n,m,l,r,x int
    ScanInts(&n,&m)
    a, next := make([]int,n+1), make([]int,n+1)
    for i := 1; i <= n; i++ { next[i] = i+1 }
    for i := 0; i < m; i++ {
        ScanInts(&l,&r,&x)
        for j, nextj := l, next[l]; j <= r; j = nextj {
            nextj = next[j]
            if (j != x) && (a[j] == 0) {
                a[j] = x
            }
            if (j < x) { next[j] = x } else { next[j] = r+1 }
        }
    }

    for i := 1; i <= n; i++ {
        writer.WriteString(strconv.Itoa(a[i]))
        if i == n { writer.WriteRune('\n') } else { writer.WriteRune(' ') }
    }
    writer.Flush()
}

// 356A-mic
package main

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

var r, l, winner [300005]int
var n, m, left, right, x int

func dfsl(left, lm, x int) {
	if left < lm {
		r[left] = x
		l[x] = left
		return
	}
	winner[left] = x
	dfsl(l[left], lm, x)
}

func dfsr(right, rm, x int) {
	if right > rm {
		l[right] = x
		r[x] = right
		return
	}
	winner[right] = x
	dfsr(r[right], rm, x)
}

func main() {
	z := bufio.NewReader(os.Stdin)
	ou := bufio.NewWriter(os.Stdout)
	fmt.Fscan(z, &n, &m)
	for i := 1; i <= n; i++ {
		l[i] = i - 1
		r[i] = i + 1
	}
	for ; m > 0; m-- {
		fmt.Fscan(z, &left, &right, &x)
		dfsl(l[x], left, x)
		dfsr(r[x], right, x)
	}
	for i := 1; i <= n; i++ {
		fmt.Fprint(ou, winner[i], " ")
	}
	ou.Flush()
	fmt.Println()
}


You are given a permutation p of length n. Also you are given m foe pairs (ai, bi) (1 ≤ ai, bi ≤ n, ai ≠ bi). Your task is to count the number of different intervals (x, y) (1 ≤ x ≤ y ≤ n) that do not contain any foe pairs. So you shouldn't count intervals (x, y) that contain at least one foe pair in it (the positions and order of the values from the foe pair are not important).Consider some example: p = [1, 3, 2, 4] and foe pairs are {(3, 2), (4, 2)}. The interval (1, 3) is incorrect because it contains a foe pair (3, 2). The interval (1, 4) is also incorrect because it contains two foe pairs (3, 2) and (4, 2). But the interval (1, 2) is correct because it doesn't contain any foe pair.

The first line contains two integers n and m (1 ≤ n, m ≤ 3·105) — the length of the permutation p and the number of foe pairs. The second line contains n distinct integers pi (1 ≤ pi ≤ n) — the elements of the permutation p. Each of the next m lines contains two integers (ai, bi) (1 ≤ ai, bi ≤ n, ai ≠ bi) — the i-th foe pair. Note a foe pair can appear multiple times in the given list.

Print the only integer c — the number of different intervals (x, y) that does not contain any foe pairs. Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

NoteIn the first example the intervals from the answer are (1, 1), (1, 2), (2, 2), (3, 3) and (4, 4).

package main

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

const MAXN = 300006

var arr[MAXN] int
var pos[MAXN] int
var nxt[MAXN] int

func addFoe(n,f int) {
	n = pos[n]
	f = pos[f]
	if n >= f {return}
	if nxt[n] > f-1 {nxt[n] = f-1}
}

func main() {
	var N,M,i,x,y int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &N, &M)
	for i=1; i<=N; i++ {
		fmt.Fscan(in, &arr[i])
		pos[arr[i]] = i
		nxt[i] = N
	}
	for ; M>0; M-- {
		fmt.Fscan(in, &x, &y)
		addFoe(x,y)
		addFoe(y,x)
	}
	last := N
	for i=N-1; i>=1; i-- {
		if nxt[i] < last {last = nxt[i]}
		nxt[i] = last
	}
	var ans int64
	for i,ans=1,0; i<=N; i++ {
		ans += int64(nxt[i]-i+1)
	}
	fmt.Printf("%d\n", ans)
}

package main

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

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

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

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

  n, m := getI(), getI()
  values := make([]int, n)
  positions := make([]int, n + 1)
  for i := range values {
    values[i] = getI()
    positions[values[i]] = i
  }
  rightToLeft := make([]int, n)
  for i := 0; i < n; i++ {
    rightToLeft[i] = -1
  }
  for i := 0; i < m; i++ {
    a, b := positions[getI()], positions[getI()]
    if b < a {
      a, b = b, a
    }
    if a > rightToLeft[b] {
      rightToLeft[b] = a
    }
  }

  result := int64(0)
  left, right, seek := 0, 0, -1
  for right < n {
    for right + 1 < n {
      seek = rightToLeft[right + 1]
      if seek < left {
        right++
      } else {
        break
      }
    }
    for left <= seek {
      result += int64(right - left + 1)
      left++
    }
    right++
  }
  for left < n {
    result += int64(n - left)
    left++
  }

  writer.WriteString(fmt.Sprintf("%d\n", result))
}


Bob watches TV every day. He always sets the volume of his TV to $$$b$$$. However, today he is angry to find out someone has changed the volume to $$$a$$$. Of course, Bob has a remote control that can change the volume.There are six buttons ($$$-5, -2, -1, +1, +2, +5$$$) on the control, which in one press can either increase or decrease the current volume by $$$1$$$, $$$2$$$, or $$$5$$$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $$$0$$$.As Bob is so angry, he wants to change the volume to $$$b$$$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $$$a$$$ and $$$b$$$, finds the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 1\,000$$$). Then the descriptions of the test cases follow. Each test case consists of one line containing two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^{9}$$$) — the current volume and Bob's desired volume, respectively.

For each test case, output a single integer — the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$. If Bob does not need to change the volume (i.e. $$$a=b$$$), then print $$$0$$$.

NoteIn the first example, Bob can press the $$$-2$$$ button twice to reach $$$0$$$. Note that Bob can not press $$$-5$$$ when the volume is $$$4$$$ since it will make the volume negative. In the second example, one of the optimal ways for Bob is to press the $$$+5$$$ twice, then press $$$-1$$$ once.In the last example, Bob can press the $$$+5$$$ once, then press $$$+1$$$.

package main

import (
    "fmt"
)

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

func main() {
	var a, b, n int;

	fmt.Scanf("%d\n", &n);
	for i := 0; i < n; i++ {
		fmt.Scanf("%d %d\n", &a, &b);
		ans := abs(a - b) / 5 + abs(a - b) % 5 / 2 + abs(a - b) % 5 % 2;
		fmt.Println(ans);
	}

}

package main

import (
	"fmt"
)

func main() {
	var n, a,b int
	fmt.Scan(&n)
	for i:=0;i<n;i++ {
		fmt.Scan(&a,&b)
		c := b-a
		if c < 0 {
			c = -c
		}
		k := c/5
		if c%5 == 1 || c%5 == 2 {
			k++
		} else if c%5 >= 3 {
			k+=2
		}
		fmt.Println(k)
	}
}

package main
import "fmt"
func main() {
	var t int
	fmt.Scanln(&t)

	for i := 0; i < t; i++ {
		var a, b int
		fmt.Scanln(&a, &b)
		// a-5, a-2, a-1, a+1, a+2, a+5
		press := 0
		for a != b {
			if a > b {
				if a-5 >= b {
					c := (a - b) / 5
					press += c
					a = a - (5 * c)
				} else if a-2 >= b {
					c := (a - b) / 2
					press += c
					a = a - (2 * c)
				} else if a-1 >= b {
					c := (a - b) / 1
					press += c
					a = a - (1 * c)
				}
			} else if a < b {
				if a+5 <= b {
					c := (b - a) / 5
					press += c
					a = a + (5 * c)
				} else if a+2 <= b {
					c := (b - a) / 2
					press += c
					a = a + (2 * c)
				} else if a+1 <= b {
					c := (b - a)
					press += c
					a = a + (1 * c)
				}
			}
		}
		fmt.Println(press)
	}
}

package main

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

var scanner *bufio.Scanner

func init() {
	scanner = bufio.NewScanner(bufio.NewReader(os.Stdin))
	//scanner.Buffer(make([]byte, 311000), 311000)
	scanner.Split(bufio.ScanWords)
}

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

func nextInt() int {
	txt := next()
	num, err := strconv.Atoi(txt)
	if err != nil {
		panic(fmt.Errorf("Atoi(%q) returned error: %v", txt, err))
	}
	return num
}

func nextLong() int64 {
	txt := next()
	num, err := strconv.ParseInt(txt, 10, 64)
	if err != nil {
		panic(fmt.Errorf("ParseInt(%q, 10, 64) returned error: %v", txt, err))
	}
	return num
}

// ========================================================

func main() {
	numCases := nextInt()
	for caseNum := 1; caseNum <= numCases; caseNum++ {
		a, b := nextInt(), nextInt()
		total := 0
		if a < b {
			p5 := (b - a) / 5
			total += p5
			a += 5 * p5
			dif := b - a
			if dif == 3 || dif == 4 {
				total += 2
			} else if dif == 2 || dif == 1 {
				total += 1
			}
		} else if a > b {
			pm5 := (b - a) / -5
			total += pm5
			a -= 5 * pm5
			dif := a - b
			if dif == 1 || dif == 2 {
				total += 1
			} else if dif == 3 || dif == 4 {
				total += 2
			}
		}
		fmt.Println(total)
	}
}

package main

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

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

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

// a < b
func solve(from, to int) int {
	delta := to - from
	if delta < 0 {
		delta = -delta
	}
	rst := 0
	rst += delta / 5
	delta = delta % 5
	if delta > 0 {
		rst += delta / 2
		delta = delta % 2
		rst += delta
	}

	return rst
}

func main() {
	defer writer.Flush()
	n := 0
	scanf("%d\n", &n)
	for i := 0; i < n; i++ {
		a := 0
		b := 0
		scanf("%d %d\n", &a, &b)
		printf("%d\n", solve(a, b))
	}
}

package main

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

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

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

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

	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
}

/*********** DP sub-functions ***********/

// ChMin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// ChMax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

/********** 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 MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var t int
var a, b int

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		a, b = ReadInt2()

		solve()
	}
}

func solve() {
	diff := AbsInt(b - a)
	ans := 0
	ans += diff / 5
	diff %= 5
	ans += diff / 2
	diff %= 2
	ans += diff

	fmt.Println(ans)
}

/*
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
*/

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

package main

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

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

	var t, a, b int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &a, &b)
		d := b - a
		if d < 0 {
			d = -d
		}
		Fprintln(out, d/5+(d%5+1)/2)
	}
}

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

package main

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

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

	var t, a, b int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &a, &b)
		d := b - a
		if d < 0 {
			d = -d
		}
		ans := d / 5
		d %= 5
		if d == 1 || d == 2 {
			ans++
		} else if d == 3 || d == 4 {
			ans += 2
		}
		Fprintln(out, ans)
	}
}

func main() {
	Sol1255A(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();

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

	var a, b int
	for i := 0; i < t; i++ {
		fmt.Fscan(in, &a, &b)

		diff := a-b
		if diff < 0 {
			diff *= -1
		}

		cnt := diff / 5
		diff %= 5
		if diff == 1 || diff == 2 {
			cnt += 1
		} else if diff == 3 || diff == 4 {
			cnt += 2
		}

		fmt.Fprintln(out, cnt)
	}
}

package main

import (
	"fmt"
)

// a < b
func solve(from, to int) int {
	delta := to - from
	if delta < 0 {
		delta = -delta
	}
	rst := 0
	rst += delta / 5
	delta = delta % 5
	if delta > 0 {
		rst += delta / 2
		delta = delta % 2
		rst += delta
	}

	return rst
}

func main() {
	n := 0
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		a := 0
		b := 0
		fmt.Scanf("%d %d", &a, &b)
		fmt.Printf("%d\n", solve(a, b))
	}
}


You are given a bracket sequence $$$s$$$ of length $$$n$$$, where $$$n$$$ is even (divisible by two). The string $$$s$$$ consists of $$$\frac{n}{2}$$$ opening brackets '(' and $$$\frac{n}{2}$$$ closing brackets ')'.In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $$$i$$$, remove the $$$i$$$-th character of $$$s$$$ and insert it before or after all remaining characters of $$$s$$$).Your task is to find the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.Recall what the regular bracket sequence is:  "()" is regular bracket sequence;  if $$$s$$$ is regular bracket sequence then "(" + $$$s$$$ + ")" is regular bracket sequence;  if $$$s$$$ and $$$t$$$ are regular bracket sequences then $$$s$$$ + $$$t$$$ is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) — the length of $$$s$$$. It is guaranteed that $$$n$$$ is even. The second line of the test case containg the string $$$s$$$ consisting of $$$\frac{n}{2}$$$ opening and $$$\frac{n}{2}$$$ closing brackets.

For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.

NoteIn the first test case of the example, it is sufficient to move the first bracket to the end of the string.In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())".

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

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

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("in.txt")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

	var t, n int
	var arr []byte
	scanf("%d", &t)

	for ; t > 0; t-- {
		scanf("\n%d", &n)
		scanf("\n%s", &arr)

		c, res := 0, 0
		for _, v := range arr {
			if v == '(' {
				c++
			} else {
				c--
			}
			res = min(res, c)
		}

		printf("%d\n", -res)
	}
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		var x int
		fmt.Scan(&x)
		var s string
		fmt.Scan(&s)
		cnt := 0
		ans := 0
		for j := 0; j < len(s); j++ {
			if s[j] == '(' {
				cnt++
			} else {
				if cnt <= 0 {
					ans++
					cnt = 0
					continue
				}
				cnt--
			}
		}
		fmt.Println(ans)
	}
}

package main

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

var read *bufio.Reader = bufio.NewReader(os.Stdin)
var write *bufio.Writer = bufio.NewWriter(os.Stdout)

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

func main() {
	defer write.Flush()
	var t int
	fmt.Fscan(read, &t)
	for ; t > 0; t-- {
		var n int
		var str string
		fmt.Fscan(read, &n)
		fmt.Fscan(read, &str)
		var zuo, you, ans = 0, 0, 0
		for i := 0; i < len(str); i++ {
			if str[i] == '(' {
				zuo++
			} else {
				you++
			}
			if ans < you - zuo {
				ans = you - zuo
			}
		}
		fmt.Fprintln(write, ans)
	}
}

package main

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

var read *bufio.Reader = bufio.NewReader(os.Stdin)
var write *bufio.Writer = bufio.NewWriter(os.Stdout)

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

func main() {
	defer write.Flush()
	var t int
	fmt.Fscan(read, &t)
	for ; t > 0; t-- {
		var n int
		var str string
		fmt.Fscan(read, &n)
		fmt.Fscan(read, &str)
		var zuo, you, ans = 0, 0, 0
		for i := 0; i < n; i++ {
			if str[i] == '(' {
				zuo++
			} else {
				you++
			}
			if ans < you - zuo {
				ans = you - zuo
			}
		}
		fmt.Fprintln(write, ans)
	}
}

package main

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

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

	for tc > 0 {
		tc--
		n := readNum(reader)
		s, _ := reader.ReadString('\n')
		fmt.Println(solve(n, s))
	}
}

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, s string) int {
	var res int
	var open int
	for i := 0; i < n; i++ {
		if s[i] == '(' {
			open++
		} else {
			open--
		}
		if open < 0 {
			// move it to end
			open = 0
			res++
		}
	}
	return res
}

package main

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

func main() {
	nCases := 0
	bufIO := bufio.NewReader(os.Stdin)
	fmt.Scanln(&nCases)

	for i := 0; i < nCases; i++ {
		n, brackets := 0, ""
		fmt.Fscan(bufIO, &n, &brackets)

		stack, reminder := 0, 0
		for iCh := 0; iCh < len(brackets); iCh++ {
			//fmt.Println(iCh)
			if brackets[iCh] == '(' {
				stack++
			} else {
				if stack > 0 {
					stack--
				} else {
					reminder++
				}
			}
		}
		fmt.Println(reminder)
	}
}

package main

import (
	"fmt"
)

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

	for t > 0 {
		var (
			s string
			n int
		)

		fmt.Scan(&n)
		fmt.Scan(&s)

		curBal, minBal := 0, 0

		for _, c := range s {
			if c == '(' {
				curBal++
			} else {
				curBal--
			}

			if curBal < minBal {
				minBal = curBal
			}
		}

		fmt.Println(-minBal)

		t--
	}
}

package main

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

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

	var t int
	var s string

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

	for t > 0 {
		t--
		scanner.Scan()

		scanner.Scan()
		s = scanner.Text()

		count := 0
		shift := 0

		for _, c := range s {
			if c == ')' {
				count--
				if count < 0 {
					count = 0
					shift++
				}
			} else {
				count++
			}
		}

		fmt.Println(shift)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(in, &n)
		str := ""
		fmt.Fscan(in, &str)
		wrongClose := 0
		opened := 0
		for j := 0; j < n; j++ {
			if str[j] == '(' {
				opened++
			} else {
				if opened > 0 {
					opened--
				} else {
					wrongClose++
				}
			}
		}
		fmt.Println(wrongClose)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		var n int
		var s string
		fmt.Scan(&n, &s)
		sum := 0
		min_sum := 0
		for _, c := range s {
			switch c{
			case '(':
				sum += 1;
			case ')':
				sum -= 1;
			}
			if sum < min_sum {
				min_sum = sum
			}
		}
		fmt.Printf("%d\n", -min_sum)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		var n int
		var s string
		fmt.Scan(&n)
		fmt.Scan(&s)
		sum := 0
		min_sum := 0
		for j := 0; j < n; j++ {
			if s[j] == '(' {
				sum = sum + 1
			} else {
				sum = sum - 1
			}
			if sum < min_sum {
				min_sum = sum
			}
		}
		fmt.Printf("%d\n", -min_sum)
	}
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		n, _ := strconv.Atoi(string(line))
		line = readLine(reader)
		moves := 0
		l := 0
		for i := 0; i < n; i++ {
			if line[i] == '(' {
				l++
			}
			if line[i] == ')' {
				if l > 0 {
					l--
				} else {
					moves++
				}
			}
		}
		fmt.Println(moves)
	}
}

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 (
	"fmt"
)

func main() {
	var t int
	fmt.Scanf("%d\n", &t)

	for i := 0; i < t; i++ {
		var n int
		var s string
		fmt.Scanf("%d\n", &n)
		fmt.Scanf("%s\n", &s)

		count := 0
		ans := 0
		for j := 0; j < n; j++ {
			if s[j] == '(' {
				count++
			} else if s[j] == ')' {
				if count <= 0 {
					ans++
					continue
				}
				count--
			}
		}

		fmt.Println(ans)
	}
}

package main

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

var nTest, n int
var s string

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, &s)

		cnt := 0
		for i := 0; i < n; i++ {
			if s[i] == ')' && cnt > 0 {
				cnt--
			}

			if s[i] == '(' {
				cnt++
			}
		}
		fmt.Fprintln(out, cnt)
	}

	out.Flush()
}

package main

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

func min(a, b int) int {
	return int(math.Min(float64(a), float64(b)))
}

func max(a, b int) int {
	return int(math.Max(float64(a), float64(b)))
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscanf(in, "%v\n", &t)
	for now := 0; now < t; now++ {
		var n int
		var s string
		fmt.Fscanf(in, "%v\n", &n)
		fmt.Fscanf(in, "%v\n", &s)
		mas := make([]int, n)
		state := 0
		for ind, i := range s {
			if i == rune('(') {
				state++
			} else {
				state--
			}
			mas[ind] = state
		}
		ans := 0
		//fmt.Fprintln(out, mas)
		for _, i := range mas{
			if math.Abs(float64(i)) > float64(ans) && i < 0{
				ans = int(math.Abs(float64(i)))
			}
		}
		fmt.Fprintln(out, ans)

	}
	return
}

// https://codeforces.com/contest/1374/problem/C
package main

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

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

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

func main() {
	defer writer.Flush()

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

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

		moved := 0
		sum := 0
		for i := 0; i < len(s); i++ {
			if s[i] == '(' {
				sum++
			} else {
				if sum == 0 {
					moved++
				} else {
					sum--
				}
			}
		}

		printf("%d\n", moved)
	}
}

package main

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

func main() {
	t := NextInt()
	for t > 0 {
		t--
		NextInt()
		s := Next()
		st := make([]byte, 0)
		for i := 0; i < len(s); i++ {
			if s[i] == '(' {
				st = append(st, s[i])
			} else if len(st) > 0 && st[len(st)-1] == '(' {
				st = st[:len(st)-1]
			} else {
				st = append(st, s[i])
			}
		}
		fmt.Println(len(st)/2)
	}
}

var sc = bufio.NewScanner(os.Stdin)

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

func Next() string {
	sc.Scan()
	return sc.Text()
}

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

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

package main

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

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

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

	var n int64
	var s string
	for ; t > 0; t-- {
		fmt.Fscanf(reader, "%d\n%s\n", &n, &s)
		num := 0
		left := 0

		for i := 0; i < len(s); i++ {
			if s[i] == '(' {
				left++
			} else {
				if left > 0 {
					left--
				} else {
					num++
				}
			}
		}

		fmt.Println(num)

	}
}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

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

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

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

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

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

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

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

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

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

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

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

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

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

func sol(s string) int64 {
	m := map[rune]int64{}
	ret := int64(0)
	for _, r := range s {
		m[r]++
		ret = max(ret, m[')']-m['('])
	}
	return ret
}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

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

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

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

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

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

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

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

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

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

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

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

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

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

func sol(s string) int64 {
	left := int64(0)
	for i := 0; i < len(s); i++ {
		if s[i] == ')' {
			left++
		} else {
			break
		}
	}
	right := int64(0)
	for i := len(s)-1; i > -1; i-- {
		if s[i] == '(' {
			right++
		} else {
			break
		}
	}
	return max(left, right)
}


A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter tij units of time.Order is important everywhere, so the painters' work is ordered by the following rules:  Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j + 1)-th painter (if j < n);  each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on;  each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest;  as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. Given that the painters start working at time 0, find for each picture the time when it is ready for sale.

The first line of the input contains integers m, n (1 ≤ m ≤ 50000, 1 ≤ n ≤ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 ≤ tij ≤ 1000), where tij is the time the j-th painter needs to work on the i-th picture.

Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.

package main

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

func main(){
	var m, n int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	m, _ = strconv.Atoi(r.Text())
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	var a, t [5]int
	for i:=0; i<m; i++ {
		for j:=0; j<n; j++ {
			r.Scan()
			a[j], _ = strconv.Atoi(r.Text())
			if j == 0 {
				t[j] += a[j]
			} else {
				if t[j] < t[j-1] {
					t[j] = t[j-1]+a[j]
				} else {
					t[j] += a[j]
				}
			}
		}
		w.WriteString(strconv.Itoa(t[n-1])+" ")
	}
	w.WriteString("\n")
	w.Flush()
}

package main

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

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

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

    var m, n int
    line, _ := bio.ReadString('\n')
    line = strings.Replace(line, "\r\n", "", -1)
    x := strings.Split(string(line)," ")

    m, _ = strconv.Atoi(x[0])
    n, _ = strconv.Atoi(x[1])

    var a [50010][6]int
    for i := 1; i <= m; i++ {
        line, _ := bio.ReadString('\n')
        line = strings.Replace(line, "\r\n", "", -1)
        x := strings.Split(string(line)," ")
        for j := 1; j <= n; j++ {
            a[i][j], _ = strconv.Atoi(x[j-1])
            a[i][j] = max(a[i][j-1], a[i-1][j]) + a[i][j]
        }
    }

    for i := 1; i <= m; i++ {
        fmt.Printf("%d ", a[i][n])
    }
}

// 416B
package main

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

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var x, y int
	var p, t [7]int
	fmt.Fscan(in, &x, &y)
	for i := 0; i < x; i++ {
		for j := 1; j <= y; j++ {
			fmt.Fscan(in, &t[j])
		}
		for j := 1; j <= y; j++ {
			p[j] = max(p[j-1]+t[j], p[j]+t[j])
		}
		fmt.Println(p[y])
	}
}

// 416B-mic
package main

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

func main() {
	var m, n, i, j int
	var mat [50001][5]int
	z := bufio.NewReader(os.Stdin)
	fmt.Scan(&m, &n)
	for i = 0; i < m; i++ {
		for j = 0; j < n; j++ {
			fmt.Fscan(z, &mat[i][j])
			if i == 0 && j != 0 {
				mat[i][j] += mat[i][j-1]
			} else if i != 0 {
				if j == 0 {
					mat[i][j] += mat[i-1][j]
				} else {
					mat[i][j] += int(math.Max(float64(mat[i][j-1]), float64(mat[i-1][j])))
				}
			}
		}
	}
	for i = 0; i < m; i++ {
		fmt.Print(mat[i][n-1])
		fmt.Print(" ")
	}
	fmt.Println()
}

package main

import (
    "fmt"
)

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

func main() {
    var m, n int
    fmt.Scanf("%d %d", &m, &n)

    var a [50000][5]int
    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            fmt.Scanf("%d ", &a[i][j])
        }
    }

    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            a[i][j] = max(a[i][j-1], a[i-1][j]) + a[i][j]
        }
    }

    for i := 1; i <= m; i++ {
        fmt.Printf("%d ", a[i][n])
    }
}

package main

import (
    "fmt"
)

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

func main() {
    var m, n int
    fmt.Scanf("%d %d", &m, &n)

    var a [50000][5]int
    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            fmt.Scanf("%d", &a[i][j])
        }
    }

    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            a[i][j] = max(a[i][j-1], a[i-1][j]) + a[i][j]
        }
    }

    for i := 1; i <= m; i++ {
        fmt.Printf("%d ", a[i][n])
    }
}

package main

import (
    "fmt"
)

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

func main() {
    var m, n int
    fmt.Scanf("%d%d", &m, &n)

    var a [50000][5]int
    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            fmt.Scanf("%d", &a[i][j])
        }
    }

    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            a[i][j] = max(a[i][j-1], a[i-1][j]) + a[i][j]
        }
    }

    for i := 1; i <= m; i++ {
        fmt.Printf("%d ", a[i][n])
    }
}

package main

import (
    "fmt"
)

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

func main() {
    var m, n int
    fmt.Scanf("%d", &m)
    fmt.Scanf("%d", &n)

    var a [50000][5]int
    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            fmt.Scanf("%d", &a[i][j])
        }
    }

    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            a[i][j] = max(a[i][j-1], a[i-1][j]) + a[i][j]
        }
    }

    for i := 1; i <= m; i++ {
        fmt.Printf("%d ", a[i][n])
    }
}

package main

import (
    "fmt"
)

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

func main() {
    var m, n int
    fmt.Scanf("%d %d ", &m, &n)

    var a [50000][5]int
    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            fmt.Scanf("%d", &a[i][j])
        }
    }

    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            a[i][j] = max(a[i][j-1], a[i-1][j]) + a[i][j]
        }
    }

    for i := 1; i <= m; i++ {
        fmt.Printf("%d ", a[i][n])
    }
}

package main

import (
    "fmt"
)

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

func main() {
    var m, n int
    fmt.Scanf("%d %d ", &m, &n)

    var a [50000][5]int
    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            fmt.Scanf("%d ", &a[i][j])
        }
    }

    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            a[i][j] = max(a[i][j-1], a[i-1][j]) + a[i][j]
        }
    }

    for i := 1; i <= m; i++ {
        fmt.Printf("%d ", a[i][n])
    }
}


Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.

The first line of input contains a single integer n (1 ≤ n ≤ 500) — the number of gemstones. The second line contains n space-separated integers, the i-th of which is ci (1 ≤ ci ≤ n) — the color of the i-th gemstone in a line.

Print a single integer — the minimum number of seconds needed to destroy the entire line.

NoteIn the first sample, Genos can destroy the entire line in one second.In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.

package main

import "fmt"

var stones [505]int
var cache [505][505]int

func getRemovals(start int, end int) (r int) {
	if cache[start][end] > 0 {
		return cache[start][end]
	}

	minValue := 2000000000

	// Base case: if there are 2 elements and they're the same value.
	if start == end-1 && stones[start] == stones[end] {
		return 1
	}

	// Base case: single element.
	if start == end {
		return 1
	}

	// Skip this choice
	if start+1 <= end {
		minValue = getRemovals(start+1, end) + 1
	}

	if stones[start] == stones[start+1] && start+2 <= end {
		res := getRemovals(start+2, end) + 1
		if res < minValue {
			minValue = res
		}
	}

	for i := start + 2; i < end; i++ {
		if stones[start] == stones[i] {
			// Possible palindrome, recursively determine.
			res := getRemovals(start+1, i-1) + getRemovals(i+1, end)
			if res < minValue {
				minValue = res
			}
		}
	}

	if stones[start] == stones[end] {
		res := getRemovals(start+1, end-1)
		if res < minValue {
			minValue = res
		}
	}

	cache[start][end] = minValue
	return minValue
}

func main() {
	var numStones int
	_, err := fmt.Scanf("%d\n", &numStones)
	if err != nil {
		panic(err)
	}

	for i := 0; i < numStones; i++ {
		_, err := fmt.Scanf("%d", &(stones[i]))
		if err != nil {
			panic(err)
		}
	}

	fmt.Println(getRemovals(0, numStones-1))
}

package main

import "fmt"

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

func main() {
	var n int
	var c[510] int
	fmt.Scan( &n)
	for i := 1; i<= n; i++{
		fmt.Scan(&c[i])
	}
	var f[510][510] int
	for i := 1; i <= n; i++{
		f[i][i] = 1
		for j := i + 1; j <= n; j++{
			f[i][j] = n
		}
	}
	for k := 1; k < n; k++{
		for i := 1; i +k <= n; i++{
			j := i + k
			f[i][j] = min(f[i][j], 1 + f[i + 1][j])
			if c[i] == c[i + 1]{
				f[i][j] = min(f[i][j], 1 + f[i + 2][j])
			}
			for kk := i + 2; kk <= j; kk++{
				if c[i] == c[kk]{
					f[i][j] = min(f[i][j], f[i + 1][kk - 1] + f[kk + 1][j])
				}
			}
			//fmt.Println(i, j, f[i][j])
		}
	}
	fmt.Println(f[1][n])
}

package main

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

const (
	MAX_N = 505
)

var N int
var A []int
var dp [MAX_N][MAX_N]int

func memo(L, R int) int {
	if L > R {
		return 0
	}
	if L == R {
		return 1
	}
	if dp[L][R] >= 0 {
		return dp[L][R]
	}
	var res int
	res = 1 << 20
	if A[L] == A[R] {
		if L+1 == R {
			res = 1
		} else {
			res = memo(L+1, R-1)
		}
	}
	for i := L; i < R; i++ {
		tmp := memo(L, i) + memo(i+1, R)
		if tmp < res {
			res = tmp
		}
	}
	dp[L][R] = res
	return res
}

func main() {
	fsc := NewScanner()
	N = fsc.NextInt()
	for i := 0; i < N; i++ {
		A = append(A, fsc.NextInt())
	}
	fmt.Println(memo(0, N-1))
}

func init() {
	for i := 0; i < MAX_N; i++ {
		for j := 0; j < MAX_N; j++ {
			dp[i][j] = -1
		}
	}

}

//template
type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}


All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of $$$n\cdot m$$$ different seals, denoted by distinct numbers. All of them were written in an $$$n\times m$$$ table.The table is lost now. Naruto managed to remember elements of each row from left to right, and elements of each column from top to bottom, but he doesn't remember the order of rows and columns. Please restore the table consistent with this data so that Naruto will be able to learn the new technique.

The first line of the input contains the only integer $$$t$$$ ($$$1\leq t\leq 100\,000$$$) denoting the number of test cases. Their descriptions follow. The first line of each test case description consists of two space-separated integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 500$$$) standing for the number of rows and columns in the table, respectively. All hand seals are encoded by the positive integers from $$$1$$$ to $$$n\cdot m$$$. The following $$$n$$$ lines contain $$$m$$$ space separated integers each, denoting elements of an arbitrary row in the table left to right. The following $$$m$$$ lines contain $$$n$$$ space separated integers each, denoting elements of an arbitrary column in the table top to bottom. Sum of $$$nm$$$ over all test cases does not exceed $$$250\,000$$$. It is guaranteed that each row occurs in the input exactly once, as well as each column. It is also guaranteed that each number from $$$1$$$ to $$$nm$$$ occurs exactly once in all rows, as well as in all columns. Finally, it is guaranteed that a table consistent with the input exists.

For each test case, output $$$n$$$ lines with $$$m$$$ space-separated integers each, denoting the restored table. One can show that the answer is always unique.

NoteConsider the first test case. The matrix is $$$2 \times 3$$$. You are given the rows and columns in arbitrary order.One of the rows is $$$[6, 5, 4]$$$. One of the rows is $$$[1, 2, 3]$$$.One of the columns is $$$[1, 6]$$$. One of the columns is $$$[2, 5]$$$. One of the columns is $$$[3, 4]$$$.You are to reconstruct the matrix. The answer is given in the output.

package main

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

func main() {
	io := bufio.NewReader(os.Stdin)
	var t, n, m, elementOfFirstColumn, input int
	var ok bool
	fmt.Fscan(io, &t)

	for i:=0; i<t; i++{
		ok = false
		fmt.Fscan(io, &n, &m)
		rows := make([][]int, n)
		column := make([]int, n)
		for i:=0; i<n; i++ {
			rows[i] = make([]int, m)
			for j:=0; j<m; j++{
				fmt.Fscan(io, &rows[i][j])
				if i == 0 && j == 0 {
					elementOfFirstColumn = rows[0][0]
				}
			}
		}
		for i:=0; i<m; i++ {
			if ok {
				for j:=0; j<n; j++{
					fmt.Fscan(io, &input)
				}
			} else {
				for j:=0; j<n; j++{
					fmt.Fscan(io, &input)
					column[j] = input
					if input == elementOfFirstColumn{
						ok = true
					}
				}
			}
		}
		for _, firstElement := range column{

			for _, row := range rows {
				if firstElement == row[0] {
					for _, rowElement := range row {
						fmt.Printf("%d ", rowElement)
					}
					fmt.Printf("\n")
				}
			}
		}
	}
}

package main

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

func main() {
	defer _w.Flush()
	T := ReadInt()
	for t := 0; t < T; t++ {
		n, m := ReadInt(), ReadInt()
		a := make([][]int, n)
		for i := 0; i < n; i++ {
			a[i] = ReadInts(m)
		}
		b := make([][]int, m)
		for i := 0; i < m; i++ {
			b[i] = ReadInts(n)
		}
		matrix := solve(n, m, a, b)
		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				if j > 0 {
					print(" ")
				}
				printf("%d", matrix[i][j])
			}
			println()
		}
	}
}

func solve(n, m int, a, b [][]int) [][]int {
	c := make([]int, n*m)
	r := make([]int, n*m)

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			v := a[i][j] - 1
			c[v] = j
		}
	}
	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			v := b[i][j] - 1
			r[v] = j
		}
	}

	matrix := make([][]int, n)
	for i := 0; i < n; i++ {
		matrix[i] = make([]int, m)
	}

	for v := 0; v < n*m; v++ {
		matrix[r[v]][c[v]] = v + 1
	}
	return matrix
}

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

func print(a ...interface{})            { fmt.Fprint(_w, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(_w, f, a...) }
func println(a ...interface{})          { fmt.Fprintln(_w, a...) }
func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(_r, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) (a []int) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt())
	}
	return
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int) (a []int64) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt64())
	}
	return
}

package main

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

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
}

func Next() string {
	sc.Scan()
	return sc.Text()
}

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

type Pos struct {
	x, y int
}

func main() {
	for tt := NextInt(); tt > 0; tt-- {
		n, m := NextInt(), NextInt()
		arr := make([]Pos, n * m + 1)
		ret := make([][]int, n)
		for i := 0; i < n; i++ {
			ret[i] = make([]int, m)
		}
 		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				arr[NextInt()].y = j
			}
		}
		for i := 0; i < m; i++ {
			for j := 0; j < n; j++ {
				arr[NextInt()].x = j
			}
		}
		for i := 1; i <= n * m; i++ {
			ret[arr[i].x][arr[i].y] = i
		}
		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				fmt.Printf("%d ", ret[i][j])
			}
			fmt.Println()
		}
	}
}

package main

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

func main() {
	//rd, _ := os.Open("input")
	//io := bufio.NewReader(rd)
	io := bufio.NewReader(os.Stdin)

	var t, n, m, elem int
	var matrix [][]int

	fmt.Fscan(io, &t)
	for ; t > 0; t-- {
		fmt.Fscan(io, &n, &m)
		matrix = make([][]int, n)

		for i := 0; i < n; i++ {
			matrix[i] = make([]int, m)
			for j := 0; j < m; j++ {
				fmt.Fscan(io, &elem)
				matrix[i][j] = elem
			}
		}
		column := -1
		for i := 0; i < n; i++ {
			fmt.Fscan(io, &elem)
			if column < 0 {
				for k1 := 0; k1 < n; k1++ {
					for k2 := 0; k2 < m; k2++ {
						if matrix[k1][k2] == elem {
							column = k2
							break
						}
					}
					if column > 0 {
						break
					}
				}
			}
			for k := i; k < n; k++ {
				if matrix[k][column] == elem {
					matrix[i], matrix[k] = matrix[k], matrix[i]
				}
			}
		}
		for i := 0; i < m; i++ {
			io.ReadLine()
		}
		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				fmt.Printf("%d ", matrix[i][j])
			}
			fmt.Println()
		}
	}
}

package main

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

func configure(scanner *bufio.Scanner) {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 1000005), 1000005)
}
func getNextString(scanner *bufio.Scanner) string {
	scanned := scanner.Scan()
	if !scanned {
		panic("scan failed")
	}
	return scanner.Text()
}
func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}
func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}
func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}
func main() {
	fp := os.Stdin
	wfp := os.Stdout
	extra := 0
	if os.Getenv("I") == "IronMan" {
		fp, _ = os.Open(os.Getenv("END_GAME"))
		extra = 100
	}
	scanner := bufio.NewScanner(fp)
	configure(scanner)
	writer := bufio.NewWriter(wfp)
	defer func() {
		r := recover()
		if r != nil {
			fmt.Fprintln(writer, r)
		}
		writer.Flush()
	}()
	solve(scanner, writer)
	for i := 0; i < extra; i++ {
		fmt.Fprintln(writer, "-----------------------------------")
		solve(scanner, writer)
	}
}
func solve(scanner *bufio.Scanner, writer *bufio.Writer) {
	t := getNextInt(scanner)
	for t > 0 {
		t--
		func() {
			n := getNextInt(scanner)
			m := getNextInt(scanner)
			ans := make([][2]int, n*m)
			for i := 0; i < n; i++ {
				for j := 0; j < m; j++ {
					k := getNextInt(scanner) - 1
					ans[k][1] = j
				}
			}
			for i := 0; i < m; i++ {
				for j := 0; j < n; j++ {
					k := getNextInt(scanner) - 1
					ans[k][0] = j
				}
			}
			correct := makeGrid(n, m)
			for i := 0; i < n*m; i++ {
				correct[ans[i][0]][ans[i][1]] = i + 1
			}
			for i := 0; i < n; i++ {
				sep := ""
				for j := 0; j < m; j++ {
					fmt.Fprintf(writer, "%s%d", sep, correct[i][j])
					sep = " "
				}
				fmt.Fprintln(writer, "")
			}
		}()
	}
}
func makeGrid(h, w int) [][]int {
	index := make([][]int, h, h)
	data := make([]int, h*w, h*w)
	for i := 0; i < h; i++ {
		index[i] = data[i*w : (i+1)*w]
	}
	return index
}

package main

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

func main() {
	//rd, _ := os.Open("input")
	io := bufio.NewReader(os.Stdin)

	var t, n, m, elem int
	var matrix [][]int

	fmt.Fscan(io, &t)
	for ; t > 0; t-- {
		fmt.Fscan(io, &n, &m)
		matrix = make([][]int, n)

		for i := 0; i < n; i++ {
			matrix[i] = make([]int, m)
			for j := 0; j < m; j++ {
				fmt.Fscan(io, &elem)
				matrix[i][j] = elem
			}
		}
		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				fmt.Fscan(io, &elem)
				if i == 0 {
					for k := 0; k < n; k++ {
						if matrix[k][0] == elem {
							matrix[j], matrix[k] = matrix[k], matrix[j]
						}
					}
				}
			}
		}
		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				fmt.Printf("%d ", matrix[i][j])
			}
			fmt.Println()
		}
	}
}

package main

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

func main() {
	//rd, _ := os.Open("input")
	io := bufio.NewReader(os.Stdin)

	var t, n, m, elem int
	var matrix [][]int

	fmt.Fscan(io, &t)
	for ; t > 0; t-- {
		fmt.Fscan(io, &n, &m)
		matrix = make([][]int, n)

		for i := 0; i < n; i++ {
			matrix[i] = make([]int, m)
			for j := 0; j < m; j++ {
				fmt.Fscan(io, &elem)
				matrix[i][j] = elem
			}
		}
		for i := 0; i < m; i++ {
			for j := 0; j < n; j++ {
				fmt.Fscan(io, &elem)
				if i == 0 {
					for k := 0; k < n; k++ {

						//fmt.Println(elem, k)
						if matrix[k][0] == elem {
							//fmt.Println(j, k, matrix)
							matrix[j], matrix[k] = matrix[k], matrix[j]
							//fmt.Println(j, k, matrix)
						}
					}
				}
			}
		}
		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				fmt.Printf("%d ", matrix[i][j])
			}
			fmt.Println()
		}
	}
}


Two players A and B have a list of $$$n$$$ integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $$$\{1, 2, 2, 3\}$$$ in a list and you decided to choose $$$2$$$ for the next turn, only a single instance of $$$2$$$ will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.

The first line of input contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the sizes of the list. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^6$$$), describing the list of the player A, who starts the game. The third line contains $$$n$$$ integers $$$b_i$$$ ($$$1 \le b_i \le 10^6$$$), describing the list of the player B.

Output the difference between A's score and B's score ($$$A-B$$$) if both of them are playing optimally.

NoteIn the first example, the game could have gone as follows:   A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A takes his $$$1$$$.  B takes his $$$1$$$. Hence, A's score is $$$1$$$, B's score is $$$1$$$ and difference is $$$0$$$.There is also another optimal way of playing:  A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A removes $$$1$$$ from B's list.  B removes $$$1$$$ from A's list. The difference in the scores is still $$$0$$$.In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be $$$0$$$.

package main

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

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 min(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

type int64s []int64

func (a int64s) Len() int           { return len(a) }
func (a int64s) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a int64s) Less(i, j int) bool { return a[i] > a[j] }

func main() {
	defer writer.Flush()
	var n, k, p1, p2, aa, bb int64
	scanf("%d\n", &n, &k)
	a := make([]int64, n)
	b := make([]int64, n)
	for i := 0; i < int(n); i++ {
		scanf("%d", &a[i])
	}
	scanf("\n")
	for i := 0; i < int(n); i++ {
		scanf("%d", &b[i])
	}

	sort.Sort(int64s(a))
	sort.Sort(int64s(b))

	for p1 < n || p2 < n {
		if p1 < n && p2 < n {
			if (p1+p2)%2 == 0 {
				if a[p1] < b[p2] {
					p2++
				} else {
					aa += (a[p1])
					p1++
				}
			} else {
				if a[p1] < b[p2] {
					bb += (b[p2])
					p2++
				} else {
					p1++
				}
			}
		} else if p1 < n {
			if (p1+p2)%2 == 0 {
				aa += (a[p1])
				p1++
			} else {
				p1++
			}
		} else {
			if (p1+p2)%2 == 1 {
				bb += (b[p2])
				p2++
			} else {
				p2++
			}
		}
	}
	printf("%d", aa-bb)

}

package main

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

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 min(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func main() {
	defer writer.Flush()
	var n, k, p1, p2, aa, bb int64
	scanf("%d\n", &n, &k)
	a := make([]int, n)
	b := make([]int, n)
	for i := 0; i < int(n); i++ {
		scanf("%d", &a[i])
	}
	scanf("\n")
	for i := 0; i < int(n); i++ {
		scanf("%d", &b[i])
	}

	sort.Sort(sort.Reverse(sort.IntSlice(a)))
	sort.Sort(sort.Reverse(sort.IntSlice(b)))

	for p1 < n || p2 < n {
		if p1 < n && p2 < n {
			if (p1+p2)%2 == 0 {
				if a[p1] < b[p2] {
					p2++
				} else {
					aa += int64(a[p1])
					p1++
				}
			} else {
				if a[p1] < b[p2] {
					bb += int64(b[p2])
					p2++
				} else {
					p1++
				}
			}
		} else if p1 < n {
			if (p1+p2)%2 == 0 {
				aa += int64(a[p1])
				p1++
			} else {
				p1++
			}
		} else {
			if (p1+p2)%2 == 1 {
				bb += int64(b[p2])
				p2++
			} else {
				p2++
			}
		}
	}
	printf("%d", aa-bb)

}

package main

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

func main() {
	n, scanner := 0, bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	fmt.Scan(&n)
	a, b, pa, pb, sa, sb := make([]int, n+1), make([]int, n+1), 0, 0, int64(0), int64(0)
	for i := 0; i < n; i++ {
		scanner.Scan()
		a[i], _ = strconv.Atoi(scanner.Text())
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		b[i], _ = strconv.Atoi(scanner.Text())
	}
	sort.Sort(sort.Reverse(sort.IntSlice(a)))
	sort.Sort(sort.Reverse(sort.IntSlice(b)))

	for i := 0; i < n; i++ {
		if a[pa] > b[pb] {
			sa += int64(a[pa])
			pa++
		} else {
			pb++
		}
		if b[pb] > a[pa] {
			sb += int64(b[pb])
			pb++
		} else {
			pa++
		}
	}
	fmt.Println(sa - sb)
}

package main

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

const (
	MaxN = 100005
)

var n int
var a [MaxN]int64
var b [MaxN]int64

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &a[i])
	}
	fmt.Fscanf(buf, "\n")
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &b[i])
	}
	sort.Slice(a[:n], func(i, j int) bool {
		return a[i] > a[j]
	})
	sort.Slice(b[:n], func(i, j int) bool {
		return b[i] > b[j]
	})
	r1 := int64(0)
	s1 := a[:n]
	s2 := b[:n]
	for i := 0; i < n; i++ {
		if len(s1) > 0 {
			if len(s2) > 0 {
				if s1[0] > s2[0] {
					r1 += s1[0]
					s1 = s1[1:]
				} else {
					s2 = s2[1:]
				}
			} else {
				r1 += s1[0]
				s1 = s1[1:]
			}
		} else {
			s2 = s2[1:]
		}
		if len(s2) > 0 {
			if len(s1) > 0 {
				if s1[0] < s2[0] {
					r1 -= s2[0]
					s2 = s2[1:]
				} else {
					s1 = s1[1:]
				}
			} else {
				r1 -= s2[0]
				s2 = s2[1:]
			}
		} else {
			s1 = s1[1:]
		}
	}
	fmt.Println(r1)
}

package main

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

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 min(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func main() {
	defer writer.Flush()
	var n, k, p1, p2, aa, bb int
	scanf("%d\n", &n, &k)
	a := make([]int, n)
	b := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d", &a[i])
	}
	scanf("\n")
	for i := 0; i < n; i++ {
		scanf("%d", &b[i])
	}

	sort.Sort(sort.Reverse(sort.IntSlice(a)))
	sort.Sort(sort.Reverse(sort.IntSlice(b)))

	for p1 < n || p2 < n {
		if p1 < n && p2 < n {
			if (p1+p2)%2 == 0 {
				if a[p1] < b[p2] {
					p2++
				} else {
					aa += a[p1]
					p1++
				}
			} else {
				if a[p1] < b[p2] {
					bb += b[p2]
					p2++
				} else {
					p1++
				}
			}
		} else if p1 < n {
			if (p1+p2)%2 == 0 {
				aa += a[p1]
				p1++
			} else {
				p1++
			}
		} else {
			if (p1+p2)%2 == 1 {
				bb += b[p2]
				p2++
			} else {
				p2++
			}
		}
	}
	printf("%d", aa-bb)

}

package main

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

const (
	MaxN = 100005
)

var n int
var a [MaxN]int
var b [MaxN]int

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &a[i])
	}
	fmt.Fscanf(buf, "\n")
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &b[i])
	}
	sort.Slice(a[:n], func(i, j int) bool {
		return a[i] > a[j]
	})
	sort.Slice(b[:n], func(i, j int) bool {
		return b[i] > b[j]
	})
	r1, r2 := 0, 0
	s1 := a[:n]
	s2 := b[:n]
	for i := 0; i < n; i++ {
		if len(s1) > 0 {
			if len(s2) > 0 {
				if s1[0] > s2[0] {
					r1 += s1[0]
					s1 = s1[1:]
				} else {
					s2 = s2[1:]
				}
			} else {
				r1 += s1[0]
				s1 = s1[1:]
			}
		} else {
			s2 = s2[1:]
		}
		if len(s2) > 0 {
			if len(s1) > 0 {
				if s1[0] < s2[0] {
					r2 += s2[0]
					s2 = s2[1:]
				} else {
					s1 = s1[1:]
				}
			} else {
				r2 += s2[0]
				s2 = s2[1:]
			}
		}
	}
	fmt.Println(r1 - r2)
}

package main

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

const (
	MaxN = 100005
)

var n int
var a [MaxN]int64
var b [MaxN]int64

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &a[i])
	}
	fmt.Fscanf(buf, "\n")
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &b[i])
	}
	sort.Slice(a[:n], func(i, j int) bool {
		return a[i] > a[j]
	})
	sort.Slice(b[:n], func(i, j int) bool {
		return b[i] > b[j]
	})
	r1, r2 := int64(0), int64(0)
	s1 := a[:n]
	s2 := b[:n]
	for i := 0; i < n; i++ {
		if len(s1) > 0 {
			if len(s2) > 0 {
				if s1[0] > s2[0] {
					r1 += s1[0]
					s1 = s1[1:]
				} else {
					s2 = s2[1:]
				}
			} else {
				r1 += s1[0]
				s1 = s1[1:]
			}
		} else {
			s2 = s2[1:]
		}
		if len(s2) > 0 {
			if len(s1) > 0 {
				if s1[0] < s2[0] {
					r2 += s2[0]
					s2 = s2[1:]
				} else {
					s1 = s1[1:]
				}
			} else {
				r2 += s2[0]
				s2 = s2[1:]
			}
		}
	}
	fmt.Println(r1 - r2)
}


Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible. If this is possible, calculate the minimal cost.

The first line contains an integer n (1 ≤ n ≤ 300), number of cards. The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards. The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.

If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.

NoteIn first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.

package main

import . "fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	type pair struct{ v, c int }
	gcd := func(a, b int) int {
		for a != 0 {
			a, b = b%a, a
		}
		return b
	}

	var n int
	Scan(&n)
	a := make([]pair, n)
	for i := range a {
		Scan(&a[i].v)
	}
	for i := range a {
		Scan(&a[i].c)
	}

	f := map[int]int{0: 0}
	for _, p := range a {
		for g, c := range f {
			if g = gcd(g, p.v); f[g] == 0 || c+p.c < f[g] {
				f[g] = c + p.c
			}
		}
	}
	if f[1] > 0 {
		Print(f[1])
	} else {
		Print(-1)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF510D(in io.Reader, out io.Writer) {
	type pair struct{ v, c int }
	gcd := func(a, b int) int {
		for a != 0 {
			a, b = b%a, a
		}
		return b
	}

	var n int
	Fscan(in, &n)
	a := make([]pair, n)
	for i := range a {
		Fscan(in, &a[i].v)
	}
	for i := range a {
		Fscan(in, &a[i].c)
	}

	dp := map[int]int{}
	dp[0] = 0
	for _, p := range a {
		for g, c := range dp {
			g = gcd(g, p.v)
			if dp[g] > 0 {
				if c+p.c < dp[g] {
					dp[g] = c + p.c
				}
			} else {
				dp[g] = c + p.c
			}
		}
	}
	if dp[1] > 0 {
		Fprint(out, dp[1])
	} else {
		Fprint(out, -1)
	}
}

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