Madeline has an array $$$a$$$ of $$$n$$$ integers. A pair $$$(u, v)$$$ of integers forms an inversion in $$$a$$$ if:  $$$1 \le u < v \le n$$$.  $$$a_u > a_v$$$. Madeline recently found a magical paper, which allows her to write two indices $$$u$$$ and $$$v$$$ and swap the values $$$a_u$$$ and $$$a_v$$$. Being bored, she decided to write a list of pairs $$$(u_i, v_i)$$$ with the following conditions:  all the pairs in the list are distinct and form an inversion in $$$a$$$.  all the pairs that form an inversion in $$$a$$$ are in the list.  Starting from the given array, if you swap the values at indices $$$u_1$$$ and $$$v_1$$$, then the values at indices $$$u_2$$$ and $$$v_2$$$ and so on, then after all pairs are processed, the array $$$a$$$ will be sorted in non-decreasing order. Construct such a list or determine that no such list exists. If there are multiple possible answers, you may find any of them.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the length of the array. Next line contains $$$n$$$ integers $$$a_1,a_2,...,a_n$$$ $$$(1 \le a_i \le 10^9)$$$  — elements of the array.

Print -1 if no such list exists. Otherwise in the first line you should print a single integer $$$m$$$ ($$$0 \le m \le \dfrac{n(n-1)}{2}$$$) — number of pairs in the list. The $$$i$$$-th of the following $$$m$$$ lines should contain two integers $$$u_i, v_i$$$ ($$$1 \le u_i < v_i\le n$$$). If there are multiple possible answers, you may find any of them.

NoteIn the first sample test case the array will change in this order $$$[3,1,2] \rightarrow [2,1,3] \rightarrow [1,2,3]$$$.In the second sample test case it will be $$$[1,8,1,6] \rightarrow [1,6,1,8] \rightarrow [1,1,6,8]$$$.In the third sample test case the array is already sorted.

package main

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

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

var err error

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

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

	n := nextInt()
	arr, inds := make([]int, n), make([]int, n)
	for i := range arr {
		arr[i], inds[i] = nextInt(), i
	}

	sort.SliceStable(inds, func(a, b int) bool {
		return arr[inds[a]] < arr[inds[b]]
	})

	for i, v := range inds {
		arr[v] = i
	}

	moves := [][2]int{}
	for i := n - 1; i > 0; i-- {
		curr := [][2]int{}
		for j := 0; j < i; j++ {
			if arr[j] > arr[i] {
				curr = append(curr, [2]int{j, i})
			}
		}
		sort.Slice(curr, func(a, b int) bool {
			return arr[curr[a][0]] < arr[curr[b][0]]
		})
		moves = append(moves, curr...)
	}

	printf("%d\n", len(moves))
	for _, v := range moves {
		printf("%d %d\n", v[0]+1, v[1]+1)
	}
}

package main

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

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

	n := readNum(reader)
	A := readNNums(reader, n)
	res := solve(n, A)
	var buf bytes.Buffer
	buf.WriteString(fmt.Sprintf("%d\n", len(res)))
	for i := 0; i < len(res); i++ {
		buf.WriteString(fmt.Sprintf("%d %d\n", res[i][0], res[i][1]))
	}
	fmt.Print(buf.String())
}

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

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

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

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

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

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

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

	return i
}

func solve(n int, A []int) [][]int {
	ps := make([]Pair, n)

	for i := 0; i < n; i++ {
		ps[i] = Pair{A[i], i + 1}
	}

	sort.Sort(Pairs(ps))
	for i := 0; i < n; i++ {
		A[ps[i].second-1] = i
	}
	pos := make([]int, n+1)
	for i := 0; i < n; i++ {
		pos[A[i]+1] = i + 1
	}

	X := make([]int, n+1)
	for i := 1; i <= n; i++ {
		X[i] = A[i-1] + 1
	}

	var res [][]int

	for cur := n; cur > 0; cur-- {
		if X[cur] == cur {
			continue
		}
		x := X[cur] + 1

		for x <= cur {
			i, j := pos[x], cur
			res = append(res, []int{i, j})
			X[i], X[j] = X[j], X[i]
			//pos[x], pos[cur] = pos[cur], pos[x]
			pos[X[i]], pos[X[j]] = i, j
			x++
		}
	}

	return res
}

type Pair struct {
	first, second int
}

type Pairs []Pair

func (ps Pairs) Len() int {
	return len(ps)
}

func (ps Pairs) Less(i, j int) bool {
	return ps[i].first < ps[j].first || ps[i].first == ps[j].first && ps[i].second < ps[j].second
}

func (ps Pairs) Swap(i, j int) {
	ps[i], ps[j] = ps[j], ps[i]
}

package main

import (
	"fmt"
	"sort"
)

type pp struct {
	L, R int
}

var (
	n int
	a [1010]int
	p [1000010]pp
	pcnt int = 0
)

func main() {
	_, _ = fmt.Scan(&n)
	for i := 1; i <= n; i++ {
		_, _ = fmt.Scan(&a[i])
	}
	for i := 1; i <= n; i++ {
		for j := i + 1; j <= n; j++ {
			if a[i] > a[j] {
				pcnt++
				p[pcnt] = pp{i, j}
			}
		}
	}
	fmt.Println(pcnt)
	for i := 1; i <= pcnt; {
		j := i
		for j <= pcnt && p[j].L == p[i].L {
			j++
		}
		sort.Slice(p[i:j], func(x int, y int) bool {
			x += i
			y += i
			if a[p[x].R] != a[p[y].R] {
				return a[p[x].R] > a[p[y].R]
			} else {
				return p[x].R > p[y].R
			}
		})
		for k := i; k < j; k++ {
			fmt.Println(p[k].L, p[k].R)
		}
		i = j
	}
}

package main

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

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

var err error

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

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

	n := nextInt()
	arr := make([]int, n)
	for i := range arr {
		arr[i] = nextInt()
	}

	moves := [][2]int{}
	for i := n - 1; i > 0; i-- {
		curr := [][2]int{}
		for j := 0; j < i; j++ {
			if arr[j] > arr[i] {
				curr = append(curr, [2]int{j, i})
			}
		}
		sort.Slice(curr, func(a, b int) bool {
			return arr[curr[a][0]] < arr[curr[b][0]]
		})
		moves = append(moves, curr...)
	}

	printf("%d\n", len(moves))
	for _, v := range moves {
		printf("%d %d\n", v[0]+1, v[1]+1)
	}
}

package main

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

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

	n := readNum(reader)
	A := readNNums(reader, n)
	res := solve(n, A)
	var buf bytes.Buffer
	buf.WriteString(fmt.Sprintf("%d\n", len(res)))
	for i := 0; i < len(res); i++ {
		buf.WriteString(fmt.Sprintf("%d %d\n", res[i][0], res[i][1]))
	}
	fmt.Print(buf.String())
}

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

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

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

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

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

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

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

	return i
}

func solve(n int, A []int) [][]int {
	ps := make([]Pair, n)

	for i := 0; i < n; i++ {
		ps[i] = Pair{A[i], i + 1}
	}

	sort.Sort(Pairs(ps))
	for i := 0; i < n; i++ {
		A[ps[i].second-1] = i
	}
	pos := make([]int, n+1)
	for i := 0; i < n; i++ {
		pos[A[i]+1] = i + 1
	}

	X := make([]int, n+1)
	for i := 1; i <= n; i++ {
		X[i] = A[i-1] + 1
	}

	var res [][]int

	for cur := n; cur > 0; cur-- {
		if X[cur] == cur {
			continue
		}
		x := X[cur] + 1

		for x <= cur {
			i, j := pos[x], cur
			res = append(res, []int{i, j})
			X[i], X[j] = X[j], X[i]
			//pos[x], pos[cur] = pos[cur], pos[x]
			pos[X[i]], pos[X[j]] = i, j
			x++
		}
	}

	return res
}

type Pair struct {
	first, second int
}

type Pairs []Pair

func (ps Pairs) Len() int {
	return len(ps)
}

func (ps Pairs) Less(i, j int) bool {
	return ps[i].first < ps[j].first
}

func (ps Pairs) Swap(i, j int) {
	ps[i], ps[j] = ps[j], ps[i]
}

package main

import (
	"fmt"
	"sort"
)

type pp struct {
	L, R int
}

var (
	n int
	a [1010]int
	p [1000010]pp
	pcnt int = 0
)

func main() {
	_, _ = fmt.Scan(&n)
	for i := 1; i <= n; i++ {
		_, _ = fmt.Scan(&a[i])
	}
	for i := 1; i <= n; i++ {
		for j := i + 1; j <= n; j++ {
			if a[i] > a[j] {
				pcnt++
				p[pcnt] = pp{i, j}
			}
		}
	}
	fmt.Println(pcnt)
	for i := 1; i <= pcnt; {
		j := i
		for j <= pcnt && p[j].L == p[i].L {
			j++
		}
		sort.Slice(p[i:j], func(i int, j int) bool {
			if a[p[i].R] != a[p[j].R] {
				return a[p[i].R] > a[p[j].R]
			} else {
				return p[i].R > p[j].R
			}
		})
		for k := i; k < j; k++ {
			fmt.Println(p[k].L, p[k].R)
		}
		i = j
	}
}


The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:There are space-separated non-empty words of lowercase and uppercase Latin letters.There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen. It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word. When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding.The ad can occupy no more that k lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it.You should write a program that will find minimal width of the ad.

