A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.

The first input file line contains integers n and m — the total number of clothing items in the shop and the total number of matching pairs of clothing items ().
Next line contains n integers ai (1≤ai≤10^6) — the prices of the clothing items in rubles.
Next m lines each contain a pair of space-separated integers ui and vi (1≤ui,vi≤n,ui≠vi). Each such pair of numbers means that the ui-th and the vi-th clothing items match each other. It is guaranteed that in each pair ui and vi are distinct and all the unordered pairs (ui,vi) are different.

Print the only number — the least possible sum in rubles that Gerald will have to pay in the shop. If the shop has no three clothing items that would match each other, print "-1" (without the quotes).

In the first test there only are three pieces of clothing and they all match each other. Thus, there is only one way — to buy the 3 pieces of clothing; in this case he spends 6 roubles.
The second test only has three pieces of clothing as well, yet Gerald can't buy them because the first piece of clothing does not match the third one. Thus, there are no three matching pieces of clothing. The answer is -1.
In the third example there are 4 pieces of clothing, but Gerald can't buy any 3 of them simultaneously. The answer is -1.

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n, m := readTwoNums(reader)
	price := readNNums(reader, n)
	E := make([][]int, m)
	for i := 0; i < m; i++ {
		E[i] = readNNums(reader, 2)
	}
	res := solve(price, E)
	fmt.Println(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 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 readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

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 solve(price []int, E [][]int) int {
	n := len(price)

	A := make([][]bool, n)
	for i := 0; i < n; i++ {
		A[i] = make([]bool, n)
	}

	for _, e := range E {
		u, v := e[0], e[1]
		u--
		v--
		A[u][v] = true
		A[v][u] = true
	}

	res := -1

	for u := 0; u < n; u++ {
		for v := u + 1; v < n; v++ {
			if A[u][v] {
				for w := 0; w < n; w++ {
					if A[u][w] && A[w][v] {
						if res < 0 || price[u]+price[v]+price[w] < res {
							res = price[u] + price[v] + price[w]
						}
					}
				}
			}
		}
	}

	return res
}


Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare. Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.

The first line contain integer t (1≤t≤20), where t is the number of races. After that all races are described one by one. Every race description start with an integer n (1≤n≤50) on a line of itself, where n is the number of clasified drivers in the given race. After that n lines follow with the classification for the race, each containing the name of a driver. The names of drivers are given in order from the first to the last place. The name of the driver consists of lowercase and uppercase English letters and has length at most 50 characters. Comparing of names should be case-sensetive.

Your output should contain exactly two line. On the first line is the name of the champion according to the original rule, and on the second line the name of the champion according to the alternative rule.

It is not guaranteed that the same drivers participate in all races. For the championship consider every driver that has participated in at least one race. The total number of drivers during the whole season is not more then 50.

3
3
Hamilton
Vettel
Webber
2
Webber
Vettel
2
Hamilton
Vettel

2
7
Prost
Surtees
Nakajima
Schumacher
Button
DeLaRosa
Buemi
8
Alonso
Prost
NinoFarina
JimClark
DeLaRosa
Nakajima
Patrese
Surtees

package main

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

var scanner *bufio.Scanner

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

type Driver struct {
  Name string
  Points int
  Places map[int]int
  MaxPlace int
}

var drivers = map[string]*Driver{}

type OldList []*Driver
type NewList []*Driver
func (list OldList) Len() int {
  return len(list)
}
func (list OldList) Swap(i, j int) {
  list[i], list[j] = list[j], list[i]
}
func (list NewList) Len() int {
  return len(list)
}
func (list NewList) Swap(i, j int) {
  list[i], list[j] = list[j], list[i]
}

func (list OldList) Less(i, j int) bool {
  a, b := list[i], list[j]
  if a.Points != b.Points {
    return a.Points > b.Points
  }
  return comparePlaces(a, b)
}
func (list NewList) Less(i, j int) bool {
  a, b := list[i], list[j]
  if a.Places[1] != b.Places[1] {
    return a.Places[1] > b.Places[1]
  }
  if a.Points != b.Points {
    return a.Points > b.Points
  }
  return comparePlaces(a, b)
}
func comparePlaces(a, b *Driver) bool {
  for p := 1; p <= a.MaxPlace || p <= b.MaxPlace; p++ {
    placesA := a.Places[p]
    placesB := b.Places[p]
    if placesA != placesB {
      return placesA > placesB
    }
  }
  return true
}

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

  points := map[int]int{ 1: 25, 2: 18, 3: 15, 4: 12, 5: 10,
      6: 8, 7: 6, 8: 4, 9: 2, 10: 1 }

  t := getI()
  for ti := 0; ti < t; ti++ {
    n := getI()
    for ni := 0; ni < n; ni++ {
      name := getS()
      place := ni+1
      driver, found := drivers[name]
      if !found {
        driver = &Driver{ name, 0, map[int]int{}, 0 }
        drivers[name] = driver
      }
      driver.Points += points[place]
      driver.Places[place] += 1
      if place > driver.MaxPlace {
        driver.MaxPlace = place
      }
    }
  }
  oldList, newList := []*Driver{}, []*Driver{}
  for _, driver := range drivers {
    oldList = append(oldList, driver)
    newList = append(newList, driver)
  }
  sort.Sort(OldList(oldList))
  sort.Sort(NewList(newList))
  writer.WriteString(fmt.Sprintf("%s\n", oldList[0].Name))
  writer.WriteString(fmt.Sprintf("%s\n", newList[0].Name))
}


Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?

The first input line contains integer n (1≤n≤10^5) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.

Output the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.

package main

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

/*
1
3
---
0
======
2
2 2
---
1
======
2
-4 -4
---
1
======
6
1 2 3 1 2 3
---
1
======
5
1 -2 3 0 -1
---
0
*/

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	bld := strings.Builder{}

	t := 1
	//scanf("%d\n", &t)

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

		ps := make([]int, n)

		for i := 0; i < n; i++ {
			var num int
			scanf("%d", &num)

			if i == 0 {
				ps[i] = num
			} else {
				ps[i] = ps[i-1] + num
			}
		}

		cnt := 0

		for i := 0; i < n-1; i++ {
			leftSum := ps[i]
			rightSum := ps[n-1] - ps[i]
			if leftSum == rightSum {
				cnt++
			}
		}

		fmt.Fprintln(&bld, cnt)
	}

	printf("%s", bld.String())
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

//goland:noinspection GoUnusedType
type pair struct {
	fst int
	snd int
}

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

//goland:noinspection GoUnusedFunction
func printf(f string, a ...interface{}) {
	if _, err := fmt.Fprintf(writer, f, a...); err != nil {
		panic(err)
	}
}

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

//goland:noinspection GoUnusedFunction
func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

//goland:noinspection GoUnusedFunction
func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

//goland:noinspection GoUnusedFunction
func isPrime(n int) bool {
	if n == 2 || n == 3 {
		return true
	}

	if n <= 1 || n%2 == 0 || n%3 == 0 {
		return false
	}

	for i := 5; i*i <= n; i += 6 {
		if n%i == 0 || n%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 2
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	lenNum := int(math.Log10(float64(num))) + 1
	if pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number lenght %d", pos, lenNum)
		panic(err)
	}

	rem := num % int(math.Pow(10, float64(pos+1)))
	return rem / int(math.Pow(10, float64(pos)))
}


Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.

The first line contains three integers n, m, x (1≤n,m≤30,1≤x≤50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1≤q≤5·10^5). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.

If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).

In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.

3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG

package main

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

var scanner *bufio.Scanner

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

