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


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

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


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

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


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


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

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


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


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

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


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

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

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

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


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

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


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

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"

func solve(n int, left, right string) map[int]int {
	const QuestionMark = '?'

	strToCountMap := func(str string) map[rune][]int {
		countMap := map[rune][]int{}
		for i, ch := range str {
			_, found := countMap[ch]
			if !found {
				countMap[ch] = []int{}
			}

			countMap[ch] = append(countMap[ch], i)
		}

		return countMap
	}

	res := map[int]int{}

	leftMap, rightMap := strToCountMap(left), strToCountMap(right)

	//fmt.Println(rightMap)

	for i, leftChar := range left {
		if leftChar != QuestionMark {
			for _, ch := range [...]rune{leftChar, QuestionMark} {
				_, found := rightMap[ch]

				if found && len(rightMap[ch]) > 0 {
					res[i] = rightMap[ch][0]

					leftMap[leftChar] = leftMap[leftChar][1:]
					rightMap[ch] = rightMap[ch][1:]

					break
				}
			}
		}
	}

	for _, rightChar := range right {
		if len(rightMap[rightChar]) > 0 {
			//fmt.Println(rightChar, rightMap[rightChar])

			_, found := leftMap[QuestionMark]

			if found && len(leftMap[QuestionMark]) > 0 {
				res[leftMap[QuestionMark][0]] = rightMap[rightChar][0]

				leftMap[QuestionMark] = leftMap[QuestionMark][1:]
				rightMap[rightChar] = rightMap[rightChar][1:]
			}
		}
	}

	return res
}

func main() {
	n := 0
	left, right := "", ""

	fmt.Scan(&n)
	fmt.Scan(&left, &right)

	ans := solve(n, left, right)
	fmt.Println(len(ans))
	for l, r := range ans {
		fmt.Println(l+1, r+1)
	}
}

package main

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

type shuts struct {
	lshut []int
	rshut []int
}

type boots [][2]int

func (s boots) Len() int {
	return len(s)
}
func (s boots) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s boots) Less(i, j int) bool {
	return s[i][0] < s[j][0]
}

type boots2 [][2]int

func (s boots2) Len() int {
	return len(s)
}
func (s boots2) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s boots2) Less(i, j int) bool {
	return s[i][0] > s[j][0]
}

func main() {

	read := bufio.NewReader(os.Stdin)
	write := bufio.NewWriter(os.Stdout)
	var n int
	var lstr, rstr string

	propar := make(map[int]shuts)

	fmt.Fscan(read, &n)
	fmt.Fscan(read, &lstr)
	fmt.Fscan(read, &rstr)

	var res [][2]int
	var lxv [][2]int
	var rxv [][2]int

	for i := 0; i < n; i++ {
		lc := int(lstr[i])
		if lc != 63 {
			shu := propar[lc]
			shu.lshut = append(shu.lshut, i+1)
			propar[lc] = shu
		} else {
			bot := [2]int{63, i + 1}
			lxv = append(lxv, bot)
		}

		rc := int(rstr[i])
		if rc != 63 {
			shu := propar[rc]
			shu.rshut = append(shu.rshut, i+1)
			propar[rc] = shu
		} else {
			bot := [2]int{63, i + 1}
			rxv = append(rxv, bot)
		}
	}

	for color, shu := range propar {
		nl := len(shu.lshut)
		nr := len(shu.rshut)
		nmin := nl
		nmax := nr
		amax := shu.rshut
		lrmax := 1
		if nmin > nr {
			nmin = nr
			nmax = nl
			amax = shu.lshut
			lrmax = 0
		}

		for i := 0; i < nmin; i++ {
			para := [2]int{shu.lshut[i], shu.rshut[i]}
			res = append(res, para)
		}
		for i := nmin; i < nmax; i++ {
			bot := [2]int{color, amax[i]}
			if lrmax == 0 {
				lxv = append(lxv, bot)
			} else {
				rxv = append(rxv, bot)
			}
		}

	}
	sort.Sort(boots(lxv))
	sort.Sort(boots2(rxv))
	nx := len(lxv)
	for i := 0; i < nx; i++ {
		if lxv[i][0] == 63 || rxv[i][0] == 63 {
			para := [2]int{lxv[i][1], rxv[i][1]}
			res = append(res, para)
		}
	}
	nres := len(res)
	fmt.Fprintln(write, nres)
	for i := 0; i < nres; i++ {
		fmt.Fprintln(write, res[i][0], res[i][1])
	}
	write.Flush()

}