The first line contains number k (1 ≤ k ≤ 105). The second line contains the text of the ad — non-empty space-separated words of lowercase and uppercase Latin letters and hyphens. Total length of the ad don't exceed 106 characters.

NoteHere all spaces are replaced with dots.In the first example one of possible results after all word wraps looks like this:garage.for.sa-leThe second example:Edu-ca-tion-al.Ro-unds.are.so.fun

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)
	scanner.Scan()
	k, _ := strconv.Atoi(scanner.Text())
	x := make([]int, 0)
	for scanner.Scan() {
		s := scanner.Text()
		cur := 0
		for _, r := range s {
			cur++
			if r == '-' {
				x = append(x, cur)
				cur = 0
			}
		}
		cur++ //include last space
		x = append(x, cur)
	}
	x[len(x)-1]-- //remove the very last space

	var maxWord, total int
	for _, xx := range x {
		total += xx
		if xx > maxWord {
			maxWord = xx
		}
	}
	// fmt.Println(x)
	// fmt.Println(count(x, 8))
	l := maxWord
	r := total
	for l < r {
		m := (l + r) / 2
		if count(x, m) <= k {
			r = m
			continue
		}
		l = m + 1
	}
	fmt.Println(l)
}

func count(x []int, l int) int {
	total := 1
	cur := 0
	for _, xx := range x {
		if cur+xx > l {
			total++
			cur = 0
		}
		cur += xx
	}
	return total
}


Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:  a < b < c;  a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has  groups of three.Help Xenia, find the required partition or else say that it doesn't exist.

The first line contains integer n (3 ≤ n ≤ 99999) — the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3.

If the required partition exists, print  groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1.

package main

import (
	"sort"
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"runtime/pprof"
	"strconv"
)

func run(s *InOut) {
	n := s.Next()

	a := make([]int, n)
	for i := range a {
		a[i] = s.Next()
	}

	sort.Ints(a)

	result := make([][]int, 0)
	for len(a) > 0 {
		r := make([]int, 3)
		i, x := 0, a[0]
		r[0] = x
		a = a[1:]
		i = sort.Search(len(a), func(i int) bool { return x < a[i] && a[i] % x == 0})
		if i >= len(a) {
			s.Println(-1)
			return
		}
		x, r[1] = a[i], a[i]
		a = append(a[0:i], a[i+1:]...)
		i = sort.Search(len(a), func(i int) bool { return x < a[i] && a[i] % x == 0})
		if i >= len(a) {
			s.Println(-1)
			return
		}
		r[2] = a[i]
		a = append(a[0:i], a[i+1:]...)
		result = append(result, r)
	}

	for _, r := range result {
		s.Println(fmt.Sprintf("%d %d %d", r[0], r[1], r[2]))
	}
}

func main() {
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}
	s := NewInOut(os.Stdin, os.Stdout)
	defer s.Flush()

	run(s)
}

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

type InOut struct {
	*bufio.Reader
	*bufio.Writer
}

func NewInOut(r io.Reader, w io.Writer) *InOut {
	return &InOut{bufio.NewReader(r), bufio.NewWriter(w)}
}

// Get Next Integer
func (s *InOut) Next() (r int) {
	b, _ := s.ReadByte()
	p := 1
	for (b < '0' || '9' < b) && b != '-' {
		b, _ = s.ReadByte()
	}
	if b == '-' {
		p = -1
		b, _ = s.ReadByte()
	}
	for '0' <= b && b <= '9' {
		r = 10*r + int(b-'0')
		b, _ = s.ReadByte()
	}
	return r * p
}

func (s *InOut) NextInt64() (r int64) {
	b, _ := s.ReadByte()
	p := int64(1)
	for (b < '0' || '9' < b) && b != '-' {
		b, _ = s.ReadByte()
	}
	if b == '-' {
		p = -1
		b, _ = s.ReadByte()
	}
	for '0' <= b && b <= '9' {
		r = 10*r + int64(b-'0')
		b, _ = s.ReadByte()
	}
	return r * p
}

// Get Next Line String
func (s *InOut) NextLine() (r string) {
	b, _ := s.ReadByte()
	for b == '\r' || b == '\n' {
		b, _ = s.ReadByte()
	}
	buf := make([]byte, 0)
	for ; b != '\r' && b != '\n'; b, _ = s.ReadByte() {
		buf = append(buf, b)
	}
	return string(buf)
}

// Get Next String using delimiter whitespace
func (s *InOut) NextStr() (r string) {
	return string(s.NextBytes())
}

// Get Next String using delimiter whitespace
func (s *InOut) NextBytes() (r []byte) {
	b, _ := s.ReadByte()
	for b == '\n' || b == ' ' {
		b, _ = s.ReadByte()
	}
	buf := make([]byte, 0)
	for ; b != '\n' && b != ' '; b, _ = s.ReadByte() {
		buf = append(buf, b)
	}
	return buf
}

// Print Strings using the suitable way to change type
func (s *InOut) Print(os ...interface{}) {
	for _, o := range os {
		switch o.(type) {
		case byte:
			s.WriteByte(o.(byte))
		case string:
			s.WriteString(o.(string))
		case int:
			s.WriteString(strconv.Itoa(o.(int)))
		case int64:
			s.WriteString(strconv.FormatInt(o.(int64), 10))
		default:
			s.WriteString(fmt.Sprint(o))
		}
	}
}

// Print Strings using the suitable way to change type with new line
func (s *InOut) Println(os ...interface{}) {
	for _, o := range os {
		s.Print(o)
	}
	s.Print("\n")
}

// Print immediately with new line (for debug)
func (s *InOut) PrintlnNow(o interface{}) {
	fmt.Println(o)
}

package main
import (
	"fmt"
	"sort"
	//"unicode/utf8"
)

func main() {
	var n int
	fmt.Scan(&n)
	a:=make([]int,n)
	for i:=0;i<n;i++ {
		fmt.Scan(&a[i])
	}
	sort.Ints(a)
	flag:=false
	for i:=0;i<n/3;i++ {
			if a[i]>=a[i+n/3] || a[i+n/3]>=a[i+(n/3)*2] || a[i+n/3]%a[i]!=0 || a[i+(n/3)*2]%a[i+n/3]!=0 {
				fmt.Println("-1")
				flag=true
				break
			}
	}
	if flag==false {
		for i:=0;i<n/3;i++ {
			fmt.Println(a[i],a[i+n/3],a[i+(n/3)*2])
		}
	}
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    var n int
    cnt := make(map[int]int)
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        scanner.Scan()
        a, _ := strconv.Atoi(scanner.Text())
        cnt[a]++
    }
    if (cnt[5] != 0) || (cnt[7] != 0) || (cnt[1] != (n/3)) || (cnt[3] > cnt[6]) || (cnt[2] != (cnt[4]+cnt[6]-cnt[3])) {
        fmt.Println(-1)
    } else {
        for cnt[4] > 0 {
            fmt.Println(1,2,4); cnt[1]--; cnt[2]--; cnt[4]--;
        }
        for cnt[2] > 0 {
            fmt.Println(1,2,6); cnt[1]--; cnt[2]--; cnt[6]--;
        }
        for cnt[6] > 0 {
            fmt.Println(1,3,6); cnt[1]--; cnt[3]--; cnt[6]--;
        }
    }
}

// 342A-mic
package main

import (
    "fmt"
)

var n int
var a [8]int
var b int

func cond() bool {
    return (a[5] == 0 && a[7] == 0 && a[1] == n/3 && a[2] >= a[4] && a[2]-a[4]+a[3] == a[6])
}

func main() {

    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        fmt.Scan(&b)
        a[b]++
    }

    if !cond() {
        fmt.Println("-1")
    } else {
        for i := 0; i < a[4]; i++ {
            fmt.Println("1 2 4")
        }
        for i := 0; i < a[2]-a[4]; i++ {
            fmt.Println("1 2 6")
        }
        for i := 0; i < a[3]; i++ {
            fmt.Println("1 3 6")
        }
    }

}

package main

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

var (
	sc   *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr   *bufio.Writer  = bufio.NewWriter(os.Stdout)
	vals                = make([]int, 8)
)

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

func populate(a, b, c int, tri *[][]int) {
	for vals[a] > 0 && vals[b] > 0 && vals[c] > 0 {
		vals[a], vals[b], vals[c] = vals[a]-1, vals[b]-1, vals[c]-1
		*tri = append(*tri, []int{a, b, c})
	}
}

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	for i := 0; i < n; i++ {
		vals[nextInt()]++
	}
	tri := make([][]int, 0)
	populate(1, 2, 4, &tri)
	populate(1, 2, 6, &tri)
	populate(1, 3, 6, &tri)
	if n == len(tri)*3 {
		for _, t := range tri {
			fmt.Fprintln(wr, t[0], t[1], t[2])
		}
	} else {
		fmt.Fprintln(wr, -1)
	}
	wr.Flush()
}

package main

import (
	"sort"
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"runtime/pprof"
	"strconv"
)

func run(s *InOut) {
	n := s.Next()

	a := make([]int, n)
	for i := range a {
		a[i] = s.Next()
	}

	sort.Ints(a)

	for len(a) > 0 {
		r := make([]int, 3)
		i, x := 0, a[0]
		r[0] = x
		a = a[1:]
		i = sort.Search(len(a), func(i int) bool { return x < a[i] && a[i] % x == 0})
		if i >= len(a) {
			s.Println(-1)
			return
		}
		x, r[1] = a[i], a[i]
		a = append(a[0:i], a[i+1:]...)
		i = sort.Search(len(a), func(i int) bool { return x < a[i] && a[i] % x == 0})
		if i >= len(a) {
			s.Println(-1)
			return
		}
		r[2] = a[i]
		a = append(a[0:i], a[i+1:]...)
		s.Println(fmt.Sprintf("%d %d %d", r[0], r[1], r[2]))
	}
}