type Key struct {
  R, C int
  Ch rune
}

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

  var n, m, x int
  line, _ := reader.ReadString('\n')
  fmt.Sscanf(line, "%d %d %d", &n, &m, &x)
  keys := []Key{}
  for r := 0; r < n; r++ {
    line, _ := reader.ReadString('\n')
    s := strings.TrimSpace(line)
    for c, ch := range s {
      keys = append(keys, Key{ r, c, ch })
    }
  }
  cost := map[rune]int{}
  for i := 0; i < len(keys); i++ {
    a := keys[i]
    if a.Ch != 'S' {
      cost[a.Ch] = 1
      continue
    }
    for j := 0; j < len(keys); j++ {
      b := keys[j]
      if b.Ch != 'S' {
        ch := b.Ch - 'a' + 'A'
        if cost[ch] == 1 {
          continue
        }
        cost[ch] = 2
        d2 := (a.R - b.R)*(a.R - b.R) + (a.C - b.C)*(a.C - b.C)
        if d2 <= x*x {
          cost[ch] = 1
        }
      }
    }
  }
  reader.ReadString('\n')
  line, _ = reader.ReadString('\n')
  s := strings.TrimSpace(line)
  result := 0
  for _, ch := range s {
    c, found := cost[ch]
    if !found {
      writer.WriteString("-1\n")
      return
    }
    result += c-1
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

[{'input': ['2 2 1\r\nab\r\ncd\r\n1\r\nA\r\n'], 'output': ['-1\r\n']}, {'input': ['2 2 1\r\nab\r\ncd\r\n1\r\ne\r\n'], 'output': ['-1\r\n']}, {'input': ['2 2 1\r\nab\r\ncS\r\n5\r\nabcBA\r\n'], 'output': ['1\r\n']}, {'input': ['3 9 4\r\nqwertyuio\r\nasdfghjkl\r\nSzxcvbnmS\r\n35\r\nTheQuIcKbRoWnFOXjummsovertHeLazYDOG\r\n'], 'output': ['2\r\n']}, {'input': ['10 9 3\r\noboxlgpey\r\nyxcuwkkmp\r\njuqeflhwq\r\nsfnxqtjqS\r\nkkudcnyjl\r\nhgjlcrkjq\r\njnofqksxn\r\nqbhsnuguv\r\nlvahnifao\r\nebwnnlrwe\r\n35\r\nCodeforcesBetaRoundproblemAtestfive\r\n'], 'output': ['4\r\n']}, {'input': ['2 7 4\r\niuqtieo\r\nysxcgmS\r\n2\r\nsQ\r\n'], 'output': ['1\r\n']}, {'input': ['1 2 4\r\nbS\r\n8\r\nbBbbbBbb\r\n'], 'output': ['0\r\n']}, {'input': ['7 8 5\r\nfqiubjpm\r\nqbshcsyk\r\ncjbxpbef\r\nptwpmapx\r\nryazscbm\r\nqnvsgzrf\r\nhtardzkz\r\n9\r\nuxrmwkayy\r\n'], 'output': ['0\r\n']}, {'input': ['8 6 4\r\nefvmov\r\nkeofnw\r\npwajpe\r\nknptky\r\nSibruu\r\nrgdukk\r\nbsxosd\r\nhovgSe\r\n10\r\nECreruXmsC\r\n'], 'output': ['-1\r\n']}, {'input': ['10 3 2\r\nukk\r\neqt\r\nfex\r\nqSh\r\ntvz\r\nfjn\r\niol\r\nehd\r\nnte\r\ngyx\r\n5\r\ncgQxI\r\n'], 'output': ['-1\r\n']}, {'input': ['10 10 19\r\nowqjcaSpqn\r\nvgrhboqahn\r\nbzziocjmbu\r\npurqsmiSop\r\nxcsifctjhy\r\nycyytwoamk\r\nrnjfxsxowl\r\nnkgcywcdff\r\nbazljrisqv\r\nkcakigSekq\r\n100\r\nzewpATtssQVicNrlRrcoifTutTAfFMUEfDFKoNyQbSrSYxTGMadNkRpmJvoEqUsqPYgAdQreaUrwDKMNFWiwdRRCcJBPorfMVMoK\r\n'], 'output': ['0\r\n']}, {'input': ['10 10 26\r\nwxmssptheb\r\nzpxbxsyxsy\r\nqbjkpaywqp\r\nfwhnuzjcgq\r\nycgaanzedz\r\njrycrbzqfs\r\ngswwakybus\r\nfhtxhljedz\r\noSepmyjosv\r\ndwviycevdn\r\n100\r\nyapwUfnyPzgZyFvAHGKWVbXQHkuhJDoUTvCAtdMMCQmKchxKkilUTECOqYJFUSHPqKiRKhDXZgHxwApDWlShdwakmVCgaeKCLOMX\r\n'], 'output': ['0\r\n']}, {'input': ['10 10 3\r\nrvouufmnqu\r\nbyukrnmnhr\r\nzjggwxgvkz\r\ntcagkSitiw\r\nhryajgtpwc\r\njragfhqoks\r\nkgroxxkuvp\r\nbpgrkqiyns\r\njbuhjjkziw\r\nomjmbaggsw\r\n100\r\nCpRzrPqPngYvrVJFCWRPMRwrpXcbtiwfoFcAkRaNjzpMMKOQAzBxSrxGbIHaYgmSqhhxhZTmhFttKnhFzRfKxYXshUZRvtKJIzZq\r\n'], 'output': ['12\r\n']}, {'input': ['10 10 2\r\nfriuxvShvg\r\nerslojqtgu\r\nzeqsmdewry\r\nwvhbeeyeSu\r\ngkofbjaavr\r\ntwkcdxugps\r\nnzlylSmafu\r\nstamkpxnzt\r\nuwxwximkrm\r\nmzxyboazbl\r\n100\r\nmRIfAtrLKmztpVkAmojDCiIgseBwlUilBIixDQhqNhNAqVLLIobuCIretLdSvixNNdCiouFMXtwHZFlObCeaygmIiFBfaCirbmCa\r\n'], 'output': ['19\r\n']}, {'input': ['10 10 2\r\nbddahSqkmk\r\npxbocxayjs\r\nottvdazstk\r\nlaxuidqlqb\r\nkfjwdpdfat\r\nxlipuubkgv\r\niqyomzfktm\r\niwbgidmwyu\r\nrngqkeupsf\r\nbqndtekryw\r\n100\r\nMNQgWFLhHycqwjSsbTkbgMYAIHFYARRmOsinYMFjOxxnLjiKfeiBbMpoeTdzUMORPaAxRNfvdAPFaKkPdxdAjjJgGCxkDzmSasqq\r\n'], 'output': ['37\r\n']}, {'input': ['10 10 2\r\nnxcwdrsmrv\r\nSyjahsosvp\r\nvkrqbxhgbv\r\nwkxywavtnn\r\nepkyoviqbi\r\nsfmpvhuwwq\r\nnlsostrotx\r\ntcdguorhny\r\nimixrqzSdu\r\nxzhdhdwibt\r\n100\r\nUzzaWiRFYbAqxIDMrRBBDoGQhSzSqSLEddAiJsZcxbemdeuddamNYdWOvzlYSCuHIRpnuxdNxAsnZMiLXBYwnrMcrbNeLrUYhZOB\r\n'], 'output': ['17\r\n']}, {'input': ['10 10 23\r\nhtyvouoiqi\r\nvySvsfqadv\r\nxvqyqjyutq\r\npjcrrphzbk\r\nhlqfyoqfmo\r\nezcSwleoew\r\nxkwqrajxyg\r\nngSiftgoso\r\njyndgicccr\r\nlgjvokydhp\r\n100\r\nJzVVfotldIRcyjhTNRcFlTxFeZKRwavZxYcvdDOQyUvTmryFRuRBcRvmscegtspkPuchqlFEKbrfpTOSlSFOARsbbvSenMwNmaRj\r\n'], 'output': ['0\r\n']}, {'input': ['10 10 7\r\nifcwalsdbj\r\njpykymrbei\r\nrylzgkyefh\r\noilvvexpjp\r\niptgodpfim\r\ndSrqejaixu\r\npksxlsniwa\r\nmoSenxtfbc\r\noqssptcenz\r\nqdhmouvyas\r\n100\r\nqtMDVUXJpSEFgPsLKyRJVRbfVoYaCKJDnQDLFVngVjSPzzVyMnMyuyahMRiBJuNhKtgpVqvukUolLvYEmidvXotgQUJukYwIweUW\r\n'], 'output': ['0\r\n']}, {'input': ['10 10 1\r\nmdxafehbkr\r\nyuhenybjps\r\ntvfwmiwcoh\r\njmzrepzjvx\r\nnqyorkSnuk\r\ntSmztmwidv\r\ncmmajnlqrw\r\nfiqewpdwax\r\nuesmkdcplt\r\nlgkomdcqbo\r\n100\r\nmcEQmAvFqKYMXLHQUDeIulkmAMRkIUtbKihTFJwJYQfcAelNrZWSAwHunwZTrdHaRWokgCyLqbubOpEHuZiDVoFHjvkMSoBPyGOI\r\n'], 'output': ['39\r\n']}, {'input': ['10 10 2\r\nnhfafdwqhh\r\neyvitpcthk\r\nrpiotuoqzh\r\nnxxnhuaxee\r\nyevrtirzwf\r\nkbtSsamyel\r\nfeenjvxsmo\r\nkqpenxjmde\r\nlqsamthlwp\r\njdyyqsbtbk\r\n100\r\nUHucxPWDaKonVpXEctuqYUAQnrFEZaTYxhoacNbHIMevlbDejXjitEzyVrTfcfBHWRMdJvaTkbkqccyHjtzpTbKmRAXwlXCtFKNX\r\n'], 'output': ['29\r\n']}, {'input': ['10 10 1\r\nsufnxxpdnx\r\nvttibpllhv\r\nlvbrjmfdjx\r\ngmtexvrnfh\r\nygsqrsSwxd\r\nkxbbjxgbzs\r\nedutwocmzd\r\nfebjgknyai\r\nvcvquagvrs\r\ndrdoarhgoc\r\n100\r\nZoZJXhUWyaLgBTpgbznABKHuyFcKzJmGaMhoKkKfyOGacLwBspaKtAEdwMZJFYiZUFNDxdDIDgKSCRvsbGUOXRqalbpuEqkduYpW\r\n'], 'output': ['44\r\n']}, {'input': ['10 10 2\r\ncstcrltzsl\r\nblotmquzvj\r\nuiitiytlgx\r\nwumpfdaprd\r\ntfxohqpztn\r\nvfrpsccddo\r\nneegusrkxw\r\niijfjozqjq\r\nioegbvuhew\r\npjjpqdxvqu\r\n100\r\nkPCBONfZLkeXzWVuSgvinPENazcnRoBcUHXwRzPyvNIiDlDSeKOYmiUmjooXuzTCtIRxKDAYeTLgjsenxHoymVazMALUADQpjVjV\r\n'], 'output': ['-1\r\n']}, {'input': ['10 10 1\r\nqztnjglyrc\r\nnukswgzajl\r\nqnpbdwjvbb\r\nliiakzcrlz\r\nnolwfzzvxd\r\nmqvhiySttx\r\nqwuizSjuto\r\nqbgwiwjukx\r\nkomyvblgkc\r\ntkzlxzgsru\r\n100\r\nYUzTZDzLFkMUhjQWbwljJCRyZGFzgJcozvROiwPktRGxkMKiPyiTvhDrtusPYhMgVAOFIjAvlpzcrUvrMrMbhkpUiyAytKfYOGTF\r\n'], 'output': ['37\r\n']}, {'input': ['10 10 1\r\nmgziiihbkq\r\niobjknuogh\r\nvntwahSopu\r\nsjsxjpaqvm\r\nwqgrodizst\r\nselzugktoi\r\nvbhfzvgjfn\r\nliqlfdcjhf\r\nbpbtpmimxb\r\npksfiydpfw\r\n100\r\nwAVZXEhKTuajdCauVTIwgnfbxWuUSmtXkjHZtNVcfTsiSAPLdpdEFdTJLZRjptUcRhAmrNjKMXmuDGatAQoaIpbddnzRGHsJrhoq\r\n'], 'output': ['39\r\n']}, {'input': ['10 10 2\r\nshbqxycvfm\r\notydudkttw\r\nqhatsxsngz\r\nixvyujtyjc\r\nsbvqhnjbak\r\neggcguuuka\r\nxcydfgjzeb\r\nytpdkcdrsq\r\nefqlpywggu\r\nfcnfrhnouo\r\n100\r\nHPqtuVckdUOhsnuhnbpekWvWKUnAEaOCihpeEvmaOKOPcIZiMixGJGEuXAaOxuUNyrIesmldLEqGnvyDKPDvFkCbRebCORHmUgeV\r\n'], 'output': ['-1\r\n']}, {'input': ['1 1 50\r\nS\r\n29\r\nargjhoaiogjiSjqfhjksdvjkSvcvn\r\n'], 'output': ['-1\r\n']}, {'input': ['1 1 50\r\nS\r\n1\r\nS\r\n'], 'output': ['-1\r\n']}, {'input': ['1 1 50\r\na\r\n29\r\nargjhoaiogjiSjqfhjksdvjkSvcvn\r\n'], 'output': ['-1\r\n']}, {'input': ['1 1 50\r\nz\r\n29\r\nargjhoaiogjiSjqfhjksdvjkSvcvn\r\n'], 'output': ['-1\r\n']}, {'input': ['2 1 2\r\nS\r\nc\r\n4\r\nCSSA\r\n'], 'output': ['-1\r\n']}]


Рассмотрим следующий код сортировки слиянием на языке Python: def sort(a):  n = len(a)  b = [0 for i in range(n)]  log = []  def mergeSort(l, r):    if r - l <;= 1:      return    m = (l + r) >> 1    mergeSort(l, m)    mergeSort(m, r)    i, j, k = l, m, l    while i <; m and j <; r:      if a[i] <; a[j]:        log.append('0')        b[k] = a[i]        i += 1      else:        log.append('1')        b[k] = a[j]        j += 1      k += 1    while i <; m:      b[k] = a[i]      i += 1      k += 1    while j <; r:      b[k] = a[j]      j += 1      k += 1    for p in range(l, r):      a[p] = b[p]  mergeSort(0, n)  return "".join(log)Как можно заметить, этот код использует логирование — важнейший инструмент разработки.Старший разработчик ВКонтакте Вася сгенерировал перестановку $$$a$$$ (массив из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$), дал её на вход функции sort и получил на выходе строку $$$s$$$. На следующий день строку $$$s$$$ Вася нашёл, а перестановка $$$a$$$ потерялась. Вася хочет восстановить любую перестановку $$$a$$$ такую, что вызов функции sort от неё даст ту же строку $$$s$$$. Помогите ему!

Ввод содержит непустую строку $$$s$$$, состоящую из символов 0 и 1.  В этой версии задачи для любого теста существует перестановка длины $$$16$$$, удовлетворяющая условию. Тем не менее, ваш ответ может иметь любую длину, в том числе отличную от $$$16$$$.

В первой строке выведите целое число $$$n$$$ — длину перестановки. Во второй строке выведите $$$n$$$ различных целых чисел $$$a_0, a_1, \ldots, a_{n-1}$$$ ($$$1 \le a_i \le n$$$) — элементы перестановки. Если существует несколько вариантов ответа, выведите любой из них.

package main

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

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

func NewIO(in io.Reader, out io.Writer) *IO {
	return &IO{in: bufio.NewReader(in), out: bufio.NewWriter(out)}
}

func (io *IO) ReadInt64() int64 {
	var res int64
	fmt.Fscanf(io.in, "%d\n", &res)
	return res
}

func (io *IO) ReadInt() int {
	var res int
	fmt.Fscanf(io.in, "%d\n", &res)
	return res
}

func (io *IO) ReadPairInt64() (int64, int64) {
	var a, b int64
	fmt.Fscanf(io.in, "%d %d\n", &a, &b)
	return a, b
}

func (io *IO) ReadPairInt() (int, int) {
	var a, b int
	fmt.Fscanf(io.in, "%d %d\n", &a, &b)
	return a, b
}

func (io *IO) ReadString() string {
	var res string
	fmt.Fscanf(io.in, "%s\n", &res)
	return res
}

func (io *IO) ReadIntSlice(n int) []int64 {
	var t int64
	res := make([]int64, 0, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(io.in, "%d", &t)
		res = append(res, t)
	}
	fmt.Fscanf(io.in, "\n")
	return res
}

type log struct {
	s string
	i int
}

var errOutOfRange = errors.New("out of range")

func (l *log) left() (bool, error) {
	if l.i >= len(l.s) {
		return false, errOutOfRange
	}
	c := l.s[l.i]
	l.i++
	return c == '0', nil
}

func mergeSort(a []int, l *log) error {
	if len(a) == 1 {
		return nil
	}

	err := mergeSort(a[:len(a)/2], l)
	if err != nil {
		return err
	}

	err = mergeSort(a[len(a)/2:], l)
	if err != nil {
		return err
	}

	b := make([]int, 0, len(a))
	i, j := 0, len(a)/2

	for i < len(a)/2 && j < len(a) {
		left, err := l.left()
		if err != nil {
			return err
		}

		if left {
			b = append(b, a[i])
			i++
		} else {
			b = append(b, a[j])
			j++
		}
	}

	for i < len(a)/2 {
		b = append(b, a[i])
		i++
	}

	for j < len(a) {
		b = append(b, a[j])
		j++
	}

	for i := range b {
		a[i] = b[i]
	}
	return nil
}

func doSomething(n int, s string) int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = i
	}

	l := log{s, 0}
	err := mergeSort(a, &l)
	if err != nil {
		return 1000000000
	}

	return len(l.s) - l.i
}