/*
10
codeforces
dodivthree
*/

package main

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

func addD(m map[byte][]int, key byte, index int) {
	if len(m[key]) <= 0 {
		m[key] = make([]int, 0)
	}
	m[key] = append(m[key], index+1)
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(buf, "%d\n", &n)
	st := make([]int, n*2)
	stf := 0
	s1 := make([]byte, n+1)
	s2 := make([]byte, n+1)
	fmt.Fscanf(buf, "%s\n", &s1)
	fmt.Fscanf(buf, "%s\n", &s2)

	m1 := make(map[byte][]int)
	m2 := make(map[byte][]int)
	for i := 0; i < n; i++ {
		addD(m1, s1[i], i)
		addD(m2, s2[i], i)
	}
//	fmt.Printf("m1=%v\n",m1)
//	fmt.Printf("m2=%v\n",m2)
	for i := 0; i < 26; i++ {
		c := 'a' + byte(i)
		front := 0
		l := len(m1[c])
		for front < l {
			if len(m2[c]) > 0 {
				st[stf] = m1[c][front]
				stf++
				st[stf] = m2[c][0]
				stf++
				m2[c] = m2[c][1:]
				//		ans++
			} else if len(m2['?']) > 0 {
				st[stf] = m1[c][front]
				stf++
				st[stf] = m2['?'][0]
				stf++
				m2['?'] = m2['?'][1:]
				//	ans++
			} else {
				break
			}
			front++
		}
	}
	//fmt.Printf("m1=%v\n",m1)
	//fmt.Printf("m2=%v\n",m2)
	sf1 := 0
	sf2:=0
	stack1 := make([]int, n+1)
	stack2 := make([]int, n+1)
	for i:= 0;i < 26;i++{
		c := 'a' + byte(i)
		l1 := len(m1[c])
		if l1 > 0{
			for j:=0;j < l1;j++{
				stack1[sf1] = m1[c][j]
				sf1++
			}
		}
		l2 := len(m2[c])
		if l2 > 0{
			for j:=0;j < l2;j++{
			//	fmt.Printf("f2=%d--%d %c %d\n",sf2,m2[c][j],c,l2)
				stack2[sf2] = m2[c][j]
				sf2++
			}
		}
	}
	left1 := len(m1['?'])
	ff := 0
	front := 0
	for front < left1{
		if ff < sf2 {
			st[stf] = m1['?'][front]
			stf++
			st[stf] = stack2[ff]
			stf++
			ff++
			front++
		}else if len(m2['?']) > 0{
			st[stf] = m1['?'][front]
			stf++
			st[stf] = m2['?'][0]
			stf++
			front++
			m2['?'] = m2['?'][1:]
		}else {
			break
		}
	}
	m1['?'] = m1['?'][front:]
	left2 := len(m2['?'])
	front = 0
	ff = 0
	for front < left2{
		if ff < sf1 {
			st[stf] = stack1[ff]
			stf++
			st[stf] = m2['?'][front]
			stf++
			ff++
			front++
		}else {
			break
		}
	}
	fmt.Printf("%d\n", stf/2)
	for i := 0; i+1 < stf; i += 2 {
		fmt.Printf("%d %d\n", st[i], st[i+1])
	}
}

/**
01010101
0101010
 */

package main

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

type Pair struct {
	leftIndex  int
	rightIndex int
}

func newPair(leftIndex int, rightIndex int) Pair {
	return Pair{leftIndex: leftIndex, rightIndex: rightIndex}
}

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

	var n int
	fmt.Fscanln(in, &n)
	pairs := make([]Pair, 0)

	lefts := make(map[rune][]int)
	leftWilds := make([]int, 0)
	for i := 1; i <= n; i++ {
		c, _, _ := in.ReadRune()

		if c == '?' {
			leftWilds = append(leftWilds, i)
			continue
		}
		lefts[c] = append(lefts[c], i)
	}

	in.ReadLine()
	rightWilds := make([]int, 0)
	for i := 1; i <= n; i++ {
		c, _, _ := in.ReadRune()

		if c == '?' {
			rightWilds = append(rightWilds, i)
			continue
		}

		if len(lefts[c]) != 0 {
			left := lefts[c][0]
			pairs = append(pairs, newPair(left, i))
			lefts[c] = lefts[c][1:]
		} else if len(leftWilds) != 0 {
			left := leftWilds[0]
			pairs = append(pairs, newPair(left, i))
			leftWilds = leftWilds[1:]
		}
	}

	for _, list := range lefts {
		if list == nil {
			continue
		}
		for len(list) != 0 && len(rightWilds) != 0 {
			pairs = append(pairs, newPair(list[0], rightWilds[0]))
			list = list[1:]
			rightWilds = rightWilds[1:]
		}
	}

	for len(leftWilds) != 0 {
		if len(rightWilds) == 0 {
			break
		}
		pairs = append(pairs, newPair(leftWilds[0], rightWilds[0]))
		leftWilds = leftWilds[1:]
		rightWilds = rightWilds[1:]
	}

	fmt.Println(len(pairs))
	for _, pair := range pairs {
		fmt.Println(pair.leftIndex, pair.rightIndex)
	}
}

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"os"
)