func main() {
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}
	s := NewInOut(os.Stdin, os.Stdout)
	defer s.Flush()

	run(s)
}

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

type InOut struct {
	*bufio.Reader
	*bufio.Writer
}

func NewInOut(r io.Reader, w io.Writer) *InOut {
	return &InOut{bufio.NewReader(r), bufio.NewWriter(w)}
}

// Get Next Integer
func (s *InOut) Next() (r int) {
	b, _ := s.ReadByte()
	p := 1
	for (b < '0' || '9' < b) && b != '-' {
		b, _ = s.ReadByte()
	}
	if b == '-' {
		p = -1
		b, _ = s.ReadByte()
	}
	for '0' <= b && b <= '9' {
		r = 10*r + int(b-'0')
		b, _ = s.ReadByte()
	}
	return r * p
}

func (s *InOut) NextInt64() (r int64) {
	b, _ := s.ReadByte()
	p := int64(1)
	for (b < '0' || '9' < b) && b != '-' {
		b, _ = s.ReadByte()
	}
	if b == '-' {
		p = -1
		b, _ = s.ReadByte()
	}
	for '0' <= b && b <= '9' {
		r = 10*r + int64(b-'0')
		b, _ = s.ReadByte()
	}
	return r * p
}

// Get Next Line String
func (s *InOut) NextLine() (r string) {
	b, _ := s.ReadByte()
	for b == '\r' || b == '\n' {
		b, _ = s.ReadByte()
	}
	buf := make([]byte, 0)
	for ; b != '\r' && b != '\n'; b, _ = s.ReadByte() {
		buf = append(buf, b)
	}
	return string(buf)
}

// Get Next String using delimiter whitespace
func (s *InOut) NextStr() (r string) {
	return string(s.NextBytes())
}

// Get Next String using delimiter whitespace
func (s *InOut) NextBytes() (r []byte) {
	b, _ := s.ReadByte()
	for b == '\n' || b == ' ' {
		b, _ = s.ReadByte()
	}
	buf := make([]byte, 0)
	for ; b != '\n' && b != ' '; b, _ = s.ReadByte() {
		buf = append(buf, b)
	}
	return buf
}

// Print Strings using the suitable way to change type
func (s *InOut) Print(os ...interface{}) {
	for _, o := range os {
		switch o.(type) {
		case byte:
			s.WriteByte(o.(byte))
		case string:
			s.WriteString(o.(string))
		case int:
			s.WriteString(strconv.Itoa(o.(int)))
		case int64:
			s.WriteString(strconv.FormatInt(o.(int64), 10))
		default:
			s.WriteString(fmt.Sprint(o))
		}
	}
}

// Print Strings using the suitable way to change type with new line
func (s *InOut) Println(os ...interface{}) {
	for _, o := range os {
		s.Print(o)
	}
	s.Print("\n")
}

// Print immediately with new line (for debug)
func (s *InOut) PrintlnNow(o interface{}) {
	fmt.Println(o)
}

package main

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

var (
	sc   *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr   *bufio.Writer  = bufio.NewWriter(os.Stdout)
	vals                = make([]int, 8)
)

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

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

func print(a, b, c int) (printed int) {
	for vals[a] > 0 && vals[b] > 0 && vals[c] > 0 {
		vals[a], vals[b], vals[c] = vals[a]-1, vals[b]-1, vals[c]-1
		fmt.Fprintln(wr, a, b, c)
		printed++
	}
	return
}

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	for i := 0; i < n; i++ {
		vals[nextInt()]++
	}
	printed := print(1, 2, 4) + print(1, 2, 6) + print(1, 3, 6)
	if printed == 0 {
		fmt.Fprintln(wr, -1)
	}
	wr.Flush()
}

package main

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

var (
	sc   *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr   *bufio.Writer  = bufio.NewWriter(os.Stdout)
	vals                = make([]int, 8)
)

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

func populate(a, b, c int, tri *[][]int) {
	for vals[a] > 0 && vals[b] > 0 && vals[c] > 0 {
		vals[a], vals[b], vals[c] = vals[a]-1, vals[b]-1, vals[c]-1
		*tri = append(*tri, []int{a, b, c})
	}
}

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	for i := 0; i < n; i++ {
		vals[nextInt()]++
	}
	tri := make([][]int, 0)
	populate(1, 2, 4, &tri)
	populate(1, 2, 6, &tri)
	populate(1, 3, 6, &tri)
	if n == cap(tri)*3 {
		for _, t := range tri {
			fmt.Fprintln(wr, t[0], t[1], t[2])
		}
	} else {
		fmt.Fprintln(wr, -1)
	}
	wr.Flush()
}


Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different!Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections a, b, c and d, such that there are two paths from a to c — one through b and the other one through d, he calls the group a "damn rhombus". Note that pairs (a, b), (b, c), (a, d), (d, c) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below:  Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him.Given that the capital of Berland has n intersections and m roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city.When rhombi are compared, the order of intersections b and d doesn't matter.

The first line of the input contains a pair of integers n, m (1 ≤ n ≤ 3000, 0 ≤ m ≤ 30000) — the number of intersections and roads, respectively. Next m lines list the roads, one per line. Each of the roads is given by a pair of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi) — the number of the intersection it goes out from and the number of the intersection it leads to. Between a pair of intersections there is at most one road in each of the two directions. It is not guaranteed that you can get from any intersection to any other one.

Print the required number of "damn rhombi".

package main

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

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	n, m := scanInt(scanner), scanInt(scanner)
	edges := make([][]int, m)
	parents := make([][]int, n+1)
	bilinks := make([][]int, n+1)
	for i := 1; i <= n; i++ {
		bilinks[i] = make([]int, n+1)
	}
	for i := 0; i < m; i++ {
		u, v := scanInt(scanner), scanInt(scanner)
		parents[v] = append(parents[v], u)
		edges[i] = []int{u, v}
	}
	for i := 0; i < m; i++ {
		b, c := edges[i][0], edges[i][1]
		for _, a := range parents[b] {
			if a != c {
				bilinks[a][c] += 1
			}
		}
	}
	count := 0
	for a := 1; a <= n; a++ {
		for c := 1; c <= n; c++ {
			x := bilinks[a][c]
			count += (x*x - x)/2
		}
	}
	writer.WriteString(fmt.Sprintf("%d\n", count))
}


Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position.In the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions. It is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.

The first line of the input contains a single integer n (3 ≤ n ≤ 100 000). Each of the next n lines contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109). It is guaranteed that no two stars lie at the same point, and there does not exist a line such that all stars lie on that line.

Print three distinct integers on a single line — the indices of the three points that form a triangle that satisfies the conditions stated in the problem. If there are multiple possible answers, you may print any of them.

NoteIn the first sample, we can print the three indices in any order.In the second sample, we have the following picture.   Note that the triangle formed by starts 1, 4 and 3 doesn't satisfy the conditions stated in the problem, as point 5 is not strictly outside of this triangle (it lies on it's border).

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 point struct {
	x, y, i int64
}

type byXY []point

func (s byXY) Len() int           { return len(s) }
func (s byXY) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byXY) Less(i, j int) bool { return s[i].x < s[j].x || s[i].x == s[j].x && s[i].y < s[j].y }

func area(a, b, c point) int64 {
	r := a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y)
	if r < 0 {
		return -r
	}
	return r
}

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

	n := readInt()
	p := make([]point, n)
	for i := range p {
		p[i] = point{readInt(), readInt(), int64(i + 1)}
	}
	sort.Sort(byXY(p))

	best := p[2]
	bestArea := area(p[0], p[1], best)
	for _, pp := range p[3:] {
		a := area(p[0], p[1], pp)
		if a != 0 && (bestArea == 0 || bestArea > a) {
			bestArea = a
			best = pp
		}
	}
	fmt.Println(p[0].i, p[1].i, best.i)
}

package main

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

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

func main() {
	defer out.Flush()
	var n int
	fmt.Fscan(in, &n)
	points := make(Points, n)
	for i, _ := range points {
		p := &Point{}
		p.index = i + 1
		fmt.Fscan(in, &p.x, &p.y)
		points[i] = p
	}
	sort.Sort(points)
	var a, b *Point
	for i, c := range points {
		if i >= 2 && area(a, b, c) != 0 {
			fmt.Fprintln(out, a.index, b.index, c.index)
			return
		}
		a, b = b, c
	}
}

func area(a, b, c *Point) int64 {
	return det(a.x-c.x, a.y-c.y, b.x-c.x, b.y-c.y)
}

func det(a, b, c, d int64) int64 {
	return a*d - b*c
}

type Point struct {
	x, y  int64
	index int
}

type Points []*Point

func (p Points) Less(i, j int) bool {
	return p[i].x < p[j].x || (p[i].x == p[j].x && p[i].y < p[j].y)
}

func (p Points) Len() int {
	return len(p)
}

func (p Points) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

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)
	for _, b := range in.Bytes() {
		res = res*10 + int64(b-'0')
	}
	return res
}

type point struct {
	x, y, i int64
}

type byXY []point

func (s byXY) Len() int           { return len(s) }
func (s byXY) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byXY) Less(i, j int) bool { return s[i].x < s[j].x || s[i].x == s[j].x && s[i].y < s[j].y }