func doSomethingWithPrint(n int, s string) int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = i
	}

	l := log{s, 0}
	err := mergeSort(a, &l)
	if err != nil {
		return 1000000000
	}

	if _, err = l.left(); err != nil {
		b := make([]int, len(a))

		for i, v := range a {
			b[v] = i + 1
		}

		fmt.Println(len(a))
		for _, v := range b {
			fmt.Printf("%d ", v)
		}
	}

	return len(l.s) - l.i
}

func main() {
	io := NewIO(os.Stdin, os.Stdout)
	s := io.ReadString()

	l, r := 1, 200000

	for r - l > 1 {
		x1 := l + (r - l) / 3
		x2 := l + (r - l) / 3 * 2

		v1 := doSomething(x1, s)
		v2 := doSomething(x2, s)

		if v1 < v2 {
			l = x1
		} else {
			r = x2
		}
	}

	doSomethingWithPrint(l, s)
}


There are two sisters Alice and Betty. You have $$$n$$$ candies. You want to distribute these $$$n$$$ candies between two sisters in such a way that:  Alice will get $$$a$$$ ($$$a > 0$$$) candies;  Betty will get $$$b$$$ ($$$b > 0$$$) candies;  each sister will get some integer number of candies;  Alice will get a greater amount of candies than Betty (i.e. $$$a > b$$$);  all the candies will be given to one of two sisters (i.e. $$$a+b=n$$$). Your task is to calculate the number of ways to distribute exactly $$$n$$$ candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent $$$n$$$ as the sum of $$$n=a+b$$$, where $$$a$$$ and $$$b$$$ are positive integers and $$$a>b$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^9$$$) — the number of candies you have.