type Pair struct {
	leftIndex  int
	rightIndex int
}

func newPair(leftIndex int, rightIndex int) Pair {
	return Pair{leftIndex: leftIndex, rightIndex: rightIndex}
}

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

	var n int
	fmt.Fscanln(in, &n)
	pairs := list.New()

	lefts := make(map[rune]*list.List)
	leftWilds := list.New()
	for i := 1; i <= n; i++ {
		c, _, _ := in.ReadRune()

		if c == '?' {
			leftWilds.PushBack(i)
			continue
		}
		if lefts[c] == nil {
			lefts[c] = list.New()
		}
		lefts[c].PushBack(i)
	}

	in.ReadLine()
	rightWilds := list.New()
	for i := 1; i <= n; i++ {
		c, _, _ := in.ReadRune()

		if c == '?' {
			rightWilds.PushBack(i)
			continue
		}

		if lefts[c] != nil && lefts[c].Len() != 0 {
			left := lefts[c].Remove(lefts[c].Front()).(int)
			pairs.PushBack(newPair(left, i))
		} else if leftWilds.Len() != 0 {
			left := leftWilds.Remove(leftWilds.Front()).(int)
			pairs.PushBack(newPair(left, i))
		}
	}

	for _, list := range lefts {
		if list == nil {
			continue
		}
		for list.Len() != 0 && rightWilds.Len() != 0 {
			left := list.Remove(list.Front()).(int)
			right := rightWilds.Remove(rightWilds.Front()).(int)
			pairs.PushBack(newPair(left, right))
		}
	}

	for left := leftWilds.Front(); left != nil; left = left.Next() {
		if rightWilds.Len() == 0 {
			break
		}
		right := rightWilds.Remove(rightWilds.Front()).(int)
		pairs.PushBack(newPair(left.Value.(int), right))
	}

	fmt.Println(pairs.Len())
	for it := pairs.Front(); it != nil; it = it.Next() {
		pair := it.Value.(Pair)
		fmt.Println(pair.leftIndex, pair.rightIndex)
	}
}

// Author: sighduck
// URL: https://codeforces.com/contest/1141/problem/D

package main

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

type Pair struct {
	ai int
	bi int
}

type CharPos struct {
	char string
	pos  int
}

func createMap(s string) map[string][]int {
	m := make(map[string][]int)
	for i, elem := range s {
		char := string(elem)
		m[char] = append(m[char], i+1)
	}
	return m
}

func min(x int, y int) int {
	if x < y {
		return x
	}
	return y
}

func remainingChars(m map[string][]int, reverse bool) []CharPos {
	chars := []CharPos{}
	for char := range m {
		for _, elem := range m[char] {
			chars = append(chars, CharPos{char, elem})
		}
	}
	sort.Slice(chars, func(i, j int) bool {
		if chars[i].char == "?" {
			return !reverse
		}
		if chars[j].char == "?" {
			return reverse
		}
		if reverse {
			return chars[i].char > chars[j].char
		}
		return chars[i].char < chars[j].char
	})
	return chars
}