func area(a, b, c point) int64 {
	r := a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y)
	if r < 0 {
		return -r
	}
	return r
}

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

	n := readInt()
	p := make([]point, n)
	for i := range p {
		p[i] = point{readInt(), readInt(), int64(i + 1)}
	}
	sort.Sort(byXY(p))

	best := p[2]
	bestArea := area(p[0], p[1], p[2])
	for _, pp := range p[2:] {
		a := area(p[0], p[1], pp)
		if bestArea == 0 || bestArea > a {
			bestArea = a
			best = pp
		}
	}
	fmt.Println(p[0].i, p[1].i, best.i)
}

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

type point struct {
	x, y, i int64
}

type byXY []point

func (s byXY) Len() int           { return len(s) }
func (s byXY) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byXY) Less(i, j int) bool { return s[i].x < s[j].x || s[i].x == s[j].x && s[i].y < s[j].y }

func area(a, b, c point) int64 {
	r := a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y)
	if r < 0 {
		return -r
	}
	return r
}

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

	n := readInt()
	p := make([]point, n)
	for i := range p {
		p[i] = point{readInt(), readInt(), int64(i + 1)}
	}
	sort.Sort(byXY(p))

	best := p[2]
	bestArea := area(p[0], p[1], best)
	for _, pp := range p[3:] {
		a := area(p[0], p[1], pp)
		if a != 0 && (bestArea == 0 || bestArea > a) {
			bestArea = a
			best = pp
		}
	}
	fmt.Println(p[0].i, p[1].i, best.i)
}

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)
	for _, b := range in.Bytes() {
		res = res*10 + int64(b-'0')
	}
	return res
}

type point struct {
	x, y, i int64
}

type byXY []point

func (s byXY) Len() int           { return len(s) }
func (s byXY) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byXY) Less(i, j int) bool { return s[i].x < s[j].x || s[i].x == s[j].x && s[i].y < s[j].y }

func area(a, b, c point) int64 {
	r := a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y)
	if r < 0 {
		return -r
	}
	return r
}

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

	n := readInt()
	p := make([]point, n)
	for i := range p {
		p[i] = point{readInt(), readInt(), int64(i + 1)}
	}
	sort.Sort(byXY(p))

	best := p[2]
	bestArea := area(p[0], p[1], best)
	for _, pp := range p[3:] {
		a := area(p[0], p[1], pp)
		if a != 0 && (bestArea == 0 || bestArea > a) {
			bestArea = a
			best = pp
		}
	}
	fmt.Println(p[0].i, p[1].i, best.i)
}


The polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y).  If the wind blows to the east, the boat will move to (x + 1, y).  If the wind blows to the south, the boat will move to (x, y - 1).  If the wind blows to the west, the boat will move to (x - 1, y).  If the wind blows to the north, the boat will move to (x, y + 1). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (ex, ey)?

The first line contains five integers t, sx, sy, ex, ey (1 ≤ t ≤ 105,  - 109 ≤ sx, sy, ex, ey ≤ 109). The starting location and the ending location will be different. The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).

If they can reach (ex, ey) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).

NoteIn the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.In the second sample, they cannot sail to the destination.

package main

import (
	"fmt"
)

func main() {
	var t, sx, sy, ex, ey int
	var wind string

	fmt.Scan(&t, &sx, &sy, &ex, &ey, &wind)
	ans, l := 0, len(wind)

	for i:=0; i<l; i++{
		if wind[i] == 'S' && sy > ey {
			sy--
		}
		if wind[i] == 'N' && sy < ey {
			sy++
		}
		if wind[i] == 'E' && sx < ex {
			sx++
		}
		if wind[i] == 'W' && sx > ex {
			sx--
		}
		ans++
		if sx == ex && sy == ey {
			break
		}
	}
	if sx == ex && sy == ey {
		fmt.Println(ans)
	} else {
		fmt.Println(-1)
	}
}

package main

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

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

  var t, fromX, fromY, toX, toY int64
  fmt.Fscanln(reader, &t, &fromX, &fromY, &toX, &toY)
  var n, e, s, w int64
  if fromX < toX {
    e = toX - fromX
  } else {
    w = fromX - toX
  }
  if fromY < toY {
    n = toY - fromY
  } else {
    s = fromY - toY
  }

  for i := int64(0); i < t; i++ {
    ch, _ := reader.ReadByte()
    if ch == 'N' && n > 0 {
      n--
    } else if ch == 'E' && e > 0 {
      e--
    } else if ch == 'S' && s > 0 {
      s--
    } else if ch == 'W' && w > 0 {
      w--
    }
    if n == 0 && e == 0 && s == 0 && w == 0 {
      writer.WriteString(fmt.Sprintf("%d\n", i+1))
      return
    }
  }
  writer.WriteString("-1\n")
}

package main

import "fmt"

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

func main() {
    var t,sx,sy,ex,ey int
    var s string
    fmt.Scan(&t,&sx,&sy,&ex,&ey)
    fmt.Scan(&s)
    dx := map[rune]int{'E':1,'S':0,'W':-1,'N':0}
    dy := map[rune]int{'E':0,'S':-1,'W':0,'N':1}
    ans := -1
    for k, v := range s {
        nx, ny := sx+dx[v], sy+dy[v]
        if (abs(nx-ex) < abs(sx-ex)) || (abs(ny-ey) < abs(sy-ey)) {
            sx, sy = nx, ny
        }
        if (sx == ex) && (sy == ey) {
            ans = k+1
            break
        }
    }
    fmt.Println(ans)
}

package main
import (
	"fmt"
)

func main() {
	var t, sx, sy, ex, ey, sec int
	var arah string
	sec=0
	fmt.Scan(&t, &sx, &sy, &ex, &ey, &arah)
	fmt.Scanln(arah)
	for i:=0; i<t; i++ {
		if arah[i]=='E' {
			sx+=1
			if sx<=ex {
				sec++
			} else {
				sx--
				sec++
			}
		} else if arah[i]=='S' {
			sy-=1
			if sy>=ey {
				sec++
			} else {
				sy++
				sec++
			}
		} else if arah[i]=='W' {
			sx-=1
			if sx>=ex {
				sec++
			} else {
				sx++
				sec++
			}
		} else if arah[i]=='N' {
			sy+=1
			if sy<=ey {
				sec++
			} else {
				sy--
				sec++
			}
		}
		if (sx==ex)&&(sy==ey) {
            		break
        	}
	}
	if (sx==ex)&&(sy==ey) {
		fmt.Println(sec)
	} else {
		fmt.Println("-1")
	}
}

//298B
package main

import (
	"fmt"
)

func main() {
	var (
		t, sx, sy, ex, ey int
		s                 string
	)
	fmt.Scan(&t, &sx, &sy, &ex, &ey, &s)
	ans, l := 0, len(s)

	for i := 0; i < l; i++ {
		if s[i] == 'S' && sy > ey {
			sy--
		}
		if s[i] == 'N' && sy < ey {
			sy++
		}
		if s[i] == 'E' && sx < ex {
			sx++
		}
		if s[i] == 'W' && sx > ex {
			sx--
		}
		ans++
		if sx == ex && sy == ey {
			break
		}
	}
	if sx == ex && sy == ey {
		fmt.Println(ans)
	} else {
		fmt.Println(-1)
	}
}

// 298B-mic_rizal
package main

import (
    "fmt"
)

func main() {
    var t, sx, sy, ex, ey int
    ANS := -1
    var x string
    fmt.Scan(&t, &sx, &sy, &ex, &ey, &x)
    for i := 0; i < t; i++ {
        if ex == sx && ey == sy && ANS == -1 {
            ANS = i - 1
        }
        if x[i] == 'N' && sy < ey {
            sy++
        } else if x[i] == 'S' && sy > ey {
            sy--
        } else if x[i] == 'E' && sx < ex {
            sx++
        } else if x[i] == 'W' && sx > ex {
            sx--
        }
    }
    if ex == sx && ey == sy && ANS == -1 {
        ANS = t
    } else if ANS == -1 {
        fmt.Println(ANS)
        return
    } else {
        fmt.Println(ANS + 1)
        return
    }

    fmt.Println(ANS)
}

//298B
package main

import (
	"fmt"
)