For each test case, print the answer — the number of ways to distribute exactly $$$n$$$ candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print $$$0$$$.

NoteFor the test case of the example, the $$$3$$$ possible ways to distribute candies are:  $$$a=6$$$, $$$b=1$$$;  $$$a=5$$$, $$$b=2$$$;  $$$a=4$$$, $$$b=3$$$.

package main

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

func main() {
	var t, n int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(in, &n)
		fmt.Println((n - 1) / 2)
	}
}


Ania has a large integer $$$S$$$. Its decimal representation has length $$$n$$$ and doesn't contain any leading zeroes. Ania is allowed to change at most $$$k$$$ digits of $$$S$$$. She wants to do it in such a way that $$$S$$$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$0 \leq k \leq n$$$) — the number of digits in the decimal representation of $$$S$$$ and the maximum allowed number of changed digits. The second line contains the integer $$$S$$$. It's guaranteed that $$$S$$$ has exactly $$$n$$$ digits and doesn't contain any leading zeroes.

Output the minimal possible value of $$$S$$$ which Ania can end with. Note that the resulting integer should also have $$$n$$$ digits.

NoteA number has leading zeroes if it consists of at least two digits and its first digit is $$$0$$$. For example, numbers $$$00$$$, $$$00069$$$ and $$$0101$$$ have leading zeroes, while $$$0$$$, $$$3000$$$ and $$$1010$$$ don't have leading zeroes.

package main

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

const MaxBuf = 200100
var buf []byte
var sc = bufio.NewScanner(os.Stdin)

func init() {
   sc.Split(bufio.ScanWords)
   sc.Buffer(buf,MaxBuf)
}

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

func readInt64() int64 {
   sc.Scan()
   r,_ := strconv.ParseInt(sc.Text(),10,64)
   return r
}

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

func main() {
	n := readInt()
	k := readInt()
	s := readString()

	r := make([]rune,n)
	for i,v := range s {
		var x rune
		if k > 0 {
			if i == 0 {
				if len(s) == 1 {
					x = '0'
				} else {
					x = '1'
				}
				if v != x {
					k--
				}
			} else {
				x = '0'
				if v != x {
					k--
				}
			}
		} else {
			x = v
		}
		r[i] = x
	}

	fmt.Println(string(r))

}


Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:  on this day the gym is closed and the contest is not carried out;  on this day the gym is closed and the contest is carried out;  on this day the gym is open and the contest is not carried out;  on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 3) separated by space, where:    ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;  ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;  ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;  ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.

Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:   to do sport on any two consecutive days,  to write the contest on any two consecutive days.

NoteIn the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer

const maxn = 100

var n int
var a [maxn + 1]int
var f [maxn + 1][3]int

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

func main() {
	bufin = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
	defer bufout.Flush()

	fmt.Fscan(bufin, &n)
	for i := 1; i <= n; i++ {
		fmt.Fscan(bufin, &a[i])
	}

	for j := 0; j < 3; j++ {
		f[0][j] = 0
	}

	for i := 1; i <= n; i++ {
		f[i][0] = n
		for j := 0; j < 3; j++ {
			f[i][0] = min(f[i][0], f[i-1][j]+1)
		}

		f[i][1] = n
		if (a[i] & 1) == 1 {
			f[i][1] = min(f[i][1], f[i-1][0])
			f[i][1] = min(f[i][1], f[i-1][2])
		}

		f[i][2] = n
		if ((a[i] >> 1) & 1) == 1 {
			f[i][2] = min(f[i][2], f[i-1][0])
			f[i][2] = min(f[i][2], f[i-1][1])
		}
	}

	r := min(min(f[n][0], f[n][1]), f[n][2])
	fmt.Fprint(bufout, r)
}


The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix. The input limitations for getting 30 points are:    1 ≤ n ≤ 5  The input limitations for getting 100 points are:   1 ≤ n ≤ 101

NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.

// A2. Good Matrix Elements
/*
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:

    Elements of the main diagonal.
    Elements of the secondary diagonal.
    Elements of the "middle" row — the row which has exactly rows above it and the same number of rows below it.
    Elements of the "middle" column — the column that has exactly columns to the left of it and the same number of columns to the right of it.

The figure shows a 5 × 5 matrix. The good elements are marked with green.

Help the Smart Beaver count the sum of good elements of the given matrix.

Input

The first line of input data contains a single odd integer n. Each of the next n lines contains n integers a ij (0 ≤ a ij ≤ 100) separated by single spaces — the elements of the given matrix.

The input limitations for getting 30 points are:

    1 ≤ n ≤ 5

The input limitations for getting 100 points are:

    1 ≤ n ≤ 101

Output
Print a single integer — the sum of good matrix elements.

Examples
Input
3
1 2 3
4 5 6
7 8 9

Output
45

Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Output
17

Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
*/
package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	input1, _ := reader.ReadString('\n')
	n, _ := strconv.Atoi(strings.TrimSpace(input1))

	total := 0
	for i := 0; i < n; i++ {
		input2, _ := reader.ReadString('\n')
		for j := 0; j < n; j++ {
			arr := strings.Split(strings.TrimSpace(input2), " ")
			x, _ := strconv.Atoi(arr[j])
			if i == j {
				total += x
			} else if i+j == n-1 {
				total += x
			} else if j == (n-1)/2 {
				total += x
			} else if i == (n-1)/2 {
				total += x
			}
		}
	}
	fmt.Print(total)
}


Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s). Second line of input contains integer k (1 ≤ k ≤ 26).

Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.

NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.

package main

import (
	"fmt"
)

func main() {
	var word string
	var k int

	fmt.Scan(&word,&k)

	if len(word) < k {
		fmt.Println("impossible")
		return
	}

	chs := make(map[rune]int,0)

	for _,ch := range word {
		chs[ch]++
	}

	out := k - len(chs)
	if out < 0 {
		out = 0
	}
    fmt.Println(out)
}