func Solve(n int, a string, b string) []Pair {
	aMap := createMap(a)
	bMap := createMap(b)
	answer := []Pair{}
	for char := range aMap {
		if char == "?" {
			continue
		}
		minLength := min(len(aMap[char]), len(bMap[char]))
		for i := 0; i < minLength; i++ {
			var ai, bi int
			ai, aMap[char] = aMap[char][len(aMap[char])-1], aMap[char][:len(aMap[char])-1]
			bi, bMap[char] = bMap[char][len(bMap[char])-1], bMap[char][:len(bMap[char])-1]
			answer = append(answer, Pair{ai, bi})
		}
	}
	aChars := remainingChars(aMap, false)
	bChars := remainingChars(bMap, true)
	for i, aElem := range aChars {
		bElem := bChars[i]
		if aElem.char == "?" || bElem.char == "?" {
			answer = append(answer, Pair{aElem.pos, bElem.pos})
		}
	}
	return answer
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	var a, b string
	fmt.Fscanf(reader, "%s\n%s\n", &a, &b)

	answer := Solve(n, a, b)
	fmt.Fprintf(writer, "%d\n", len(answer))
	for _, elem := range answer {
		fmt.Fprintf(writer, "%d %d\n", elem.ai, elem.bi)
	}
}

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"os"
)

type Pair struct {
	leftIndex  int
	rightIndex int
}

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

	var n int
	fmt.Fscanln(in, &n)
	pairs := list.New()

	lefts := make(map[rune]*list.List)
	leftWilds := list.New()
	for i := 1; i <= n; i++ {
		c, _, _ := in.ReadRune()

		if c == '?' {
			leftWilds.PushBack(i)
			continue
		}
		if lefts[c] == nil {
			lefts[c] = list.New()
		}
		lefts[c].PushBack(i)
	}

	in.Discard(1)
	rightWilds := list.New()
	for i := 1; i <= n; i++ {
		c, _, _ := in.ReadRune()

		if c == '?' {
			rightWilds.PushBack(i)
			continue
		}

		if lefts[c] != nil && lefts[c].Len() != 0 {
			pairs.PushBack(Pair{
				leftIndex:  lefts[c].Front().Value.(int),
				rightIndex: i,
			})
			lefts[c].Remove(lefts[c].Front())
		} else if leftWilds.Len() != 0 {
			pairs.PushBack(Pair{
				leftIndex:  leftWilds.Front().Value.(int),
				rightIndex: i,
			})
			leftWilds.Remove(leftWilds.Front())
		}
	}

	for _, list := range lefts {
		if rightWilds.Len() == 0 {
			break
		}
		for list.Len() != 0 {
			pairs.PushBack(Pair{
				leftIndex:  list.Front().Value.(int),
				rightIndex: rightWilds.Front().Value.(int),
			})
			list.Remove(list.Front())
			rightWilds.Remove(rightWilds.Front())
		}
	}

	for left := leftWilds.Front(); left != nil; left = left.Next() {
		if rightWilds.Len() == 0 {
			break
		}
		pairs.PushBack(Pair{
			leftIndex:  left.Value.(int),
			rightIndex: rightWilds.Front().Value.(int),
		})
		rightWilds.Remove(rightWilds.Front())
	}

	fmt.Println(pairs.Len())
	for it := pairs.Front(); it != nil; it = it.Next() {
		pair := it.Value.(Pair)
		fmt.Println(pair.leftIndex, pair.rightIndex)
	}
}

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"os"
)

type Pair struct {
	leftIndex  interface{}
	rightIndex interface{}
}

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

	var n int
	fmt.Fscanln(in, &n)
	pairs := list.New()

	lefts := make(map[rune]*list.List)
	leftWilds := list.New()
	for i := 1; i <= n; i++ {
		c, _, _ := in.ReadRune()

		if c == '?' {
			leftWilds.PushBack(i)
			continue
		}
		if lefts[c] == nil {
			lefts[c] = list.New()
		}
		lefts[c].PushBack(i)
	}

	in.Discard(1)
	rightWilds := list.New()
	for i := 1; i <= n; i++ {
		c, _, _ := in.ReadRune()

		if c == '?' {
			rightWilds.PushBack(i)
			continue
		}

		if lefts[c] != nil && lefts[c].Len() != 0 {
			pairs.PushBack(Pair{
				leftIndex:  lefts[c].Front().Value,
				rightIndex: i,
			})
			lefts[c].Remove(lefts[c].Front())
		} else if leftWilds.Len() != 0 {
			pairs.PushBack(Pair{
				leftIndex: leftWilds.Front().Value,
				rightIndex: i,
			})
			leftWilds.Remove(leftWilds.Front())
		}
	}

	for _, list := range lefts {
		if rightWilds.Len() == 0 {
			break
		}
		for list.Len() != 0 {
			pairs.PushBack(Pair{
				leftIndex: list.Front().Value,
				rightIndex: rightWilds.Front().Value,
			})
			list.Remove(list.Front())
			rightWilds.Remove(rightWilds.Front())
		}
	}

	for left := leftWilds.Front(); left != nil; left = left.Next() {
		if rightWilds.Len() == 0 {
			break
		}
		pairs.PushBack(Pair{
			leftIndex: left.Value,
			rightIndex: rightWilds.Front().Value,
			})
		rightWilds.Remove(rightWilds.Front())
	}

	fmt.Println(pairs.Len())
	for it := pairs.Front(); it != nil; it = it.Next() {
		pair := it.Value.(Pair)
		fmt.Println(pair.leftIndex, pair.rightIndex)
	}
}