func main() {
	var (
		t, sx, sy, ex, ey int
		s                 string
	)
	fmt.Scan(&t, &sx, &sy, &ex, &ey, &s)
	ans, l := 0, len(s)

	for i := 0; i < l; i++ {
		if s[i] == 'S' && sy > ey {
			sy--
		}
		if s[i] == 'N' && sy < ey {
			sy++
		}
		if s[i] == 'E' && sx < ex {
			sx++
		}
		if s[i] == 'W' && sx > ex {
			sx--
		}
		ans++
		if sx == ex && sy == ey {
			break
		}
	}
	if sx != ex && sy != ey {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

// 298B-mic_rizal
package main

import (
    "fmt"
)

func main() {
    var t, sx, sy, ex, ey int
    ANS := -1
    var x string
    fmt.Scan(&t, &sx, &sy, &ex, &ey, &x)
    for i := 0; i < t; i++ {
        if ex == sx && ey == sy && ANS == -1 {
            ANS = i - 1
        }
        if x[i] == 'N' && sy < ey {
            sy++
        } else if x[i] == 'S' && sy > ey {
            sy--
        } else if x[i] == 'E' && sx < ex {
            sx++
        } else if x[i] == 'W' && sx > ex {
            sx--
        }
    }
    if ex == sx && ey == sy && ANS == -1 {
        ANS = t
    }
    if ANS == -1 {
        fmt.Println(ANS)
    } else {
        fmt.Println(ANS + 1)
    }
}


Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 < a_i < 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.

Print the maximum possible beauty of $$$k$$$ shelves in the new office.

package main

import "fmt"

func pos(a []int64, k int, m int64) bool {
	sum := make([]int64, len(a)+1)
	for i := range a {
		sum[i+1] = sum[i] + a[i]
	}

	dp := make([][]bool, k+1)
	dp[0] = make([]bool, len(a)+1)
	dp[0][0] = true
	for i := 1; i <= k; i++ {
		dp[i] = make([]bool, len(a)+1)
		for used := i; used <= len(a); used++ {
			for prev := i - 1; prev < used; prev++ {
				dp[i][used] = dp[i-1][prev] && (sum[used]-sum[prev])&m == m
				if dp[i][used] {
					break
				}
			}
		}
	}
	return dp[k][len(a)]
}

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	a := make([]int64, n)
	for i := range a {
		fmt.Scan(&a[i])
	}
	cur := int64(0)
	for bit := int64(1 << 60); bit > 0; bit /= 2 {
		if pos(a, k, cur|bit) {
			cur |= bit
		}
	}
	fmt.Println(cur)
}

package main

import "fmt"

const maxn  = 55

var (
	n, k int
	sum [maxn]int64
	dp [maxn][maxn]bool
)

func read() {
	fmt.Scan(&n, &k)
	var tmp int64
	for i := 1; i <= n; i++ {
		fmt.Scan(&tmp)
		sum[i] = sum[i - 1] + tmp
	}
}

func check(x int64) bool {
	for i := 1; i <= n; i++ {
		dp[i][1] = (sum[i] & x) == x
	}
	for i := 2; i <= k; i++ {
		for j := i; j <= n; j++ {
			dp[j][i] = false
			for l := i - 1; l < j; l++ {
				if dp[l][i - 1] && ((sum[j] - sum[l]) & x) == x {
					dp[j][i] = true
				}
			}
		}
	}
	return dp[n][k]
}

func solve() {
	var ans int64 = 0
	for i := 60; i >= 0; i-- {
		if check(ans + (1 << uint(i))) {
			ans += 1 << uint(i)
		}
	}
	fmt.Println(ans)
}

func main() {
	read()
	solve()
}

package main

import . "fmt"

func main() {
	var n, k int
	Scan(&n, &k)
	sum := make([]uint64, n+1)
	for i := 1; i <= n; i++ {
		var a uint64
		Scan(&a)
		sum[i] = sum[i-1] + a
	}

	ans := uint64(0)
	for i := 55; i >= 0; i-- {
		bits := ans | 1<<uint(i)
		var dp [51][51]bool
		for r := 1; r <= n; r++ {
			dp[1][r] = bits&sum[r] == bits
		}
		for i := 2; i <= k; i++ {
			for l := i - 1; l < n; l++ {
				if dp[i-1][l] {
					for r := l + 1; r <= n; r++ {
						dp[i][r] = dp[i][r] || bits&(sum[r]-sum[l]) == bits
					}
				}
			}
		}
		if dp[k][n] {
			ans = bits
		}
	}
	Println(ans)
}

package main

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

func found(bits uint64, sum []uint64, k int) bool {
	n := len(sum) - 1
	var dp [51][51]bool
	for r := 1; r <= n; r++ {
		dp[1][r] = bits&sum[r] == bits
	}
	for i := 2; i <= k; i++ {
		for l := i - 1; l < n; l++ {
			if dp[i-1][l] {
				for r := l + 1; r <= n; r++ {
					dp[i][r] = dp[i][r] || bits&(sum[r]-sum[l]) == bits
				}
			}
		}
	}
	return dp[k][n]
}

func Sol981D(reader io.Reader, writer io.Writer) {
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n, k int
	Fscan(in, &n, &k)
	sum := make([]uint64, n+1)
	for i := 1; i <= n; i++ {
		var a uint64
		Fscan(in, &a)
		sum[i] = sum[i-1] + a
	}

	ans := uint64(0)
	for i := 55; i >= 0; i-- {
		pow2 := uint64(1) << uint(i)
		if found(ans|pow2, sum, k) {
			ans |= pow2
		}
	}

	Fprintln(out, ans)
}

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

package main

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

type Contest struct {
	in *bufio.Scanner
	out io.Writer
}

func NewSubmitContest() *Contest {
	C := &Contest{bufio.NewScanner(os.Stdin), os.Stdout}
	C.SetSplit(bufio.ScanWords)
	return C
}

func NewTestContest(testIn string, testOut *bytes.Buffer) *Contest  {
	C := &Contest{bufio.NewScanner(strings.NewReader(testIn)), testOut}
	C.SetSplit(bufio.ScanWords)
	return C
}

func (C *Contest) SetSplit(split bufio.SplitFunc) *Contest  {
	C.in.Split(split)
	return C
}

func (C *Contest) InStr() string {
	C.in.Scan()
	return C.in.Text()
}

func (C *Contest) InBytes() []byte {
	C.in.Scan()
	return C.in.Bytes()
}

func (C *Contest) InInt() int {
	C.in.Scan()
	i, _ := strconv.Atoi(C.in.Text())
	return i
}

func (C *Contest) InInt64() int64 {
	C.in.Scan()
	i, _ := strconv.ParseInt(C.in.Text(), 10, 64)
	return i
}

func (C *Contest) Out(format string, a ...interface{}) {
	fmt.Fprintf(C.out, format, a...)
}

func (C *Contest) MaxInt64(i1, i2 int64) int64 {
	if i1 > i2 {
		return i1
	}
	return i2
}

var (
	n, k int
	a []int64
	dpDone [][]bool
	dpRes [][]bool
)

// https://codeforces.com/contest/981/problem/D
func problem(C *Contest) {
	n = C.InInt()
	k = C.InInt()

	a = make([]int64, n)
	for i := range a {
		a[i] = C.InInt64()
	}

	dpRes = make([][]bool, n + 1)
	for i := range dpRes {
		dpRes[i] = make([]bool, k + 1)
	}

	var best, x int64
	for i := 62; i >= 0; i-- {
		dpDone = make([][]bool, n + 1)
		for i := range dpDone {
			dpDone[i] = make([]bool, k + 1)
		}

		x = int64(1) << uint(i)
		if checkSplit(best|x, n, k) {
			best |= x
		}
	}

	C.Out("%d\n", best)
}

func checkSplit(x int64, n int, k int) bool {
	if k < 0 {
		return false
	} else if dpDone[n][k] {
		return dpRes[n][k]
	} else {
		dpDone[n][k] = true
	}

	sum := int64(0)
	for i := n - 1; i >= 0; i-- {
		sum += a[i]
		if sum & x == x {
			if checkSplit(x, i, k - 1) {
				dpRes[n][k] = true
				return dpRes[n][k]
			}
		}
	}

	dpRes[n][k] = (n == 0) && (k == 0)
	return dpRes[n][k]
}

func main() {
	c := NewSubmitContest()
	problem(c)
}

package main

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

type Contest struct {
	in *bufio.Scanner
	out io.Writer
}

func NewSubmitContest() *Contest {
	C := &Contest{bufio.NewScanner(os.Stdin), os.Stdout}
	C.SetSplit(bufio.ScanWords)
	return C
}

func NewTestContest(testIn string, testOut *bytes.Buffer) *Contest  {
	C := &Contest{bufio.NewScanner(strings.NewReader(testIn)), testOut}
	C.SetSplit(bufio.ScanWords)
	return C
}

func (C *Contest) SetSplit(split bufio.SplitFunc) *Contest  {
	C.in.Split(split)
	return C
}

func (C *Contest) InStr() string {
	C.in.Scan()
	return C.in.Text()
}

func (C *Contest) InBytes() []byte {
	C.in.Scan()
	return C.in.Bytes()
}

func (C *Contest) InInt() int {
	C.in.Scan()
	i, _ := strconv.Atoi(C.in.Text())
	return i
}

func (C *Contest) InInt64() int64 {
	C.in.Scan()
	i, _ := strconv.ParseInt(C.in.Text(), 10, 64)
	return i
}

func (C *Contest) Out(format string, a ...interface{}) {
	fmt.Fprintf(C.out, format, a...)
}

func (C *Contest) MaxInt64(i1, i2 int64) int64 {
	if i1 > i2 {
		return i1
	}
	return i2
}

var (
	n, k int
	a []int64
	best, x int64
	cDone, cRes [][]bool
)

// https://codeforces.com/contest/981/problem/D
func problem(C *Contest) {
	n = C.InInt()
	k = C.InInt()

	a = make([]int64, n)
	for i := range a {
		a[i] = C.InInt64()
	}

	cRes = newCache(n, k)
	best = int64(0)
	for i := 62; i >= 0; i-- {
		cDone = newCache(n, k)
		x = int64(1) << uint(i)
		if checkSplit(best|x, n, k) {
			best |= x
		}
	}

	C.Out("%d\n", best)
}

func newCache(n int, k int) [][]bool {
	c := make([][]bool, n + 1)
	for i := range c {
		c[i] = make([]bool, k + 1)
	}

	return c
}

func checkSplit(x int64, n int, k int) bool {
	if k < 0 {
		return false
	} else if cDone[n][k] {
		return cRes[n][k]
	} else {
		cDone[n][k] = true
	}

	sum := int64(0)
	for i := n - 1; i >= 0; i-- {
		sum += a[i]
		if sum & x == x {
			if checkSplit(x, i, k - 1) {
				cRes[n][k] = true
				return cRes[n][k]
			}
		}
	}

	cRes[n][k] = (n == 0) && (k == 0)
	return cRes[n][k]
}

func main() {
	c := NewSubmitContest()
	problem(c)
}

package main

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

type Contest struct {
	in *bufio.Scanner
	out io.Writer
}

func NewSubmitContest() *Contest {
	C := &Contest{bufio.NewScanner(os.Stdin), os.Stdout}
	C.SetSplit(bufio.ScanWords)
	return C
}

func NewTestContest(testIn string, testOut *bytes.Buffer) *Contest  {
	C := &Contest{bufio.NewScanner(strings.NewReader(testIn)), testOut}
	C.SetSplit(bufio.ScanWords)
	return C
}

func (C *Contest) SetSplit(split bufio.SplitFunc) *Contest  {
	C.in.Split(split)
	return C
}

func (C *Contest) InStr() string {
	C.in.Scan()
	return C.in.Text()
}

func (C *Contest) InBytes() []byte {
	C.in.Scan()
	return C.in.Bytes()
}

func (C *Contest) InInt() int {
	C.in.Scan()
	i, _ := strconv.Atoi(C.in.Text())
	return i
}

func (C *Contest) InInt64() int64 {
	C.in.Scan()
	i, _ := strconv.ParseInt(C.in.Text(), 10, 64)
	return i
}

func (C *Contest) Out(format string, a ...interface{}) {
	fmt.Fprintf(C.out, format, a...)
}

func (C *Contest) MaxInt64(i1, i2 int64) int64 {
	if i1 > i2 {
		return i1
	}
	return i2
}

var (
	n, k int
	a []int64
)

// https://codeforces.com/contest/981/problem/D
func problem(C *Contest) {
	n = C.InInt()
	k = C.InInt()

	a = make([]int64, n)
	for i := range a {
		a[i] = C.InInt64()
	}

	var best, x int64
	for i := uint(10); i > 0; i-- {
		x = int64(1) << i
		if checkSplit(best|x, n, k) {
			best |= x
		}
	}

	C.Out("%d\n", best)
}

func checkSplit(x int64, n int, k int) bool {
	sum := int64(0)
	for i := n - 1; i >= 0; i-- {
		sum += a[i]
		if sum & x == x {
			if checkSplit(x, i, k - 1) {
				return true
			}
		}
	}

	return k == 0
}

func main() {
	c := NewSubmitContest()
	problem(c)
}

package main

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

type Contest struct {
	in *bufio.Scanner
	out io.Writer
}

func NewSubmitContest() *Contest {
	C := &Contest{bufio.NewScanner(os.Stdin), os.Stdout}
	C.SetSplit(bufio.ScanWords)
	return C
}

func NewTestContest(testIn string, testOut *bytes.Buffer) *Contest  {
	C := &Contest{bufio.NewScanner(strings.NewReader(testIn)), testOut}
	C.SetSplit(bufio.ScanWords)
	return C
}

func (C *Contest) SetSplit(split bufio.SplitFunc) *Contest  {
	C.in.Split(split)
	return C
}

func (C *Contest) InStr() string {
	C.in.Scan()
	return C.in.Text()
}

func (C *Contest) InBytes() []byte {
	C.in.Scan()
	return C.in.Bytes()
}

func (C *Contest) InInt() int {
	C.in.Scan()
	i, _ := strconv.Atoi(C.in.Text())
	return i
}

func (C *Contest) InInt64() int64 {
	C.in.Scan()
	i, _ := strconv.ParseInt(C.in.Text(), 10, 64)
	return i
}

func (C *Contest) Out(format string, a ...interface{}) {
	fmt.Fprintf(C.out, format, a...)
}

func (C *Contest) MaxInt64(i1, i2 int64) int64 {
	if i1 > i2 {
		return i1
	}
	return i2
}

var (
	n, k int
	a []int64
)

// https://codeforces.com/contest/981/problem/D
func problem(C *Contest) {
	n = C.InInt()
	k = C.InInt()

	a = make([]int64, n)
	for i := range a {
		a[i] = C.InInt64()
	}

	var best, x int64
	for i := uint(63); i > 0; i-- {
		x = int64(1) << i
		if checkSplit(best|x, n, k) {
			best |= x
		}
	}

	C.Out("%d\n", best)
}

func checkSplit(x int64, n int, k int) bool {
	sum := int64(0)
	for i := n - 1; i >= 0; i-- {
		sum += a[i]
		if sum & x == x {
			if checkSplit(x, i, k - 1) {
				return true
			}
		}
	}

	return (k == 0) && (n == 0)
}

func main() {
	c := NewSubmitContest()
	problem(c)
}


Xenia the vigorous detective faced n (n ≥ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right. Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is x, he can pass the note to another spy, either x - 1 or x + 1 (if x = 1 or x = n, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.But nothing is that easy. During m steps Xenia watches some spies attentively. Specifically, during step ti (steps are numbered from 1) Xenia watches spies numbers li, li + 1, li + 2, ..., ri (1 ≤ li ≤ ri ≤ n). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.You've got s and f. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy s to spy f as quickly as possible (in the minimum number of steps).

The first line contains four integers n, m, s and f (1 ≤ n, m ≤ 105; 1 ≤ s, f ≤ n; s ≠ f; n ≥ 2). Each of the following m lines contains three integers ti, li, ri (1 ≤ ti ≤ 109, 1 ≤ li ≤ ri ≤ n). It is guaranteed that t1 < t2 < t3 < ... < tm.

Print k characters in a line: the i-th character in the line must represent the spies' actions on step i. If on step i the spy with the note must pass the note to the spy with a lesser number, the i-th character should equal "L". If on step i the spy with the note must pass it to the spy with a larger number, the i-th character must equal "R". If the spy must keep the note at the i-th step, the i-th character must equal "X". As a result of applying the printed sequence of actions spy s must pass the note to spy f. The number of printed characters k must be as small as possible. Xenia must not catch the spies passing the note. If there are miltiple optimal solutions, you can print any of them. It is guaranteed that the answer exists.

// 342B
package main

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

func main() {
	var n, m, s, f, t, l, r, i uint64
	in := bufio.NewReader(os.Stdin)
	t, i = 0, 0
	fmt.Scan(&n, &m, &s, &f)
	for ; ; i++ {
		if t == i && i < m {
			fmt.Fscan(in, &t)
		}
		if t == i+1 {
			fmt.Fscan(in, &l, &r)
		} else {
			l = 0
			r = 0
		}
		if s < f && (s+1 < l || s > r) {
			fmt.Print(string('R'))
			s++
		} else if s > f && (s < l || s-1 > r) {
			fmt.Print(string('L'))
			s--
		} else if s == f {
			break
		} else {
			fmt.Print(string('X'))
		}
	}
}

package main

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

var (
	sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr *bufio.Writer  = bufio.NewWriter(os.Stdout)
)

type Watch struct{ t, l, r int }

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

func main() {
	sc.Split(bufio.ScanWords)
	_, m, s, f := nextInt(), nextInt(), nextInt(), nextInt()
	watch := make([]Watch, m)
	for i := 0; i < m; i++ {
		watch[i].t, watch[i].l, watch[i].r = nextInt(), nextInt(), nextInt()
	}

	for t := 1; s != f; t++ {
		neigh, dir := s+1, "R"
		if s > f {
			neigh, dir = s-1, "L"
		}
		if len(watch) > 0 && watch[0].t == t && (watch[0].l <= s && s <= watch[0].r || watch[0].l <= neigh && neigh <= watch[0].r) {
			fmt.Fprint(wr, "X")
		} else {
			fmt.Fprint(wr, dir)
			s = neigh
		}
		if len(watch) > 0 && watch[0].t == t {
			watch = watch[1:]
		}
	}
	fmt.Fprintln(wr)
	wr.Flush()
}

package main

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

var (
	sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
	wr *bufio.Writer  = bufio.NewWriter(os.Stdout)
)

type Watch struct{ t, l, r int }

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

func main() {
	sc.Split(bufio.ScanWords)
	_, m, s, f := nextInt(), nextInt(), nextInt(), nextInt()
	watch := make([]Watch, m)
	for i := 0; i < m; i++ {
		watch[i].t, watch[i].l, watch[i].r = nextInt(), nextInt(), nextInt()
	}

	for t := 1; s != f; t++ {
		neigh, dir := s+1, "R"
		if s > f {
			neigh, dir = s-1, "L"
		}
		if len(watch) > 0 && watch[0].t == t && (watch[0].l <= s && s <= watch[0].r || watch[0].l <= neigh && neigh <= watch[0].r) {
			fmt.Fprint(wr, "X")
			watch = watch[1:]
		} else {
			fmt.Fprint(wr, dir)
			s = neigh
		}
	}
	fmt.Fprintln(wr)
	wr.Flush()
}


Hongcow likes solving puzzles.One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.

The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece. The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space. It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.

Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.

NoteFor the first sample, one example of a rectangle we can form is as follows 111222111222For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle: .......XX................

package main

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

func solve() {
    m, _ := readInt(), readInt()
    a := make([]string, m)
    is, js, cnt := []int{}, []int{}, 0
    for i := range a {
        a[i] = readString()
        for j, r := range a[i] {
            if r == 'X' {
                cnt++
                is = append(is, i)
                js = append(js, j)
            }
        }
    }
    sort.Ints(is)
    sort.Ints(js)
    ans := "NO"
    if s := (is[len(is)-1]-is[0]+1) * (js[len(js)-1]-js[0]+1); s == cnt {
        ans = "YES"
    }
    fmt.Println(ans)
}

// Helpers

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func main() {
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

// Math

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

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

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

// IO

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

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

func readInt64() int64 {
	v, _ := strconv.ParseInt(readString(), 10, 64)
	return v
}

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

func readInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := 0; i < n; i++ {
		res[i] = readInt64()
	}
	return res
}

// Sort

type Ints64 []int64

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

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

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

func main() {
	var n, m int
	fmt.Scanf("%v %v\n", &n, &m)
	// is a rectangle if each line is a copy of the line above
	reader := bufio.NewReader(os.Stdin)
	//scanner.Scan() //get first line
	prevline,_ := reader.ReadString('\n')
	blank := strings.Repeat(".", m) + "\n"
	//fmt.Println("Prev: ",prevline)
	//fmt.Println("blank: ",blank)
	//fmt.Println(strings.Compare(strings.TrimSpace(prevline), strings.TrimSpace(blank)))
	count := 0
	for i := 0; i < n; i++ {
		if strings.Compare(strings.TrimSpace(prevline), strings.TrimSpace(blank)) == 0 {
			//fmt.Println("Blank found - retrying: ", prevline)
			prevline,_ = reader.ReadString('\n') //read until first nonblank
			count += 1
		}
	}
	//fmt.Println("Prevline:", prevline)
	rect := 1
	for i := 0; i < n - count - 1; i++ {
		nextline,_ := reader.ReadString('\n')
		//fmt.Println(i)
		//fmt.Println("Nextline: ",nextline)
		if strings.Compare(prevline, nextline) == 0 {
			// so far so good
			prevline = nextline
		} else {
			if strings.Compare(strings.TrimSpace(nextline), strings.TrimSpace(blank)) != 0 {
				rect = 0
				fmt.Println("NO")
				break
			}
			break
		}
	}
	if rect == 1 {
		fmt.Println("YES")
	}

}

package main

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

func main() {
  var n, m int
  in := bufio.NewReader(os.Stdin)
  fmt.Fscan(in, &n, &m)
  startx, starty := n, m
  finx, finy := 0, 0
  count := 0
  for i := 0; i < n; i++ {
    var s string
    fmt.Fscan(in, &s)
    for k := 0; k < m; k++ {
      if s[k] == 'X' {
        if startx > i {
          startx = i
        }
        if starty > k {
          starty = k
        }
        if finx < i {
          finx = i
        }
        if finy < k {
          finy = k
        }
        count++
      }
    }
  }

  shouldbe := (finx - startx+1) * (finy - starty+1)
  if shouldbe == count {
    fmt.Println("YES")
  } else {
    fmt.Println("NO")
  }
}

package main

import "fmt"

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	var p []string
	for i := 0; i < n; i++ {
		var s string
		fmt.Scan(&s)
		p = append(p, s)
	}
	sV := 0
	for i := 0; i < m; i++ {
		s := 0
		for j := 0; j < n; j++ {
			if p[j][i] == 'X' {
				s++
			}
		}
		if sV == 0 {
			sV = s
			continue
		}
		if s != sV && s != 0 {
			fmt.Println("NO")
			return
		}
	}
	sH := 0
	for i := 0; i < n; i++ {
		s := 0
		for j := 0; j < m; j++ {
			if p[i][j] == 'X' {
				s++
			}
		}
		if sH == 0 {
			sH = s
			continue
		}
		if s != sH && s != 0 {
			fmt.Println("NO")
			return
		}
	}
	fmt.Println("YES")
}

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

func main() {
	var n, m int
	fmt.Scanf("%v %v\n", &n, &m)
	// is a rectangle if each line is a copy of the line above
	reader := bufio.NewReader(os.Stdin)
	//scanner.Scan() //get first line
	prevline,_ := reader.ReadString('\n')
	blank := strings.Repeat(".", m) + "\n"
	count := 0
	for i := 0; i < n; i++ {
		if strings.Compare(prevline, blank) != 0 {
			prevline,_ = reader.ReadString('\n') //read until first nonblank
			count += 1
		}
	}
	//fmt.Println("Prevline:", prevline)
	rect := 1
	for i := 0; i < n - count; i++ {
		nextline,_ := reader.ReadString('\n')
		//fmt.Println(i)
		//fmt.Println("Nextline: ",nextline)
		if strings.Compare(prevline, nextline) == 0 {
			// so far so good
			prevline = nextline
		} else {
			if strings.Compare(nextline, blank) != 0 {
				rect = 0
				fmt.Println("NO")
				break
			}
			break
		}
	}
	if rect == 1 {
		fmt.Println("YES")
	}

}

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

func main() {
	var n, m int
	fmt.Scanf("%v %v\n", &n, &m)
	// is a rectangle if each line is a copy of the line above
	reader := bufio.NewReader(os.Stdin)
	//scanner.Scan() //get first line
	prevline,_ := reader.ReadString('\n')
	//fmt.Println("Prevline:", prevline)
	rect := 1
	for i := 0; i < n - 1; i++ {
		nextline,_ := reader.ReadString('\n')
		//fmt.Println(i)
		//fmt.Println("Nextline: ",nextline)
		if strings.Compare(prevline, nextline) == 0 {
			// so far so good
		} else {
			rect = 0
			fmt.Println("NO")
			break
		}
	}
	if rect == 1 {
		fmt.Println("YES")
	}

}


There are n cities in Berland. Some pairs of them are connected with m directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities (x, y) there is at most one road from x to y.A path from city s to city t is a sequence of cities p1, p2, ... , pk, where p1 = s, pk = t, and there is a road from city pi to city pi + 1 for each i from 1 to k - 1. The path can pass multiple times through each city except t. It can't pass through t more than once.A path p from s to t is ideal if it is the lexicographically minimal such path. In other words, p is ideal path from s to t if for any other path q from s to t pi < qi, where i is the minimum integer such that pi ≠ qi.There is a tourist agency in the country that offers q unusual excursions: the j-th excursion starts at city sj and ends in city tj. For each pair sj, tj help the agency to study the ideal path from sj to tj. Note that it is possible that there is no ideal path from sj to tj. This is possible due to two reasons:   there is no path from sj to tj;  there are paths from sj to tj, but for every such path p there is another path q from sj to tj, such that pi > qi, where i is the minimum integer for which pi ≠ qi. The agency would like to know for the ideal path from sj to tj the kj-th city in that path (on the way from sj to tj).For each triple sj, tj, kj (1 ≤ j ≤ q) find if there is an ideal path from sj to tj and print the kj-th city in that path, if there is any.

The first line contains three integers n, m and q (2 ≤ n ≤ 3000,0 ≤ m ≤ 3000, 1 ≤ q ≤ 4·105) — the number of cities, the number of roads and the number of excursions. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), denoting that the i-th road goes from city xi to city yi. All roads are one-directional. There can't be more than one road in each direction between two cities. Each of the next q lines contains three integers sj, tj and kj (1 ≤ sj, tj ≤ n, sj ≠ tj, 1 ≤ kj ≤ 3000).

In the j-th line print the city that is the kj-th in the ideal path from sj to tj. If there is no ideal path from sj to tj, or the integer kj is greater than the length of this path, print the string '-1' (without quotes) in the j-th line.

package main

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

var in = bufio.NewScanner(os.Stdin)

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

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

	n := readInt()
	m := readInt()
	q := readInt()

	edges := make([][]int, n+1)
	for i := 0; i < m; i++ {
		x := readInt()
		y := readInt()
		edges[x] = append(edges[x], y)
	}
	for _, e := range edges {
		sort.Ints(e)
	}

	ans := make([]int, q)
	type query struct {
		k, idx int
	}
	queries := make([]map[int][]query, n+1)
	for i := 0; i < q; i++ {
		s := readInt()
		t := readInt()
		if queries[s] == nil {
			queries[s] = make(map[int][]query)
		}
		queries[s][t] = append(queries[s][t], query{readInt(), i})
	}

	var stack []int
	looper := make(map[int]bool)
	visited := make([]int, n+1)
	for i := 1; i <= n; i++ {
		if len(queries[i]) == 0 {
			continue
		}
		stack = stack[:0]
		var dfs func(int)
		dfs = func(v int) {
			stack = append(stack, v)
			visited[v] = -i
			for _, q := range queries[i][v] {
				if ans[q.idx] != 0 {
					continue
				}
				if len(looper) != 0 || q.k > len(stack) {
					ans[q.idx] = -1
				} else {
					ans[q.idx] = stack[q.k-1]
				}
			}
			for _, u := range edges[v] {
				if visited[u] == i {
					continue
				}
				if visited[u] == -i {
					looper[u] = true
					continue
				}
				dfs(u)
			}
			visited[v] = i
			stack = stack[:len(stack)-1]
			delete(looper, v)
		}
		dfs(i)
	}

	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	for _, a := range ans {
		if a == 0 {
			a = -1
		}
		fmt.Fprintln(out, a)
	}
}