[{'input': 'yandex\r\n6\r\n', 'output': ['0\r\n']}, {'input': 'yahoo\r\n5\r\n', 'output': ['1\r\n']}, {'input': 'google\r\n7\r\n', 'output': ['impossible\r\n']}, {'input': 'a\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'z\r\n2\r\n', 'output': ['impossible\r\n']}, {'input': 'fwgfrwgkuwghfiruhewgirueguhergiqrbvgrgf\r\n26\r\n', 'output': ['14\r\n']}, {'input': 'nfevghreuoghrueighoqghbnebvnejbvnbgneluqe\r\n26\r\n', 'output': ['12\r\n']}, {'input': 'a\r\n3\r\n', 'output': ['impossible\r\n']}, {'input': 'smaxpqplaqqbxuqxalqmbmmgubbpspxhawbxsuqhhegpmmpebqmqpbbeplwaepxmsahuepuhuhwxeqmmlgqubuaxehwuwasgxpqmugbmuawuhwqlswllssueglbxepbmwgs\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'cuguccgcugcugucgggggcgcgucgucugcuuuccccuugccg\r\n4\r\n', 'output': ['1\r\n']}, {'input': 'fcfccfcfccfcfcffcffffffcfccfccfcffccccfcffffccfccfcffcfcccccffcfffcccffcfccfffffcccfccffffffccfccccf\r\n20\r\n', 'output': ['18\r\n']}, {'input': 'swmkwaruyv\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'tnbqpsuhkczmejirvyfdolxwga\r\n22\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abb\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'aaaa\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'yandex\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'aaabbbccc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'asdfgh\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'aab\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'mynameissako\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abcdef\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'abcdefg\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'abc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'asdafjsgljdllgjdgkl\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'yaay\r\n3\r\n', 'output': ['1\r\n']}, {'input': 'yaay\r\n4\r\n', 'output': ['2\r\n']}, {'input': 'zzzzzz\r\n2\r\n', 'output': ['1\r\n']}]


Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 106. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.

package main
import (
	"fmt"
)
func main(){
	var n, register int
	var action string
	var peopleMap map[int] bool
	peopleMap = make(map[int]bool)
	var tmpList []int
	var peopleList []int
	res := 0
	fmt.Scanf("%d\n", &n)
	for i := 0; i < n; i++{
		fmt.Scanf("%s%d\n", &action, &register)
		if action == "+"{
			peopleMap[register] = true
			tmpList = append(tmpList, register)
		}else{
			tmpList = append(tmpList, register * -1)
			_, ok := peopleMap[register]
			if ok{
				delete(peopleMap, register)
			}else{
				peopleList = append(peopleList, register)
			}
		}
	}
	peopleMap = make(map[int]bool)
	peopleList = append(peopleList, tmpList...)
	for i := 0; i < len(peopleList); i++{
		if peopleList[i] > 0{
			peopleMap[peopleList[i]] = true
		}else{
			now := peopleList[i] * -1
			delete(peopleMap, now)
		}
		res = Max(res, len(peopleMap))
	}
	fmt.Println(res)
}

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


There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hallWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.

The first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.

If there is no way to assigns seats to parliamentarians in a proper way print -1. Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.

NoteIn the first sample there are many other possible solutions. For example, 3 20 1and 2 13 0The following assignment 3 21 0is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats.

package main

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

func main() {
	get := wrapStdin()
	n, a, b := get.Int(), get.Int(), get.Int()

	if a*b < n {
		fmt.Println(-1)
		return
	}

	g := func(b int) func() int {
		return func() int {
			t := b
			b += 2
			if t > n {
				t = 0
			}
			return t
		}
	}
	ev, od := g(2), g(1)

	for i := 0; i < a; i++ {
		for j := 0; j < b; j++ {
			var x int
			if (i^j)&1 == 0 {
				x = od()
			} else {
				x = ev()
			}
			fmt.Printf("%d ", x)
		}
		fmt.Printf("\n")
	}
}

type Input struct {
	*bufio.Scanner
}

func wrapStdin() Input {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	return Input{Scanner: sc}
}
func (in Input) Int() int {
	in.Scan()
	x, _ := strconv.Atoi(in.Text())
	return x
}
func (in Input) IntOk() (int, bool) {
	ok := in.Scan()
	x, _ := strconv.Atoi(in.Text())
	return x, ok
}


Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.

package main

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

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

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

	n := nextInt()
	_ = n

	s := next()

	i, count := 0, 0

	for i<len(s) && s[i]=='.' {
		i++
	}

	if i==len(s) {
		println(len(s))
		return
	}

	lastPush := i
	i++

	if s[lastPush]=='R' {
		count += lastPush
	}

	for i<len(s) {
		if s[i] != '.' {
			if s[i] == 'R' {
				count += i - lastPush - 1
			} else {
				if (i-lastPush)%2 == 0 {
					count++
				}
			}
			lastPush = i
		}
		i++
	}

	if s[lastPush]=='L' {
		count += len(s) - lastPush - 1
	}

	println(count)
}

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

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	return n
}

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

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


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

package main

import "fmt"
//import "sort"

func main(){
	var n int
	fmt.Scan(&n)
	var aa int
	a := make([]int, 5000)
	for i:=0; i<n; i++ {
		fmt.Scan(&aa)
		a[aa-1] = aa
	}
	tot := 0
//	sort.Ints(a)
	for j:=0; j<n; j++ {
		if a[j] == 0 {
			tot +=1
		} else {
			tot = tot
		}
	}
	fmt.Println(tot)
}


One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, 1 ≤ k ≤ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7).

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.

Print the single number — the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7).

NoteIn the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB".

package main
import "fmt"

func main(){
	var n,m,i,u,count,ans int64
	fmt.Scan(&n,&m)
	s:=make([]string,n)
	for i=0; i<n; i++{ fmt.Scan(&s[i]) }
	ans = 1
	for i=0; i<m; i++{
		var dif [26]int
		count=0
		for u=0; u<n ; u++{
			x:= s[u][i]-'A'
			if dif[x] == 0{ dif[x]++}
		}
		for j:=0; j<26; j++{
			count+= int64(dif[j])
		}
		ans= (ans*count)%1000000007
	}
	fmt.Println(ans)
}