package main

import "fmt"

func solve(n int, left, right string) map[int]int {
	const QuestionMark = '?'

	strToCountMap := func(str string) map[rune][]int {
		countMap := map[rune][]int{}
		for i, ch := range str {
			_, found := countMap[ch]
			if !found {
				countMap[ch] = []int{}
			}

			countMap[ch] = append(countMap[ch], i)
		}

		return countMap
	}

	res := map[int]int{}

	leftMap, rightMap := strToCountMap(left), strToCountMap(right)

	for i, leftChar := range left {
		if leftChar != QuestionMark {
			for _, ch := range [...]rune{leftChar, QuestionMark} {
				_, found := rightMap[ch]

				if found && len(rightMap[ch]) > 0 {
					res[i] = rightMap[ch][0]

					leftMap[leftChar] = leftMap[leftChar][1:]
					rightMap[ch] = rightMap[ch][1:]

					break
				}
			}
		}
	}

	for j, rightChar := range right {
		if len(rightMap[rightChar]) > 0 {
			_, found := leftMap[QuestionMark]

			if found && len(leftMap[QuestionMark]) > 0 {
				res[leftMap[QuestionMark][0]] = j

				leftMap[QuestionMark] = leftMap[QuestionMark][1:]
				rightMap[rightChar] = rightMap[rightChar][1:]
			}
		}
	}

	return res
}

func main() {
	n := 0
	left, right := "", ""

	fmt.Scan(&n)
	fmt.Scan(&left, &right)

	ans := solve(n, left, right)
	fmt.Println(len(ans))
	for l, r := range ans {
		fmt.Println(l+1, r+1)
	}
}


package main

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

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

	situations := make(map[string]int)

	target := make([]int, n)
	gears := make([]int, n)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; i < n && scanner.Scan(); i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		gears[i] = a
		target[i] = i
	}

	target_code := gears_to_code(target, n)
	situations[gears_to_code(gears, n)] = 1

	for true {
		for i := 0; i < n; i++ {
			if i%2 == 0 {
				gears[i] = (gears[i] + 1) % n
			} else {
				if gears[i] > 0 {
					gears[i] = gears[i] - 1
				} else {
					gears[i] = n - 1
				}
			}
		}

		sit := gears_to_code(gears, n)
		if target_code == sit {
			fmt.Println("Yes")
			return
		} else if situations[sit] > 0 {
			fmt.Println("No")
			return
		} else {
			situations[sit] = 1
		}
	}
}

func gears_to_code(g []int, n int) string {
	res := make([]string, n)
	for i := 0; i < n; i++ {
		res[i] = strconv.Itoa(g[i])
	}
	return strings.Join(res, "")
}

package main

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

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

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

	n := nextInt()
	a := make([]int, n)

	for i := range a {
		a[i] = nextInt()
	}

	dif := (n - a[0]) % n
	a[0] = 0

	for i := 1; i < n; i++ {
		if i%2 == 0 {
			a[i] = (a[i] + dif) % n
		} else {
			a[i] = (a[i] + n - dif) % n
		}

		if a[i]-1 != a[i-1] {
			println("No")
			return
		}
	}

	println("Yes")
	// println(a)
}

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

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

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

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

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

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

import (
    "fmt"

)