package main

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

var in = bufio.NewScanner(os.Stdin)

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

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

	n := readInt()
	m := readInt()
	q := readInt()

	edges := make([][]int, n+1)
	for i := 0; i < m; i++ {
		x := readInt()
		y := readInt()
		edges[x] = append(edges[x], y)
	}
	for _, e := range edges {
		sort.Ints(e)
	}

	ans := make([]int, q)
	type query struct {
		k, idx int
	}
	queries := make([]map[int][]query, n+1)
	for i := 0; i < q; i++ {
		s := readInt()
		t := readInt()
		if queries[s] == nil {
			queries[s] = make(map[int][]query)
		}
		queries[s][t] = append(queries[s][t], query{readInt(), i})
	}

	var stack, looper []int
	visited := make([]int, n+1)
	for i := 1; i <= n; i++ {
		if len(queries[i]) == 0 {
			continue
		}
		stack = stack[:0]
		looper = looper[:0]
		var dfs func(int)
		dfs = func(v int) {
			stack = append(stack, v)
			visited[v] = -i
			for _, q := range queries[i][v] {
				if len(looper) > 0 || q.k > len(stack) {
					ans[q.idx] = -1
				} else {
					ans[q.idx] = stack[q.k-1]
				}
			}
			for _, u := range edges[v] {
				if visited[u] == i {
					continue
				}
				if visited[u] == -i {
					looper = append(looper, u)
					continue
				}
				dfs(u)
			}
			visited[v] = i
			stack = stack[:len(stack)-1]
			if l := len(looper); l > 0 && looper[l-1] == v {
				looper = looper[:l-1]
			}
		}
		dfs(i)
	}

	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	for _, a := range ans {
		if a == 0 {
			a = -1
		}
		fmt.Fprintln(out, a)
	}
}