[{'input': '2 3\r\nAAB\r\nBAA\r\n', 'output': ['4\r\n']}, {'input': '4 5\r\nABABA\r\nBCGDG\r\nAAAAA\r\nYABSA\r\n', 'output': ['216\r\n']}, {'input': '1 1\r\nE\r\n', 'output': ['1\r\n']}, {'input': '2 2\r\nNS\r\nPD\r\n', 'output': ['4\r\n']}, {'input': '3 4\r\nPJKD\r\nNFJX\r\nFGFK\r\n', 'output': ['81\r\n']}, {'input': '4 5\r\nSXFMY\r\nATHLM\r\nKDDQW\r\nZWGDS\r\n', 'output': ['1024\r\n']}, {'input': '20 14\r\nJNFKBBBJYZHWQE\r\nLBOKZCPFNKDBJY\r\nXKNWGHQHIOXUPF\r\nDDNRUKVUGHWMXW\r\nMTIZFNAAFEAPHX\r\nIXBQOOHEULZYHU\r\nMRCSREUEOOMUUN\r\nHJTSQWKUFYZDQU\r\nGMCMUZCOPRVEIQ\r\nXBKKGGJECOBLTH\r\nXXHTLXCNJZJUAF\r\nVLJRKXXXWMTPKZ\r\nPTYMNPTBBCWKAD\r\nQYJGOBUBHMEDYE\r\nGTKUUVVNKAHTUI\r\nZNKXYZPCYLBZFP\r\nQCBLJTRMBDWNNE\r\nTDOKJOBKEOVNLZ\r\nFKZUITYAFJOQIM\r\nUWQNSGLXEEIRWF\r\n', 'output': ['515139391\r\n']}, {'input': '5 14\r\nAQRXUQQNSKZPGC\r\nDTTKSPFGGVCLPT\r\nVLZQWWESCHDTAZ\r\nCOKOWDWDRUOMHP\r\nXDTRBIZTTCIDGS\r\n', 'output': ['124999979\r\n']}, {'input': '9 23\r\nOILBYKHRGMPENVFNHLSIUOW\r\nLPJFHTUQUINAALRDGLSQUXR\r\nLYYJJEBNZATAFQWTDZSPUNZ\r\nHSJPIQKKWWERJZIEMLCZUKI\r\nOJYIEYDGPFWRHCMISJCCUEM\r\nLMGKZVFYIVDRTIHBWPCNUTG\r\nUBGGNCITVHAIPKXCLTSAULQ\r\nOWSAWUOXQDBSXXBHTLSXUVD\r\nUGQTIZQPBGMASRQPVPSFUWK\r\n', 'output': ['454717784\r\n']}, {'input': '25 4\r\nLVKG\r\nMICU\r\nZHKW\r\nLFGG\r\nOWQO\r\nLCQG\r\nLVXU\r\nOUKB\r\nLNQX\r\nZJTO\r\nOOQX\r\nLVQP\r\nMFQB\r\nMRQV\r\nOIQH\r\nOPXX\r\nXFKU\r\nFCQB\r\nZPKH\r\nLVCH\r\nNFCU\r\nOVQW\r\nOZKU\r\nLFHX\r\nLPXO\r\n', 'output': ['5733\r\n']}, {'input': '30 10\r\nUTNTGOKZYJ\r\nQHOUHNYZVW\r\nLTVGHJRZVW\r\nMZHYHOLZYJ\r\nERYEUEPZYE\r\nUZDBFTURYJ\r\nRVSMQTIZGW\r\nWDJQHMIRYY\r\nKCORHQPZYE\r\nRRPLFOZZVY\r\nJTXMFNNNYJ\r\nMVTGGOZZVV\r\nEHAFFNUZVF\r\nLBRNWJZNYE\r\nJVMOHTPZYJ\r\nWTARFJLZVV\r\nLVJCWOURVW\r\nLCLQFJYRVV\r\nQVBVGNJRYF\r\nNTZGHOLRYE\r\nMGQKHOUPYJ\r\nRRSSBXPZYJ\r\nRYCRGTLZYJ\r\nJRDEGNKRVW\r\nRZKFGHYRVG\r\nMDJBFNIZYG\r\nMPLWHXIZYE\r\nSRZMHMURVE\r\nMTEBBMRZYJ\r\nJPJIFOLZYM\r\n', 'output': ['919913906\r\n']}, {'input': '40 7\r\nPNTVVER\r\nPAHTQDR\r\nRXMJVAS\r\nVIQNLYC\r\nILPUSVX\r\nYJOXQDJ\r\nSEFODTO\r\nOTJMREL\r\nLIQRZGD\r\nLBJJPOR\r\nRUTYHQO\r\nRIWEPBD\r\nKQUMFIB\r\nISTRRYH\r\nXBTOTGK\r\nRFQODEY\r\nHDSTZTP\r\nYCXFAGL\r\nAREGRFU\r\nLELZUYU\r\nGVABDKH\r\nFJAMMME\r\nACVULXE\r\nJHVPJAS\r\nAAQNMBX\r\nJJGUCXG\r\nOQATILQ\r\nNEOSHJM\r\nHFLWOFM\r\nICYEQHY\r\nFACGLYP\r\nPLLXJEQ\r\nDCHXYPB\r\nAGDDZJJ\r\nLSQRXTN\r\nHDQZXIY\r\nNAHDDWW\r\nQCMXRQN\r\nFDUDSZO\r\nHKBEVTW\r\n', 'output': ['206575993\r\n']}, {'input': '2 2\r\nAA\r\nBB\r\n', 'output': ['4\r\n']}, {'input': '1 10\r\nAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '2 8\r\nAAAAAAAA\r\nBBBBBBBB\r\n', 'output': ['256\r\n']}, {'input': '10 10\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\nCCCCCCCCCC\r\nDDDDDDDDDD\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\nCCCCCCCCCC\r\nDDDDDDDDDD\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\n', 'output': ['1048576\r\n']}, {'input': '1 20\r\nAAAAAAAAAAAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '20 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\n', 'output': ['7\r\n']}, {'input': '5 60\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\nBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\r\nCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC\r\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD\r\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\r\n', 'output': ['449874206\r\n']}, {'input': '50 4\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\n', 'output': ['10000\r\n']}, {'input': '1 100\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '100 1\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\n', 'output': ['1\r\n']}, {'input': '100 1\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\n', 'output': ['2\r\n']}, {'input': '100 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\n', 'output': ['14\r\n']}, {'input': '100 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\n', 'output': ['26\r\n']}]


An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.

The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.

Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.

package main

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

var scanner *bufio.Scanner

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()
  mark := make([][]bool, n)
  rows := make([]string, n)
  for r := range rows {
    rows[r] = getS()
    mark[r] = make([]bool, m)
  }
  for r := range rows {
    seen := map[byte]int{}
    for c := 0; c < m; c++ {
      ch := rows[r][c]
      if seen[ch] != 0 {
        mark[r][seen[ch]-1] = true
        mark[r][c] = true
      } else {
        seen[ch] = c+1
      }
    }
  }
  for c := 0; c < m; c++ {
    seen := map[byte]int{}
    for r := range rows {
      ch := rows[r][c]
      if seen[ch] != 0 {
        mark[seen[ch]-1][c] = true
        mark[r][c] = true
      } else {
        seen[ch] = r+1
      }
    }
  }
  chars := []byte{}
  for r := range rows {
    for c := 0; c < m; c++ {
      if !mark[r][c] {
        chars = append(chars, rows[r][c])
      }
    }
  }
  writer.WriteString(fmt.Sprintf("%s\n", string(chars)))
}

[{'input': '3 3\r\ncba\r\nbcd\r\ncbc\r\n', 'output': ['abcd']}, {'input': '5 5\r\nfcofd\r\nooedo\r\nafaoa\r\nrdcdf\r\neofsf\r\n', 'output': ['codeforces']}, {'input': '4 4\r\nusah\r\nusha\r\nhasu\r\nsuha\r\n', 'output': ['ahhasusu']}, {'input': '7 5\r\naabcd\r\neffgh\r\niijkk\r\nlmnoo\r\npqqrs\r\nttuvw\r\nxxyyz\r\n', 'output': ['bcdeghjlmnprsuvwz']}, {'input': '10 10\r\naaaaaaaaaa\r\nbccceeeeee\r\ncdfffffffe\r\ncdfiiiiile\r\ncdfjjjjile\r\ndddddddile\r\nedfkkkkile\r\nedddddddde\r\ngggggggggg\r\nhhhhhhhhhe\r\n', 'output': ['b']}, {'input': '15 3\r\njhg\r\njkn\r\njui\r\nfth\r\noij\r\nyuf\r\nyfb\r\nugd\r\nhgd\r\noih\r\nhvc\r\nugg\r\nyvv\r\ntdg\r\nhgf\r\n', 'output': ['hkniftjfbctd']}, {'input': '17 19\r\nbmzbmweyydiadtlcoue\r\ngmdbyfwurpwbpuvhifn\r\nuapwyndmhtqvkgkbhty\r\ntszotwflegsjzzszfwt\r\nzfpnscguemwrczqxyci\r\nvdqnkypnxnnpmuduhzn\r\noaquudhavrncwfwujpc\r\nmiggjmcmkkbnjfeodxk\r\ngjgwxtrxingiqquhuwq\r\nhdswxxrxuzzfhkplwun\r\nfagppcoildagktgdarv\r\neusjuqfistulgbglwmf\r\ngzrnyxryetwzhlnfewc\r\nzmnoozlqatugmdjwgzc\r\nfabbkoxyjxkatjmpprs\r\nwkdkobdagwdwxsufees\r\nrvncbszcepigpbzuzoo\r\n', 'output': ['lcorviunqvgblgjfsgmrqxyivyxodhvrjpicbneodxjtfkpolvejqmllqadjwotmbgxrvs']}, {'input': '1 1\r\na\r\n', 'output': ['a']}, {'input': '2 2\r\nzx\r\nxz\r\n', 'output': ['zxxz']}, {'input': '1 2\r\nfg\r\n', 'output': ['fg']}, {'input': '2 1\r\nh\r\nj\r\n', 'output': ['hj']}, {'input': '1 3\r\niji\r\n', 'output': ['j']}, {'input': '3 1\r\nk\r\np\r\nk\r\n', 'output': ['p']}, {'input': '2 3\r\nmhw\r\nbfq\r\n', 'output': ['mhwbfq']}, {'input': '3 2\r\nxe\r\ner\r\nwb\r\n', 'output': ['xeerwb']}, {'input': '3 7\r\nnutuvjg\r\ntgqutfn\r\nyfjeiot\r\n', 'output': ['ntvjggqfnyfjeiot']}, {'input': '5 4\r\nuzvs\r\namfz\r\nwypl\r\nxizp\r\nfhmf\r\n', 'output': ['uzvsamfzwyplxizphm']}, {'input': '8 9\r\ntjqrtgrem\r\nrwjcfuoey\r\nywrjgpzca\r\nwabzggojv\r\najqmmcclh\r\nozilebskd\r\nqmgnbmtcq\r\nwakptzkjr\r\n', 'output': ['mrjcfuyyrjpzabzvalhozilebskdgnbtpzr']}, {'input': '9 3\r\njel\r\njws\r\ntab\r\nvyo\r\nkgm\r\npls\r\nabq\r\nbjx\r\nljt\r\n', 'output': ['elwtabvyokgmplabqbxlt']}, {'input': '7 6\r\neklgxi\r\nxmpzgf\r\nxvwcmr\r\nrqssed\r\nouiqpt\r\ndueiok\r\nbbuorv\r\n', 'output': ['eklgximpzgfvwcmrrqedoiqptdeiokuorv']}, {'input': '14 27\r\npzoshpvvjdpmwfoeojapmkxjrnk\r\nitoojpcorxjdxrwyewtmmlhjxhx\r\ndoyopbwusgsmephixzcilxpskxh\r\nygpvepeuxjbnezdrnjfwdhjwjka\r\nrfjlbypoalbtjwrpjxzenmeipfg\r\nkhjhrtktcnajrnbefhpavxxfnlx\r\nvwlwumqpfegjgvoezevqsolaqhh\r\npdrvrtzqsoujqfeitkqgtxwckrl\r\nxtepjflcxcrfomhqimhimnzfxzg\r\nwhkfkfvvjwkmwhfgeovwowshyhw\r\nolchgmhiehumivswgtfyhqfagbp\r\ntdudrkttpkryvaiepsijuejqvmq\r\nmuratfqqdbfpefmhjzercortroh\r\nwxkebkzchupxumfizftgqvuwgau\r\n', 'output': ['zshdanicdyldybwgclygzrhkayatwxznmicbpvlupfsoewcleploqngsyolceswtyqbpyasmuadbpcehqva']}, {'input': '1 100\r\nysijllpanprcrrtvokqmmupuptvawhvnekeybdkzqaduotmkfwybqvytkbjfzyqztmxckizheorvkhtyoohbswcmhknyzlgxordu\r\n', 'output': ['g']}, {'input': '2 100\r\ngplwoaggwuxzutpwnmxhotbexntzmitmcvnvmuxknwvcrnsagvdojdgaccfbheqojgcqievijxapvepwqolmnjqsbejtnkaifstp\r\noictcmphxbrylaarcwpruiastazvmfhlcgticvwhpxyiiqokxcjgwlnfykkqdsfmrfaedzchrfzlwdclqjxvidhomhxqnlmuoowg\r\n', 'output': ['rbe']}, {'input': '3 100\r\nonmhsoxoexfwavmamoecptondioxdjsoxfuqxkjviqnjukwqjwfadnohueaxrkreycicgxpmogijgejxsprwiweyvwembluwwqhj\r\nuofldyjyuhzgmkeurawgsrburovdppzjiyddpzxslhyesvmuwlgdjvzjqqcpubfgxliulyvxxloqyhxspoxvhllbrajlommpghlv\r\nvdohhghjlvihrzmwskxfatoodupmnouwyyfarhihxpdnbwrvrysrpxxptdidpqabwbfnxhiziiiqtozqjtnitgepxjxosspsjldo\r\n', 'output': ['blkck']}, {'input': '100 1\r\na\r\nm\r\nn\r\nh\r\na\r\nx\r\nt\r\na\r\no\r\np\r\nj\r\nz\r\nr\r\nk\r\nq\r\nl\r\nb\r\nr\r\no\r\ni\r\ny\r\ni\r\np\r\ni\r\nt\r\nn\r\nd\r\nc\r\nz\r\np\r\nu\r\nn\r\nw\r\ny\r\ng\r\ns\r\nt\r\nm\r\nz\r\ne\r\nv\r\ng\r\ny\r\nj\r\nd\r\nz\r\ny\r\na\r\nn\r\nx\r\nk\r\nd\r\nq\r\nn\r\nv\r\ng\r\nk\r\ni\r\nk\r\nf\r\na\r\nb\r\nw\r\no\r\nu\r\nw\r\nk\r\nk\r\nb\r\nz\r\nu\r\ni\r\nu\r\nv\r\ng\r\nv\r\nx\r\ng\r\np\r\ni\r\nz\r\ns\r\nv\r\nq\r\ns\r\nb\r\nw\r\ne\r\np\r\nk\r\nt\r\np\r\nd\r\nr\r\ng\r\nd\r\nk\r\nm\r\nf\r\nd\r\n', 'output': ['hlc']}, {'input': '100 2\r\nhd\r\ngx\r\nmz\r\nbq\r\nof\r\nst\r\nzc\r\ndg\r\nth\r\nba\r\new\r\nbw\r\noc\r\now\r\nvh\r\nqp\r\nin\r\neh\r\npj\r\nat\r\nnn\r\nbr\r\nij\r\nco\r\nlv\r\nsa\r\ntb\r\nbl\r\nsr\r\nxa\r\nbz\r\nrp\r\nsz\r\noi\r\nec\r\npw\r\nhf\r\njm\r\nwu\r\nhq\r\nra\r\npv\r\ntc\r\ngv\r\nik\r\nux\r\ntz\r\nbf\r\nty\r\ndk\r\nwo\r\nor\r\nza\r\nkv\r\nqt\r\nfa\r\njy\r\nbk\r\nuv\r\ngk\r\ncz\r\nds\r\nie\r\noq\r\nmf\r\nxn\r\nql\r\nxs\r\nfb\r\niv\r\ncj\r\nkn\r\nns\r\nlg\r\nji\r\nha\r\naj\r\ndg\r\nfj\r\nut\r\nsg\r\nju\r\noc\r\nov\r\nhe\r\nnw\r\nbl\r\nlp\r\nbx\r\nnm\r\nyq\r\ncw\r\nov\r\nxk\r\npg\r\noh\r\npl\r\nuo\r\ngf\r\nul\r\n', 'output': ['dvy']}, {'input': '100 3\r\nruy\r\nmye\r\njgp\r\nscn\r\nktq\r\nalx\r\nmvk\r\nlpm\r\nkry\r\norb\r\nmpu\r\nzcv\r\nlge\r\nkft\r\ndzp\r\ntfb\r\nhqz\r\nuur\r\nhry\r\nzjx\r\ncuo\r\nqqc\r\ntih\r\nenj\r\nvnp\r\nbwi\r\nzzh\r\nhkc\r\nwdr\r\nldh\r\nvel\r\nizj\r\nfhb\r\nqrn\r\nqpp\r\nvzs\r\nlhg\r\nkee\r\nlbq\r\nzhy\r\nwcl\r\nyaa\r\nton\r\nfly\r\nkyw\r\nept\r\ngwq\r\ncoe\r\nopd\r\neez\r\nnmx\r\nnjg\r\nwhy\r\nvel\r\nafq\r\nnbq\r\nulx\r\noxs\r\nbbo\r\nyhx\r\nfmz\r\nnrg\r\nnfm\r\njek\r\nbeu\r\ntya\r\nxgs\r\nsgg\r\nnkq\r\nbbv\r\nwkd\r\ntns\r\nfdt\r\neox\r\nobc\r\neab\r\nkkj\r\noub\r\ngji\r\nrht\r\nozv\r\nysk\r\nsbt\r\nflf\r\npbu\r\nlxb\r\npzs\r\nrzh\r\ncea\r\nkmi\r\nuea\r\nncc\r\nzng\r\nvkn\r\njhn\r\njqw\r\nlqc\r\nmbt\r\nlov\r\ngam\r\n', 'output': ['tvdiixs']}]


...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.It is guaranteed that the graph contains no multiple edges and self-loops.

The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ ). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.

Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.