func main(){
    var n int
    fmt.Scanf("%d\n", &n)
    //fmt.Println(n)
    var g0 int
    fmt.Scanf("%d", &g0)
    //fmt.Println(g0)
    rot := n - g0

    for i := 0; i < n - 1; i += 1 {
        fmt.Scanf("%d", &g0)
        //fmt.Println(g0)
        if i % 2 == 0 {
            g0 -= rot
        } else {
            g0 += rot
        }
        g0 += n * 10
        g0 %= n

        if g0 != i + 1 {
            fmt.Println("No")
            return
        }
    }

    fmt.Println("Yes")
}

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 getLine() string {
	s, _ := reader.ReadString('\n')
	for len(s) > 0 && (s[len(s)-1] == '\n' || s[len(s)-1] == '\r') {
		s = s[:len(s)-1]
	}
	return s
}

func main() {
	// STDOUT MUST BE FLUSHED MANUALLY!!!
	defer writer.Flush()

	var n int
	scanf("%d\n", &n)
	var a = make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d", &a[i])
	}
	var k = -1
	var d = a[0]
	var check = true
	for i := 0; i < n && check; i++ {
		if (a[i]+k*d+n)%n != i {
			check = false
		}
		k *= -1
	}
	if check {
		printf("Yes\n")
	} else {
		printf("No\n")
	}
}

package main

import (
	"fmt"
)

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

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

	first := n - an[0]
	ans := true
	for i := 1; i < n; i++ {
		if i%2 != 0 {
			an[i] -= first
			an[i] += n
		} else {
			an[i] += first
		}
		if an[i]%n != i {
			ans = false
			break
		}
	}

	if ans {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

package main

import (
    "fmt"

)

func main(){
    var n int
    fmt.Scanf(" %d", &n)
    var g0 int
    fmt.Scanf(" %d", &g0)
    rot := n - g0

    for i := 0; i < n - 1; i += 1 {
        fmt.Scanf(" %d", &g0)

        if i % 2 == 0 {
            g0 -= rot
        } else {
            g0 += rot
        }
        g0 += n * 10
        g0 %= n

        if g0 != i + 1 {
            fmt.Println("No")
            return
        }
    }

    fmt.Println("Yes")
}

package main

import (
    "fmt"

)

func main(){
    var n int
    fmt.Scanf("%d", &n)
    var g0 int
    fmt.Scanf("%d", &g0)
    rot := n - g0

    for i := 0; i < n - 1; i += 1 {
        fmt.Scanf("%d", &g0)
        if i % 2 == 0 {
            g0 -= rot
        } else {
            g0 += rot
        }
        g0 %= n
        if g0 < 0 {
            g0 += n
        }
        if g0 != i + 1 {
            fmt.Println("No")
            return
        }
    }

    fmt.Println("Yes")
}

package main

import (
    "fmt"

)

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

    var g0 int
    fmt.Scanf(" %d", &g0)
    rot := n - g0

    for i := 0; i < n - 1; i += 1 {
        fmt.Scanf(" %d", &g0)

        if i % 2 == 0 {
            g0 -= rot
        } else {
            g0 += rot
        }
        g0 += n * 10
        g0 %= n

        if g0 != i + 1 {
            fmt.Println("No")
            return
        }
    }

    fmt.Println("Yes")
}


package main

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

var stdin io.Reader

func nextInt() int {
	var x int
	fmt.Fscan(stdin, &x)
	return x
}

type contestant struct {
	id, x, y int
}

type byDif []contestant

func (a byDif) Len() int           { return len(a) }
func (a byDif) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a byDif) Less(i, j int) bool { return a[i].x-a[i].y < a[j].x-a[j].y }

var N, E int
var idToPos []int
var enemies [][]int
var ctts []contestant
var sumX, sumY []int64

func leftOf(sum []int64, pos int) int64 {
	if pos < 0 {
		return 0
	}
	return sum[pos]
}

func rightOf(sum []int64, pos int) int64 {
	if pos >= len(sum) {
		return 0
	}
	res := sum[len(sum)-1]
	if pos > 0 {
		res -= sum[pos-1]
	}
	return res
}