package main

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

var in = bufio.NewScanner(os.Stdin)

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

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

	n := readInt()
	m := readInt()
	q := readInt()

	edges := make([][]int, n+1)
	for i := 0; i < m; i++ {
		x := readInt()
		y := readInt()
		edges[x] = append(edges[x], y)
	}
	for _, e := range edges {
		sort.Ints(e)
	}

	ans := make([]int, q)
	type query struct {
		k, idx int
	}
	queries := make([]map[int][]query, n+1)
	for i := 0; i < q; i++ {
		s := readInt()
		t := readInt()
		if queries[s] == nil {
			queries[s] = make(map[int][]query)
		}
		queries[s][t] = append(queries[s][t], query{readInt(), i})
	}

	var stack, looper []int
	visited := make([]int, n+1)
	for i := 1; i <= n; i++ {
		if len(queries[i]) == 0 {
			continue
		}
		stack = stack[:0]
		looper = looper[:0]
		var dfs func(int)
		dfs = func(v int) {
			stack = append(stack, v)
			visited[v] = -i
			for _, q := range queries[i][v] {
				if ans[q.idx] != 0 {
					continue
				}
				if len(looper) > 0 || q.k > len(stack) {
					ans[q.idx] = -1
				} else {
					ans[q.idx] = stack[q.k-1]
				}
			}
			for _, u := range edges[v] {
				if visited[u] == i {
					continue
				}
				if visited[u] == -i {
					looper = append(looper, u)
					continue
				}
				dfs(u)
			}
			visited[v] = i
			stack = stack[:len(stack)-1]
			if l := len(looper); l > 0 && looper[l-1] == v {
				looper = looper[:l-1]
			}
		}
		dfs(i)
	}

	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	for _, a := range ans {
		if a == 0 {
			a = -1
		}
		fmt.Fprintln(out, a)
	}
}


Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.