NoteLet us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).A rooted tree is a tree where one vertex is selected to be the root.

package main

import (
	"fmt"
)

type Graph struct {
	n int
	adj [][]int
}
func build(g *Graph, n int) {
	g.n = n
	g.adj = make([][]int, n)
}
func add(g *Graph, v, u int) {
	g.adj[v] = append(g.adj[v], u)
	g.adj[u] = append(g.adj[u], v)
}

var n, m int
var g Graph
var used []bool

func dfs(v int) {
	used[v] = true
	for _, u := range g.adj[v] {
		if used[u] {
			continue
		}
		dfs(u)
	}
}

func main() {
	fmt.Scanf("%d %d\n", &n, &m)
	build(&g, n)
	for i := 0; i < m; i++ {
		var v, u int
		fmt.Scanf("%d %d\n", &v, &u)
		v--
		u--
		add(&g, v, u)
	}
	used = make([]bool, n)
	dfs(0)
	ok := true
	for v := 0; v < n; v++ {
		if !used[v] {
			ok = false
			break
		}
	}
	ans := (n == m) && ok
	if ans {
		fmt.Println("FHTAGN!")
	} else {
		fmt.Println("NO")
	}
}


Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: a12 + a22 + ... + an2 ≥ x a1 + a2 + ... + an ≤ y

The first line contains three space-separated integers n, x and y (1 ≤ n ≤ 105, 1 ≤ x ≤ 1012, 1 ≤ y ≤ 106). Please do not use the %lld specificator to read or write 64-bit integers in С++. It is recommended to use cin, cout streams or the %I64d specificator.

Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.

package main

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

func scanInt64(scanner *bufio.Scanner) int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}

func main() {
  scanner := bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()
  n, x, y := scanInt64(scanner), scanInt64(scanner), scanInt64(scanner)
  a := y - n + 1
  s := a*a + n - 1
  if a >= 1 && s >= x {
    writer.WriteString(fmt.Sprintf("%d\n", a))
    for i := int64(1); i < n; i++ {
      writer.WriteString("1\n")
    }
  } else {
    writer.WriteString("-1\n")
  }
}


Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.  Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.

The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew. 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.

Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).

NoteThe first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.

// 185A
package main

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

func main() {
	var n, x, y, m int64
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in, &n)
	y, x, m = 1, 2, 1000000007
	for n != 0 {
		if n%2 != 0 {
			y = (y * x) % m
		}
		x = (x * x) % m
		n = n / 2
	}
	fmt.Fprint(out, ((y*y+y)/2)%m)
	out.Flush()
}


In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.

The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles. The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103).

Print a single number — the sought number of days.

NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.

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)
  rain := map[int][]int{}
  for pos := 0; pos < n; pos++ {
    day := scanInt(scanner)
    tiles, found := rain[day]
    if !found {
      rain[day] = []int{ pos }
    } else {
      rain[day] = append(tiles, pos)
    }
    tiles = rain[day]
  }
  wreck := make([]bool, n)
  day, done := 0, false
  for !done {
    day++
    tiles, found := rain[day]
    if !found {
      continue
    }
    for _, pos := range tiles {
      if pos == 0 || pos == n-1 || wreck[pos-1] || wreck[pos+1] {
        done = true
        break
      }
      wreck[pos] = true
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", day))
}


Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

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

)

func main() {
	var n,i,f,j,e int64
	e=0
	a:=make([]int64,55)
	x:=make([]int64,10)
	y:=make([]int64,10)
	input := bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	for i=1;i<=n;i++ {
		input.Scan()
		aa,_ := strconv.ParseInt(input.Text(),0,64)
		a[i]=aa
	}
	for i=1;i<=5;i++ {
		input.Scan()
		bb,_ := strconv.ParseInt(input.Text(),0,64)
		x[i]=bb
	}
	for i=1;i<=n;i++ {
		e+=a[i]
		for j=5;j>=1;j-- {
			y[j]+=e/x[j]
			e%=x[j]
		}
	}
	for f=1; f<=5;f++ {
		fmt.Print(y[f]," ")
	}
	fmt.Println()
	fmt.Println(e)
}


Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