func main() {
	stdin = bufio.NewReader(os.Stdin)
	N, E = nextInt(), nextInt()

	ctts = make([]contestant, N)
	for i := range ctts {
		ctts[i] = contestant{id: i, x: nextInt(), y: nextInt()}
	}

	enemies = make([][]int, N)
	for i := range enemies {
		enemies[i] = make([]int, 0, 8)
	}

	for i := 0; i < E; i++ {
		a, b := nextInt()-1, nextInt()-1
		enemies[a] = append(enemies[a], b)
		enemies[b] = append(enemies[b], a)
	}

	sort.Sort(byDif(ctts))
	idToPos = make([]int, N)
	for i := range ctts {
		idToPos[ctts[i].id] = i
	}

	//fmt.Printf("idToPos=%v \n", idToPos)

	sumX = make([]int64, N)
	sumY = make([]int64, N)
	sumX[0] = int64(ctts[0].x)
	sumY[0] = int64(ctts[0].y)
	for i := 1; i < N; i++ {
		sumX[i] = sumX[i-1] + int64(ctts[i].x)
		sumY[i] = sumY[i-1] + int64(ctts[i].y)
	}

	answers := make([]int64, N)

	for cur := 0; cur < N; cur++ {
		ll := leftOf(sumX, cur-1) + int64(cur)*int64(ctts[cur].y)
		rr := rightOf(sumY, cur+1) + int64(N-cur-1)*int64(ctts[cur].x)

		total := ll + rr

		for _, enemyId := range enemies[ctts[cur].id] {
			enemyPos := idToPos[enemyId]
			if enemyPos < cur {
				total = total - int64(ctts[cur].y) - int64(ctts[enemyPos].x)
			} else {
				total = total - int64(ctts[cur].x) - int64(ctts[enemyPos].y)
			}
		}

		answers[ctts[cur].id] = total
	}

	output := bufio.NewWriterSize(os.Stdout, N*5)
	defer output.Flush()

	for _, x := range answers {
		fmt.Fprintf(output, "%d ", x)
	}
}

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int64 {
	if !in.Scan() {
		panic(in.Err())
	}
	res := int64(0)
	mul := int64(1)
	for _, b := range in.Bytes() {
		if b == '-' {
			mul *= -1
			continue
		}
		res = res*10 + int64(b-'0')
	}
	return mul * res
}

type participant struct {
	i    int
	x, y int64
}

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	m := readInt()
	participants := make([]participant, n)
	for i := range participants {
		participants[i].i = i
		participants[i].x = readInt()
		participants[i].y = readInt()
	}

	ans := make([]int64, n)
	for i := int64(0); i < m; i++ {
		u := readInt() - 1
		v := readInt() - 1
		score := participants[u].x + participants[v].y
		if o := participants[v].x + participants[u].y; score > o {
			score = o
		}
		ans[u] -= score
		ans[v] -= score
	}

	sort.Slice(participants, func(i, j int) bool { return participants[i].x-participants[i].y < participants[j].x-participants[j].y })

	sumX := int64(0)
	for i := range ans {
		ans[participants[i].i] += int64(i)*participants[i].y + sumX
		sumX += participants[i].x
	}
	sumY := int64(0)
	for i := range ans {
		idx := n-1-int64(i)
		ans[participants[idx].i] += int64(i)*participants[idx].x + sumY
		sumY += participants[idx].y
	}

	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	for i := range ans {
		if i+1 == int(n) {
			fmt.Fprintln(out, ans[i])
		} else {
			fmt.Fprint(out, ans[i], " ")
		}
	}
}

package main

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

var stdin io.Reader
var scanner *bufio.Scanner

func nextInt() int {
	//scanner.Scan()
	//x, _ := strconv.Atoi(scanner.Text())
	var x int
	fmt.Fscan(stdin, &x)
	return x
}

type contestant struct {
	id, x, y int
}

type byDif []contestant

func (a byDif) Len() int           { return len(a) }
func (a byDif) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a byDif) Less(i, j int) bool { return a[i].x-a[i].y < a[j].x-a[j].y }

var N, E int
var idToPos []int
var enemies [][]int
var ctts []contestant
var sumX, sumY []int64

func leftOf(sum []int64, pos int) int64 {
	if pos < 0 {
		return 0
	}
	return sum[pos]
}