The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array.  The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.

Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).

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

func main() {
	var n,m,q,l,k,i int64
	l,k=0,0
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	a :=make([]int64,100001)
	for i=1;i<=n;i++ {
		input.Scan()
		bb,_:=strconv.ParseInt(input.Text(),0,64)
		a[bb]=i
	}
	input.Scan()
	c,_:=strconv.ParseInt(input.Text(),0,64)
	m=c
	for i=1;i<=m;i++ {
		input.Scan()
		aa,_:=strconv.ParseInt(input.Text(),0,64)
		q=aa
		k+=a[q]
		l+=n-a[q]+1
	}
	fmt.Println(k,l)
}

package main

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

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

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

	n := scanInt(scanner)
	arr := make([]int, n)
	position := make(map[int]int)
	for i := 0; i < n; i++ {
		arr[i] = scanInt(scanner)
		position[arr[i]] = i
	}
	left, right := int64(0), int64(0)
	m := scanInt(scanner)
	for i := 0; i < m; i++ {
		pos := position[scanInt(scanner)]
		left += int64(pos+1)
		right += int64(n-pos)
	}
	writer.WriteString(fmt.Sprintf("%d %d\n", left, right))
}

package main

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

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

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

    var n,m,a int
    ScanInts(&n)
    pos := make([]int,n+1)
    for i := 0; i < n; i++ {
        ScanInts(&a)
        pos[a] = i
    }
    ScanInts(&m)
    v, p := int64(0), int64(0)
    for i := 0; i < m; i++ {
        ScanInts(&a)
        v += int64(pos[a]+1)
        p += int64(n-pos[a])
    }
    fmt.Println(v,p)
}

package main

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

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

func main() {
	defer writer.Flush()
		n := reader.NextInt64()
		aa:=make([]int64,n)
		for i:=range aa {
			aa[i]=reader.NextInt64()
		}
		m:=reader.NextInt64()
		bb:=make([]int64,m)
		for i:=range bb {
			bb[i]=reader.NextInt64()
		}
		hm:=make(map[int64]int64,n)
		for i,v:=range aa {
			hm[v]=int64(i)
		}
		left,right:=int64(0),int64(0)
		for _,v:=range bb {
			left+=hm[v]+1
			right+=n-hm[v]
		}
		writer.Printf("%d %d \n",left,right)
}

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

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

type writerImpl struct {
	*bufio.Writer
}

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

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

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

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

type wordScannerImpl struct {
	*bufio.Scanner
}

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

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

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

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

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

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

func main() {
	var n,m,q,l,k,i int64
	l,k=0,0
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	a :=make([]int64,100001)
	for i=1;i<=n;i++ {
		input.Scan()
		bb,_:=strconv.ParseInt(input.Text(),0,64)
		a[bb]=i
	}
	fmt.Scan(&m)
	for i=1;i<=m;i++ {
		input.Scan()
		aa,_:=strconv.ParseInt(input.Text(),0,64)
		q=aa
		k+=a[q]
		l+=n-a[q]+1
	}
	fmt.Println(k,l)
}

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

func main() {
	var n,m,q,l,k,i int64
	var p int
	l,k=0,0
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	a :=make([]int64,100001)
	for i=1;i<=n;i++ {
		input.Scan()
		bb,_:=strconv.Atoi(input.Text())
		//fmt.Scan(&p)
		p=bb
		a[p]=i
	}
	fmt.Scan(&m)
	for i=1;i<=m;i++ {
		input.Scan()
		aa,_:=strconv.ParseInt(input.Text(),0,64)
		q=aa
		k+=a[q]
		l+=n-a[q]+1
	}
	fmt.Println(k,l)
}

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

func main() {
	var n,m,p,q,l,k,i int64
	l,k=0,0
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	a :=make([]int64,100001)
	for i=1;i<=n;i++ {
		input.Scan()
		bb,_:=strconv.ParseInt(input.Text(),0,64)
		//fmt.Scan(&p)
		p=bb
		a[p]=i
	}
	fmt.Scan(&m)
	for i=1;i<=m;i++ {
		input.Scan()
		aa,_:=strconv.ParseInt(input.Text(),0,64)
		q=aa
		k+=a[q]
		l+=n-a[q]+1
	}
	fmt.Println(k,l)
}

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

func main() {
	var n,m,q,l,k,i int64
	l,k=0,0
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	a :=make([]int64,100001)
	for i=1;i<=n;i++ {
		input.Scan()
		bb,_:=strconv.Atoi(input.Text())
		a[bb]=i
	}
	fmt.Scan(&m)
	for i=1;i<=m;i++ {
		input.Scan()
		aa,_:=strconv.ParseInt(input.Text(),0,64)
		q=aa
		k+=a[q]
		l+=n-a[q]+1
	}
	fmt.Println(k,l)
}

package main

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

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

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

	n := scanInt(scanner)
	arr := make([]int, n)
	position := make(map[int]int)
	for i := 0; i < n; i++ {
		arr[i] = scanInt(scanner)
		position[arr[i]] = i
	}
	left, right := 0, 0
	m := scanInt(scanner)
	for i := 0; i < m; i++ {
		pos := position[scanInt(scanner)]
		left += pos+1
		right += n-pos
	}
	writer.WriteString(fmt.Sprintf("%d %d\n", left, right))
}

package main

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

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

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

    var n,m int
    var a int64
    fmt.Scan(&n)
    pos := make([]int,n+1)
    for i := 0; i < n; i++ {
        ScanInts(&a)
        pos[a] = i
    }
    fmt.Scan(&m)
    v, p := int64(0), int64(0)
    for i := 0; i < m; i++ {
        ScanInts(&a)
        v += int64(pos[a]+1)
        p += int64(n-pos[a])
    }
    fmt.Println(v,p)
}

package main

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

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

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

    var n,m,a int
    fmt.Scan(&n)
    pos := make([]int,n+1)
    for i := 0; i < n; i++ {
        ScanInts(&a)
        pos[a] = i
    }
    fmt.Scan(&m)
    v, p := int64(0), int64(0)
    for i := 0; i < m; i++ {
        ScanInts(&a)
        v += int64(pos[a]+1)
        p += int64(n-pos[a])
    }
    fmt.Println(v,p)
}

package main

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

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

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

    var n,m,a int
    fmt.Scan(&n)
    pos := make([]int,n+1)
    for i := 0; i < n; i++ {
        ScanInts(&a)
        pos[a] = i
    }
    fmt.Scan(&m)
    v, p := int64(0), int64(0)
    for i := 0; i < m; i++ {
        ScanInts(&a)
        v += int64(pos[a]+1)
        p += int64(n-pos[a])
    }
    fmt.Println(v,p)
}