package main
import (
	"fmt"
)
func main() {
	var n,m,b int
	ma,c:=0,1
	fmt.Scan(&n)
	a:=make([]int,n)
	for i:=0;i<n;i++ {
		fmt.Scan(&a[i])
	}
	fmt.Scan(&m)
	for i:=0;i<m;i++ {
		fmt.Scan(&b)
		for j:=0;j<n;j++ {
			if b%a[j]==0 {
				x:=b/a[j]
				if x>ma {
					ma=x
					c=1
				} else if x==ma {
					c++
				}
				break
			}
		}
	}

	fmt.Println(c)
}


Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

package main

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

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

type Point struct {
	x, y int
	visited bool
}

func flood(points []Point, pos int) {
	points[pos].visited = true
	x, y := points[pos].x, points[pos].y
	for i := 0; i < len(points); i++ {
		if !points[i].visited && (points[i].x == x || points[i].y == y) {
			flood(points, i)
		}
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	n := scanInt(scanner)
	points := make([]Point, n)
	for i := 0; i < n; i++ {
		points[i] = Point{x: scanInt(scanner), y: scanInt(scanner)}
	}
	count := -1
	for i := 0; i < n; i++ {
		if points[i].visited {
			continue
		}
		count++
		flood(points, i)
	}
	writer.WriteString(fmt.Sprintf("%d\n", count))
}


Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.  The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output one of the four words without inverted commas:    «forward» — if Peter could see such sequences only on the way from A to B;  «backward» — if Peter could see such sequences on the way from B to A;  «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;  «fantasy» — if Peter could not see such sequences.

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func reverse(s string) string {
	b := []byte(s)
	for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
		b[i], b[j] = b[j], b[i]
	}
	return string(b)
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var s, s0, s1 string
	var forward, backward bool

	fmt.Fscanf(reader, "%s\n", &s)
	fmt.Fscanf(reader, "%s\n", &s0)
	fmt.Fscanf(reader, "%s", &s1)

	findex0 := strings.Index(s, s0)
	findex1 := strings.LastIndex(s, s1)
	if findex0 == -1 || findex1 == -1 || findex1-findex0 < len(s0) {
		forward = false
	} else {
		forward = true
	}

	s = reverse(s)
	bindex0 := strings.Index(s, s0)
	bindex1 := strings.LastIndex(s, s1)
	if bindex0 == -1 || bindex1 == -1 || bindex1-bindex0 < len(s0) {
		backward = false
	} else {
		backward = true
	}

	if forward && backward {
		fmt.Printf("both\n")
	} else if forward && !backward {
		fmt.Printf("forward\n")
	} else if !forward && backward {
		fmt.Printf("backward\n")
	} else {
		fmt.Printf("fantasy")
	}
}

[{'input': 'atob\r\na\r\nb\r\n', 'output': ['forward\r\n']}, {'input': 'aaacaaa\r\naca\r\naa\r\n', 'output': ['both\r\n']}, {'input': 'aaa\r\naa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'astalavista\r\nastla\r\nlavista\r\n', 'output': ['fantasy\r\n']}, {'input': 'abacabadabacaba\r\nabacaba\r\nabacaba\r\n', 'output': ['both\r\n']}, {'input': 'a\r\na\r\na\r\n', 'output': ['fantasy\r\n']}, {'input': 'ab\r\nb\r\na\r\n', 'output': ['backward\r\n']}, {'input': 'aaa\r\naaaa\r\naaaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'bbabbbbababbaabaabaa\r\nabb\r\nbaab\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'babaabababaaaababaabababaabababababababbababbbabbaabababaababbaabbababaababaaabababaabbaababaaababaa\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'aababaaababaabbaabababaaababaabababbaabbabaabababaabbabbbababbababababababaabababaababaaaabababaabab\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['backward\r\n']}, {'input': 'aaaa\r\naaa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzzzz\r\nzzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzz\r\n', 'output': ['both\r\n']}, {'input': 'aabaa\r\naab\r\nbaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'aabaab\r\naba\r\nab\r\n', 'output': ['forward\r\n']}, {'input': 'aab\r\nb\r\naa\r\n', 'output': ['backward\r\n']}, {'input': 'abacaba\r\naca\r\nba\r\n', 'output': ['both\r\n']}]


And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following:   during one run the minibus makes n stops, the i-th stop is in point (xi, 0)  coordinates of all the stops are different  the minibus drives at a constant speed, equal to vb  it can be assumed the passengers get on and off the minibus at a bus stop momentarily  Student can get off the minibus only at a bus stop  Student will have to get off the minibus at a terminal stop, if he does not get off earlier  the University, where the exam will be held, is in point (xu, yu)  Student can run from a bus stop to the University at a constant speed vs as long as needed  a distance between two points can be calculated according to the following formula:   Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.

The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.

In the only line output the answer to the problem — index of the optimum bus stop.

NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"math"
	"os"
)

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var n int
	var vb, vs, xu, yu float64

	fmt.Fscanf(reader, "%d %f %f\n", &n, &vb, &vs)
	stop := make([]float64, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%f", &stop[i])
		if i != n-1 {
			fmt.Fscanf(reader, " ")
		} else {
			fmt.Fscanf(reader, "\n")
		}
	}
	fmt.Fscanf(reader, "%f %f", &xu, &yu)
	min := 99999999999.0
	var minStop int
	for i := 1; i < n; i++ {
		t := stop[i]/vb + math.Sqrt((xu-stop[i])*(xu-stop[i])+yu*yu)/vs
		if t < min {
			minStop = i
			min = t
		} else if t == min {
			if math.Abs(xu-stop[minStop]) > math.Abs(xu-stop[i]) {
				minStop = i
				min = t
			}
		}
	}
	fmt.Printf("%d", minStop+1)
}


A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the Оx-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?

The first line of the input data contains numbers n and t (1 ≤ n, t ≤ 1000). Then there follow n lines, each of them contains two space-separated integer numbers: xi ai, where xi — x-coordinate of the centre of the i-th house, and ai — length of its side ( - 1000 ≤ xi ≤ 1000, 1 ≤ ai ≤ 1000).

Output the amount of possible positions of the new house.

NoteIt is possible for the x-coordinate of the new house to have non-integer value.

package main

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

var scanner *bufio.Scanner

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

type House struct {
  Pos, Size int
}
type Houses []*House
func (houses Houses) Len() int {
  return len(houses)
}
func (houses Houses) Swap(i, j int) {
  houses[i], houses[j] = houses[j], houses[i]
}
func (houses Houses) Less(i, j int) bool {
  return houses[i].Pos < houses[j].Pos
}

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

  n, s := getI(), getI()
  houses := make([]*House, n)
  for i := 0; i < n; i++ {
    houses[i] = &House{ getI(), getI() }
  }
  sort.Sort(Houses(houses))
  result := 2
  for i := 1; i < n; i++ {
    doubleGap := 2*(houses[i].Pos - houses[i-1].Pos)
    doubleGap -= houses[i].Size + houses[i-1].Size
    if doubleGap >= 2*s {
      result++
    }
    if doubleGap > 2*s {
      result++
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}


Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1 × 5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:  As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.

The first line contains a positive integer n (1 ≤ n ≤ 1000). The second line contains n positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000.

Print a single number, the maximal number of watered sections if we create artificial rain above exactly one section.

package main
import (
	"fmt"
)
func max(a,b int) int{
	if a>b {
		return a
	} else {
		return b
	}
}

func main() {
	var n,ans int
	var a [1001]int
	ans=0
	fmt.Scan(&n)
	for i:=0; i<n; i++{
		fmt.Scan(&a[i])
	}
	for i:=0; i<n; i++{
		l,r:=0,0
		for ; (i-l)>0 && a[i-l-1]<=a[i-l];l++ {}
		for ; (i+r)<n-1 && a[i+r]>=a[i+r+1];r++ {}
		ans = max(ans,l+r+1)
	}
	fmt.Println(ans)
}


n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.

The first line contains integer n (2 ≤ n ≤ 100) — amount of soldiers. Then follow the heights of the soldiers in their order in the circle — n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1000). The soldier heights are given in clockwise or counterclockwise direction.

Output two integers — indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.

package main

import (
    "fmt"
    "math"
)

func main() {
    var n int
    fmt.Scan(&n)
    a := make([]int,n)
    min, ansi, ansj := 1000, 0, 0
    for i := 0; i < n; i++ { fmt.Scan(&a[i]) }
    for i := 0; i < n; i++ {
        u := int(math.Abs(float64(a[i])-float64(a[(i+1)%n])))
        if min > u {
            min = u
            ansi = i+1
            ansj = ((i+1)%n)+1
        }
    }
    fmt.Println(ansi,ansj)
}


The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.

The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.

Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.

package main

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

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

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

	var years int = 0
	for i := di[n-1]; i < di[n]; i++ {
		years += di[i-1]
	}

	fmt.Println(years)
}