func rightOf(sum []int64, pos int) int64 {
	if pos >= len(sum) {
		return 0
	}
	res := sum[len(sum)-1]
	if pos > 0 {
		res -= sum[pos-1]
	}
	return res
}

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

	N, E = nextInt(), nextInt()

	ctts = make([]contestant, N)
	for i := range ctts {
		ctts[i] = contestant{id: i, x: nextInt(), y: nextInt()}
	}

	enemies = make([][]int, N)
	for i := range enemies {
		enemies[i] = make([]int, 0, 8)
	}

	for i := 0; i < E; i++ {
		a, b := nextInt()-1, nextInt()-1
		enemies[a] = append(enemies[a], b)
		enemies[b] = append(enemies[b], a)
	}

	sort.Sort(byDif(ctts))
	idToPos = make([]int, N)
	for i := range ctts {
		idToPos[ctts[i].id] = i
	}

	//fmt.Printf("idToPos=%v \n", idToPos)

	sumX = make([]int64, N)
	sumY = make([]int64, N)
	sumX[0] = int64(ctts[0].x)
	sumY[0] = int64(ctts[0].y)
	for i := 1; i < N; i++ {
		sumX[i] = sumX[i-1] + int64(ctts[i].x)
		sumY[i] = sumY[i-1] + int64(ctts[i].y)
	}

	answers := make([]int64, N)

	for cur := 0; cur < N; cur++ {
		ll := leftOf(sumX, cur-1) + int64(cur)*int64(ctts[cur].y)
		rr := rightOf(sumY, cur+1) + int64(N-cur-1)*int64(ctts[cur].x)

		total := ll + rr

		for _, enemyId := range enemies[ctts[cur].id] {
			enemyPos := idToPos[enemyId]
			if enemyPos < cur {
				total = total - int64(ctts[cur].y) - int64(ctts[enemyPos].x)
			} else {
				total = total - int64(ctts[cur].x) - int64(ctts[enemyPos].y)
			}
		}

		answers[ctts[cur].id] = total
	}

	output := bufio.NewWriterSize(os.Stdout, N*5)
	defer output.Flush()

	for _, x := range answers {
		fmt.Fprintf(output, "%d ", x)
	}
}

package main

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

var stdin io.Reader
var scanner *bufio.Scanner

func nextInt() int {
	scanner.Scan()
	x, _ := strconv.Atoi(scanner.Text())
	//fmt.Fscan(stdin, &x)
	return x
}

type contestant struct {
	id, x, y int
}

type byDif []contestant

func (a byDif) Len() int           { return len(a) }
func (a byDif) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a byDif) Less(i, j int) bool { return a[i].x-a[i].y < a[j].x-a[j].y }

var N, E int
var idToPos []int
var enemies [][]int
var ctts []contestant
var sumX, sumY []int64

func leftOf(sum []int64, pos int) int64 {
	if pos < 0 {
		return 0
	}
	return sum[pos]
}

func rightOf(sum []int64, pos int) int64 {
	if pos >= len(sum) {
		return 0
	}
	res := sum[len(sum)-1]
	if pos > 0 {
		res -= sum[pos-1]
	}
	return res
}

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

	N, E = nextInt(), nextInt()

	ctts = make([]contestant, N)
	for i := range ctts {
		ctts[i] = contestant{id: i, x: nextInt(), y: nextInt()}
	}

	enemies = make([][]int, N)
	for i := range enemies {
		enemies[i] = make([]int, 0, 8)
	}

	for i := 0; i < E; i++ {
		a, b := nextInt()-1, nextInt()-1
		enemies[a] = append(enemies[a], b)
		enemies[b] = append(enemies[b], a)
	}

	sort.Sort(byDif(ctts))
	idToPos = make([]int, N)
	for i := range ctts {
		idToPos[ctts[i].id] = i
	}

	//fmt.Printf("idToPos=%v \n", idToPos)

	sumX = make([]int64, N)
	sumY = make([]int64, N)
	sumX[0] = int64(ctts[0].x)
	sumY[0] = int64(ctts[0].y)
	for i := 1; i < N; i++ {
		sumX[i] = sumX[i-1] + int64(ctts[i].x)
		sumY[i] = sumY[i-1] + int64(ctts[i].y)
	}

	answers := make([]int64, N)

	for cur := 0; cur < N; cur++ {
		ll := leftOf(sumX, cur-1) + int64(cur)*int64(ctts[cur].y)
		rr := rightOf(sumY, cur+1) + int64(N-cur-1)*int64(ctts[cur].x)

		total := ll + rr

		for _, enemyId := range enemies[ctts[cur].id] {
			enemyPos := idToPos[enemyId]
			if enemyPos < cur {
				total = total - int64(ctts[cur].y) - int64(ctts[enemyPos].x)
			} else {
				total = total - int64(ctts[cur].x) - int64(ctts[enemyPos].y)
			}
		}

		answers[ctts[cur].id] = total
	}

	output := bufio.NewWriterSize(os.Stdout, N*5)
	defer output.Flush()

	for _, x := range answers {
		fmt.Fprintf(output, "%d ", x)
	}
}