You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that .

The first line contains integer n (1 ≤ n ≤ 5·105), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]| ≤  109) — the elements of array a.

Print a single integer — the number of ways to split the array into three parts with the same sum.

package main;

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

func solve() int64 {
  var n int;
  in := bufio.NewReader(os.Stdin)
  var a[10e6] int;
  var prefix[10e6] int64;
  var ansi[10e6] int64;
  fmt.Fscan(in, &n);
  for i := 0; i < n; i++ {
    fmt.Fscan(in, &a[i]);
    if (i == 0) {
      prefix[i] = int64(a[i]);
    } else {
      prefix[i] = prefix[i-1] + int64(a[i]);
    }
  }

  if n < 3 || prefix[n - 1] % 3 != 0 {
    return 0;
  }

  ans := prefix[n - 1] / 3;

  // if (ans == 0) {
  //   zeros := int64(0);
  //   for i := 0; i < n; i++ {
  //     if prefix[i] == 0 {
  //       zeros++;
  //     }
  //   }
  //   return (zeros - 2) * (zeros - 1) / 2
  // }

  i := 0;
  for prefix[i] != ans && i < n {
    i++;
  }

  if (i == n) {
    return 0;
  }

  ansi[i] = 1;
  for j := i + 1; j < n; j++ {
    ansi[j] = ansi[j - 1];
    if prefix[j] == ans {
      ansi[j]++;
    }
  }

  j := i + 1;
  ret := int64(0);
  for j < n - 1 {
    if prefix[j] - prefix[i] == ans &&
       prefix[n - 1] - prefix[j] == ans {
      ret += ansi[j - 1];
    }
    j++;
  }
  return ret;
}

func main() {
  fmt.Print(solve());
}

package main;

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

func solve() int64 {
  var n int;
  in := bufio.NewReader(os.Stdin);
  fmt.Fscan(in, &n);
  a := make([]int, n);
  prefix := make([]int64, n);
  ansi := make([]int64, n);
  for i := 0; i < n; i++ {
    fmt.Fscan(in, &a[i]);
    if (i == 0) {
      prefix[i] = int64(a[i]);
    } else {
      prefix[i] = prefix[i-1] + int64(a[i]);
    }
  }

  if n < 3 || prefix[n - 1] % 3 != 0 {
    return 0;
  }

  ans := prefix[n - 1] / 3;

  i := 0;
  for i < n && prefix[i] != ans {
    i++;
  }

  if (i == n) {
    return 0;
  }

  ansi[i] = 1;
  for j := i + 1; j < n; j++ {
    ansi[j] = ansi[j - 1];
    if prefix[j] == ans {
      ansi[j]++;
    }
  }

  j := i + 1;
  ret := int64(0);
  for j < n - 1 {
    if prefix[j] - prefix[i] == ans &&
       prefix[n - 1] - prefix[j] == ans {
      ret += ansi[j - 1];
    }
    j++;
  }
  return ret;
}

func main() {
  fmt.Print(solve());
}

package main

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

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

func IsSpace(b byte) bool {
	switch b {
	case ' ', '\t', '\n', '\r':
		return true
	default:
		return false
	}
}

func IsDigit(b byte) bool {
	return '0' <= b && b <= '9'
}

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

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

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

func LowerBound(a []int64, x int64) int {
	ub, lb := len(a), 0
	for ub - lb > 1 {
		mid := (ub + lb) / 2
		if a[mid] < x {
			lb = mid
		} else {
			ub = mid
		}
	}
	return ub
}

func UpperBound(a []int64, x int64) int {
	ub, lb := len(a), 0
	for ub - lb > 1 {
		mid := (ub + lb) / 2
		if a[mid] > x {
			ub = mid
		} else {
			lb = mid
		}
	}
	return ub
}

type Container []int64

func (a Container) Len() int {
	return len(a)
}

func (a Container) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func init() {
	in = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
}

func main() {
	var n int
	fmt.Fscan(in, &n)
	a := make([]int64, n)
	s := int64(0)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &a[i])
		s += a[i]
	}
	ct := make(map[int64]int64)
	r := int64(0)
	t := int64(0)
	for i := 0; i < n - 1; i++ {
		t += a[i]
		u := s - t
		if s == 3 * u {
			r += ct[u]
		}
		ct[t]++
	}
	fmt.Fprintln(out, r)
	out.Flush()
}

package main

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

var (
	p int
	ibuf []byte
)

func IsSpace(b byte) bool {
	switch b {
	case ' ', '\t', '\n', '\r':
		return true
	default:
		return false
	}
}

func IsDigit(b byte) bool {
	return '0' <= b && b <= '9'
}

func ReadWord() string {
	for ; p < len(ibuf) && IsSpace(ibuf[p]); p++ {
	}
	buf := make([]byte, 0)
	for ; p < len(ibuf) && IsSpace(ibuf[p]); p++ {
		buf = append(buf, ibuf[p])
	}
	return string(buf)
}

func ReadInt() int {
	for ; p < len(ibuf) && !IsDigit(ibuf[p]) && ibuf[p] != '-'; p++ {
	}
	s := 1
	if ibuf[p] == '-' {
		s = -1
		p++
	}

	d := 0
	for ; p < len(ibuf) && IsDigit(ibuf[p]); p++ {
		d = 10 * d + int(ibuf[p] - '0')
	}
	return s * d
}

func ReadInt64() int64 {
	for ; p < len(ibuf) && !IsDigit(ibuf[p]) && ibuf[p] != '-'; p++ {
	}
	s := int64(1)
	if ibuf[p] == '-' {
		s = int64(-1)
		p++
	}
	d := int64(0)
	for ; p < len(ibuf) && IsDigit(ibuf[p]); p++ {
		d = int64(10) * d + int64(ibuf[p] - '0')
	}
	return s * d
}

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

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

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

func LowerBound(a []int64, x int64) int {
	ub, lb := len(a), 0
	for ub - lb > 1 {
		mid := (ub + lb) / 2
		if a[mid] < x {
			lb = mid
		} else {
			ub = mid
		}
	}
	return ub
}

func UpperBound(a []int64, x int64) int {
	ub, lb := len(a), 0
	for ub - lb > 1 {
		mid := (ub + lb) / 2
		if a[mid] > x {
			ub = mid
		} else {
			lb = mid
		}
	}
	return ub
}

type Container []int64

func (a Container) Len() int {
	return len(a)
}

func (a Container) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func init() {
	p = 0
	ibuf, _ = ioutil.ReadAll(os.Stdin)
}

func main() {
	n := ReadInt()
	a := make([]int64, n)
	s := int64(0)
	for i := 0; i < n; i++ {
		a[i] = ReadInt64()
		s += a[i]
	}
	ct := make(map[int64]int64)
	r := int64(0)
	t := int64(0)
	for i := 0; i < n - 1; i++ {
		t += a[i]
		u := s - t
		if s == 3 * u {
			r += ct[u]
		}
		ct[t]++
	}
	fmt.Println(r)
}

package main

import (
	"os"
	"io/ioutil"
	"strconv"
	"fmt"
)

var (
	p int
	ibuf []byte
)

func IsSpace(b byte) bool {
	switch b {
	case ' ', '\t', '\n', '\r':
		return true
	default:
		return false
	}
}

func IsDigit(b byte) bool {
	return '0' <= b && b <= '9'
}

func ReadWord() string {
	for ; p < len(ibuf) && IsSpace(ibuf[p]); p++ {
	}
	buf := make([]byte, 0)
	for ; p < len(ibuf) && !IsSpace(ibuf[p]); p++ {
		buf = append(buf, ibuf[p])
	}
	return string(buf)
}

func ReadInt() int {
	v, _ := strconv.Atoi(ReadWord())
	return v
}

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

func ParseFloat64() float64 {
	v, _ := strconv.ParseFloat(ReadWord(), 64)
	return v
}

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

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

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

func LowerBound(a []int64, x int64) int {
	ub, lb := len(a), 0
	for ub - lb > 1 {
		mid := (ub + lb) / 2
		if a[mid] < x {
			lb = mid
		} else {
			ub = mid
		}
	}
	return ub
}

func UpperBound(a []int64, x int64) int {
	ub, lb := len(a), 0
	for ub - lb > 1 {
		mid := (ub + lb) / 2
		if a[mid] > x {
			ub = mid
		} else {
			lb = mid
		}
	}
	return ub
}

type Container []int64

func (a Container) Len() int {
	return len(a)
}

func (a Container) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func init() {
	p = 0
	ibuf, _ = ioutil.ReadAll(os.Stdin)
}

func main() {
	n := ReadInt()
	a := make([]int64, n)
	s := int64(0)
	for i := 0; i < n; i++ {
		a[i] = ReadInt64()
		s += a[i]
	}
	ct := make(map[int64]int64)
	r := int64(0)
	t := int64(0)
	for i := 0; i < n - 1; i++ {
		t += a[i]
		u := s - t
		if s == 3 * u {
			r += ct[u]
		}
		ct[t]++
	}
	fmt.Println(r)
}

package main

import (
	"bufio"
	"fmt"
	"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()
	a := make([]int64, n)
	a[0] = nextInt64()

	if n < 3 {
		println(0)
		return
	}

	for i := 1; i < n; i++ {
		a[i] = a[i - 1] + nextInt64()
	}

	if a[n - 1] % 3 != 0 {
		println(0)
		return
	}

	div1 := a[n - 1] / 3
	div2 := div1 * 2
	var count, cntDiv1, cntDiv2 int64

	if a[n-2] == div2 {
		cntDiv2++
	}

	for i := n - 3; i >= 0; i-- {
		if a[i] == div1 {
			cntDiv1++
			count += cntDiv2
		}

		if a[i] == div2 {
			cntDiv2++
		}
	}
	// println(a)
	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 nextInt64() int64 {
	return int64(nextInt())
}

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

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

// http://codeforces.com/problemset/problem/466/C
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

const (
	MOD = 1e9 + 7
)

type (

)

func main () {
	var (
		n int
	)

	input := bufio.NewReaderSize(os.Stdin, 1024*1024)
	fmt.Fscanln(input, &n)
	a := make([]int64, n)
	sum := make([]int64, n + 1)
	rights := make([]int64, n + 1)  // count of factors from right

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

	if sum[n] % 3 != 0 {
		fmt.Println(0)
		return
	}

	var ans int64
	factor := sum[n] / 3

	rsum := int64(0)
	for i := n - 1; i >= 0; i-- {
		rsum += a[i]
		rights[i] = rights[i + 1]

		if rsum == factor {
			rights[i]++
		}
	}

	for i := 1; i < n - 1; i++ {
		if (sum[i] == factor) {
			ans += rights[i + 1]
		}
	}

	fmt.Println(ans)
}

package main

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

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

var (
	n   int
	ans int64
	ss  int64
	sum int64
)

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

	read(&n)
	a := make([]int64, n)
	sum = 0

	for i := 0; i < n; i++ {
		readI64(&a[i])
		sum += int64(a[i])
	}

	if sum%3 != 0 {
		writer.WriteByte('0')
		writer.Flush()
		os.Exit(0)
	}
	cnt := make([]int64, n)

	ss = a[n-1]
	if a[n-1] == sum/3 {
		cnt[n-1] = 1
	}

	for i := n - 2; i >= 0; i-- {
		ss += a[i]
		cnt[i] = cnt[i+1]
		if ss == sum/3 {
			cnt[i] += 1
		}
	}

	/*
		for _, value := range cnt {
			writeI64(value)
		}
		writer.WriteByte('\n')
	*/
	ss = 0
	for i := 0; i < n-2; i++ {
		ss += a[i]
		if ss == sum/3 {
			ans += cnt[i+2]
		}
	}

	writeI64(ans)
}

func writeI64(n int64) {
	str := strconv.FormatInt(n, 10) + " "
	writer.WriteString(str)
}

func read(n *int) {
	scanner.Scan()
	*n, _ = strconv.Atoi(scanner.Text())
}

func readI64(n *int64) {
	scanner.Scan()
	*n, _ = strconv.ParseInt(scanner.Text(), 10, 64)
}

package main

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

// Let 'k' be total_sum / 3
// Iterate from last, maintain
// sum_so_far - sum of numbers visited so far,
// 2k - number of indices where prefix_sum was equal to 2k's
// At each i:
// calculate prefix_sum as total_sum - sum_so_far
// if prefix_sum at i == k, add 2k to answer
// if prefix_sum at i == 2k, increment 2k by 1
// add a[i] to sum_so_far
func ways(arr []int64, n int) int64 {
	var total_sum int64
	for i := 0; i < n; i++ {
		total_sum += arr[i]
	}
	if total_sum%3 != 0 {
		return 0
	}
	k := int64(total_sum / 3)
	var number_of_ways, prefix_sum, sum_so_far, twok_count int64
	sum_so_far = arr[n-1]
	for i := n - 2; i >= 0; i-- {
		prefix_sum = total_sum - sum_so_far
		if prefix_sum == k {
			number_of_ways += twok_count
		}
		if prefix_sum == 2*k {
			twok_count += 1
		}
		sum_so_far += arr[i]
	}
	return number_of_ways
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &arr[i])
	}
	fmt.Fprintln(writer, ways(arr, n))
}

package main

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

// Let 'k' be total_sum / 3
// Iterate from last, maintain
// sum_so_far - sum of numbers visited so far,
// 2k - number of indices where prefix_sum was equal to 2k's
// At each i:
// calculate prefix_sum as total_sum - sum_so_far
// if prefix_sum at i == k, add 2k to answer
// if prefix_sum at i == 2k, increment 2k by 1
// add a[i] to sum_so_far
func ways(arr []int64, n int) int64 {
	var total_sum int64
	for _, ai := range arr {
		total_sum += ai
	}
	if total_sum%3 != 0 {
		return 0
	}
	k := int64(total_sum / 3)
	var number_of_ways, prefix_sum, sum_so_far, twok_count int64
	sum_so_far = arr[n-1]
	for i := n - 2; i >= 0; i-- {
		prefix_sum = total_sum - sum_so_far
		if prefix_sum == k {
			number_of_ways += twok_count
		}
		if prefix_sum == 2*k {
			twok_count += 1
		}
		sum_so_far += arr[i]
	}
	return number_of_ways
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &arr[i])
	}
	fmt.Fprintln(writer, ways(arr, n))
}

package main

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

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

	var n int
	Fscan(in, &n)
	if n < 3 {
		Fprintln(out, 0)
		return
	}
	sum := make([]int64, n+1)
	for i := 1; i <= n; i++ {
		var val int64
		Fscan(in, &val)
		sum[i] = sum[i-1] + val
	}
	allSum := sum[n]

	if allSum%3 != 0 {
		Fprintln(out, 0)
		return
	}
	if allSum == 0 {
		cnt0 := int64(0)
		for _, s := range sum[1:n] {
			if s == 0 {
				cnt0++
			}
		}
		Fprintln(out, cnt0*(cnt0-1)/2)
		return
	}
	partSum := allSum / 3
	var ans, cnt1 int64
	for i := 1; i < n; i++ {
		if sum[i] == partSum {
			cnt1++
		} else if sum[i] == 2*partSum {
			ans += cnt1
		}
	}
	Fprintln(out, ans)
}

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

package main

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

//var solve [2][]int
//
//func main() {
//	var a []int
//	var n int
//	reader := bufio.NewReader(os.Stdin)
//	fmt.Fscanln(reader, &n)
//	var sum int
//	a = make([]int, n)
//	for i := 0; i < 2; i++ {
//		solve[i] = make([]int, n)
//	}
//	for i := 0; i < 2; i++ {
//		for j := 0; j < n; j++ {
//			solve[i][j] = -1
//		}
//	}
//	for i := 0; i < n; i++ {
//		fmt.Fscan(reader, &a[i])
//		sum += a[i]
//	}
//	fmt.Fscanln(reader)
//	if sum%3 != 0 {
//		fmt.Println(0)
//		return
//	}
//	average := sum / 3
//	fmt.Println(dfs2(a, 3, average))
//}
//
//func dfs2(a []int, count int, average int) int {
//	if count > len(a) {
//		return 0
//	}
//	if count == 1 {
//		return 1
//	}
//	add := 0
//	resCount := 0
//	for i, v := range a {
//		add += v
//		if add == average && i+1 < len(a) {
//			if solve[count-2][i+1] != -1 {
//				resCount += solve[count-2][i+1]
//			} else {
//				x := dfs2(a[i+1:], count-1, average)
//				solve[count-2][i+1] = x
//				resCount += x
//			}
//			//fmt.Println(resCount, a[i+1:], count-1, average)
//		}
//	}
//	return resCount
//}

func main() {
	var a []int64
	var n int
	var head []bool
	var tail []bool
	var tailCount []int64
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscanln(reader, &n)
	var sum int64
	a = make([]int64, n)
	head = make([]bool, n)
	tail = make([]bool, n)
	tailCount = make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
		sum += a[i]
	}
	fmt.Fscanln(reader)
	if sum%3 != 0 {
		fmt.Println(0)
		return
	}
	average := sum / 3

	var headAdd int64
	for i := 0; i < n; i++ {
		headAdd += a[i]
		if headAdd == average {
			head[i] = true
		}
	}
	var tailAdd int64
	for i := n - 1; i >= 0; i-- {
		tailAdd += a[i]
		if tailAdd == average {
			tail[i] = true
		}
	}
	if tail[n-1] {
		tailCount[n-1] = 1
	}
	for i := n - 2; i >= 0; i-- {
		if tail[i] {
			tailCount[i] = tailCount[i+1] + 1
		} else {
			tailCount[i] = tailCount[i+1]
		}
	}
	//fmt.Println(head)
	//fmt.Println(tailCount)

	var count int64
	for i := 0; i < n-2; i++ {
		if head[i] {
			count += int64(tailCount[i+2])
		}
	}

	fmt.Println(count)
}

package main

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

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

	an := make([]int64, n, n)
	var sum int64 = 0
	bs := bufio.NewScanner(os.Stdin)
	bs.Split(bufio.ScanWords)
	for i := 0; i < n; i++ {
		bs.Scan()
		an[i], _ = strconv.ParseInt(bs.Text(), 10, 64)
		sum += an[i]
	}

	if sum%3 != 0 {
		fmt.Println(0)
		return
	}

	sum /= 3
	count := make([]int64, n, n)
	var s int64 = 0
	for i := n - 1; i >= 0; i-- {
		s += an[i]
		if s == sum {
			count[i] = 1
		}
	}

	for i := n - 2; i >= 0; i-- {
		count[i] += count[i+1]
	}

	s = 0
	var ans int64 = 0
	for i := 0; i < n-2; i++ {
		s += an[i]
		if s == sum {
			ans += count[i+2]
		}
	}

	fmt.Println(ans)
}

package main

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

func main() {
	var n int
	scanf("%d\n", &n)

	var sum int64

	a := make([]int, n)
	for i, s := range strings.Split(readline(), " ") {
		x, err := strconv.Atoi(s)
		if err != nil {
			panic(err)
		}
		a[i] = x
		sum += int64(a[i])
	}

	if n < 3 || sum%3 != 0 {
		printf("0\n")
		return
	}

	sum /= 3

	var ns int
	var cur, ans int64
	for i := 0; i < n-1; i++ {
		cur += int64(a[i])
		if cur == 2*sum {
			ans += int64(ns)
		}
		if cur == sum {
			ns++
		}
	}
	printf("%d\n", ans)
}

func printf(format string, x ...interface{}) {
	fmt.Fprintf(os.Stdout, format, x...)
}

func scanf(format string, x ...interface{}) {
	if _, err := fmt.Fscanf(os.Stdin, format, x...); err != nil {
		panic(err)
	}
}

func readline() string {
	line, err := bufio.NewReader(os.Stdin).ReadString('\n')
	if err != nil {
		panic(err)
	}
	k := len(line)-1
	if k > 0 && line[k-1] == '\r' {
		k--
	}
	return line[:k]
}

package main

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

func main() {
	var n int
	scanf("%d\n", &n)

	var sum int64
	a := make([]int, 0, n)

	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	for r.Scan() {
		x, err := strconv.Atoi(r.Text())
		if err != nil {
			panic(err)
		}
		a = append(a, x)
		sum += int64(x)
	}
	if err := r.Err(); err != nil {
		panic(err)
	}

	if n < 3 || sum%3 != 0 {
		printf("0\n")
		return
	}

	sum /= 3

	var ns int
	var cur, ans int64
	for i := 0; i < n-1; i++ {
		cur += int64(a[i])
		if cur == 2*sum {
			ans += int64(ns)
		}
		if cur == sum {
			ns++
		}
	}
	printf("%d\n", ans)
}

func printf(format string, x ...interface{}) {
	fmt.Fprintf(os.Stdout, format, x...)
}

func scanf(format string, x ...interface{}) {
	if _, err := fmt.Fscanf(os.Stdin, format, x...); err != nil {
		panic(err)
	}
}

package main;

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

func solve() int64 {
  var n int;
  in := bufio.NewReader(os.Stdin)
  var a[10e6] int;
  var prefix[10e6] int64;
  fmt.Fscan(in, &n);
  for i := 0; i < n; i++ {
    fmt.Fscan(in, &a[i]);
    if (i == 0) {
      prefix[i] = int64(a[i]);
    } else {
      prefix[i] = prefix[i-1] + int64(a[i]);
    }
  }

  if n < 3 || prefix[n - 1] % 3 != 0 {
    return 0;
  }

  ans := prefix[n - 1] / 3;

  if (ans == 0) {
    zeros := int64(0);
    for i := 0; i < n; i++ {
      if prefix[i] == 0 {
        zeros++;
      }
    }
    return (zeros - 2) * (zeros - 1) / 2
  }

  i := 0;
  for prefix[i] != ans && i < n {
    i++;
  }

  if (i == n) {
    return 0;
  }
  firstZeros := int64(0);

  j := i + 1;

  for prefix[j] - prefix[i] != ans && j < n {
    if prefix[j] - prefix[i] == 0 {
      firstZeros++;
    }
    j++;
  }
  if (j == n || prefix[n - 1] - prefix[j] != ans) {
    return 0;
  }
  secondZeros := int64(0);
  k := j + 1;
  for k < n - 1 {
    if prefix[k] - prefix[j] == 0 {
      secondZeros++;
    }
    k++;
  }
  return int64((firstZeros + 1) * (secondZeros + 1));
}

func main() {
  fmt.Print(solve());
}

package main;

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

func solve() int64 {
  var n int;
  in := bufio.NewReader(os.Stdin)
  var a[10e6] int;
  var prefix[10e6] int64;
  fmt.Fscan(in, &n);
  for i := 0; i < n; i++ {
    fmt.Fscan(in, &a[i]);
    if (i == 0) {
      prefix[i] = int64(a[i]);
    } else {
      prefix[i] = prefix[i-1] + int64(a[i]);
    }
  }

  if n < 3 || prefix[n - 1] % 3 != 0 {
    return 0;
  }

  ans := prefix[n - 1] / 3;

  if (ans == 0) {
    zeros := int64(0);
    for i := 0; i < n; i++ {
      zeros++;
    }
    return (zeros - 2) * (zeros - 1) / 2
  }

  i := 0;
  for prefix[i] != ans && i < n {
    i++;
  }

  if (i == n) {
    return 0;
  }
  firstZeros := int64(0);

  j := i + 1;

  for prefix[j] - prefix[i] != ans && j < n {
    if prefix[j] - prefix[i] == 0 {
      firstZeros++;
    }
    j++;
  }
  if (j == n || prefix[n - 1] - prefix[j] != ans) {
    return 0;
  }
  secondZeros := int64(0);
  k := j + 1;
  for k < n - 1 {
    if prefix[k] - prefix[j] == 0 {
      secondZeros++;
    }
    k++;
  }
  return int64((firstZeros + 1) * (secondZeros + 1));
}

func main() {
  fmt.Print(solve());
}

package main

import (
	"os"
	"io/ioutil"
	"strconv"
	"fmt"
)

var (
	p int
	ibuf []byte
)

func IsSpace(b byte) bool {
	switch b {
	case ' ', '\t', '\n', '\r':
		return true
	default:
		return false
	}
}

func IsDigit(b byte) bool {
	return '0' <= b && b <= '9'
}

func ReadWord() string {
	for ; p < len(ibuf) && IsSpace(ibuf[p]); p++ {
	}
	buf := make([]byte, 0)
	for ; p < len(ibuf) && IsSpace(ibuf[p]); p++ {
		buf = append(buf, ibuf[p])
	}
	return string(buf)
}

func ReadInt() int {
	v, _ := strconv.Atoi(ReadWord())
	return v
}

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

func ParseFloat64() float64 {
	v, _ := strconv.ParseFloat(ReadWord(), 64)
	return v
}

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

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

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

func LowerBound(a []int64, x int64) int {
	ub, lb := len(a), 0
	for ub - lb > 1 {
		mid := (ub + lb) / 2
		if a[mid] < x {
			lb = mid
		} else {
			ub = mid
		}
	}
	return ub
}

func UpperBound(a []int64, x int64) int {
	ub, lb := len(a), 0
	for ub - lb > 1 {
		mid := (ub + lb) / 2
		if a[mid] > x {
			ub = mid
		} else {
			lb = mid
		}
	}
	return ub
}

type Container []int64

func (a Container) Len() int {
	return len(a)
}

func (a Container) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func init() {
	p = 0
	ibuf, _ = ioutil.ReadAll(os.Stdin)
}

func main() {
	n := ReadInt()
	a := make([]int64, n)
	s := int64(0)
	for i := 0; i < n; i++ {
		a[i] = ReadInt64()
		s += a[i]
	}
	ct := make(map[int64]int64)
	r := int64(0)
	t := int64(0)
	for i := 0; i < n - 1; i++ {
		t += a[i]
		u := s - t
		if s == 3 * u {
			r += ct[u]
		}
		ct[t]++
	}
	fmt.Println(r)
}

package main

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

var (
	p int
	ibuf []byte
)

func IsSpace(b byte) bool {
	switch b {
	case ' ', '\t', '\n', '\r':
		return true
	default:
		return false
	}
}

func IsDigit(b byte) bool {
	return '0' <= b && b <= '9'
}

func ReadWord() string {
	for ; p < len(ibuf) && IsSpace(ibuf[p]); p++ {
	}
	buf := make([]byte, 0)
	for ; p < len(ibuf) && IsSpace(ibuf[p]); p++ {
		buf = append(buf, ibuf[p])
	}
	return string(buf)
}

func ReadInt() int {
	for ; p < len(ibuf) && !IsDigit(ibuf[p]) && ibuf[p] != '-'; p++ {
	}
	s := 1
	if ibuf[p] == '-' {
		s = -1
		p++
	}

	d := 0
	for ; p < len(ibuf) && IsDigit(ibuf[p]); p++ {
		d = 10 * d + int(ibuf[p] - '0')
	}
	return s * d
}

func ReadInt64() int64 {
	for ; p < len(ibuf) && !IsDigit(ibuf[p]) && ibuf[p] != '-'; p++ {
	}
	s := int64(1)
	if ibuf[p] == '-' {
		s = int64(-1)
		p++
	}
	d := int64(0)
	for ; p < len(ibuf) && IsDigit(ibuf[p]); p++ {
		d = int64(10) * d + int64(ibuf[p] - '0')
	}
	return s * d
}

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

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

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

func LowerBound(a []int64, x int64) int {
	ub, lb := len(a), 0
	for ub - lb > 1 {
		mid := (ub + lb) / 2
		if a[mid] < x {
			lb = mid
		} else {
			ub = mid
		}
	}
	return ub
}

func UpperBound(a []int64, x int64) int {
	ub, lb := len(a), 0
	for ub - lb > 1 {
		mid := (ub + lb) / 2
		if a[mid] > x {
			ub = mid
		} else {
			lb = mid
		}
	}
	return ub
}

type Container []int64

func (a Container) Len() int {
	return len(a)
}

func (a Container) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func init() {
	p = 0
	ibuf, _ = ioutil.ReadAll(os.Stdin)
}

func main() {
	n := ReadInt()
	a := make([]int64, n)
	s := int64(0)
	for i := 0; i < n; i++ {
		a[i] = ReadInt64()
		s += a[i]
	}
	ct := make(map[int64]int)
	r := 0
	t := int64(0)
	for i := 0; i < n - 1; i++ {
		t += a[i]
		u := s - t
		if s == 3 * u {
			r += ct[u]
		}
		ct[t]++
	}
	fmt.Println(r)
}

package main

import (
	"bufio"
	"fmt"
	"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()
	a := make([]int64, n)
	a[0] = nextInt64()
	count := 0

	if n < 3 {
		println(0)
		return
	}

	for i := 1; i < n; i++ {
		a[i] = a[i - 1] + nextInt64()
	}

	for i := 0; i < n - 2; i++ {
		if a[i] * 3 == a[n-1] {
			for j := i + 1; j < n - 1; j++ {
				if a[i] * 2 > a[j] {
					break
				} else if a[i] * 2 == a[j] {
					count++
				}
			}
		} else if a[i] * 3 > a[n - 1] {
			break
		}
	}

	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 nextInt64() int64 {
	return int64(nextInt())
}

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

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

// http://codeforces.com/problemset/problem/466/C
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

const (
	MOD = 1e9 + 7
)

type (

)

func main () {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscanln(input, &n)

	a := make([]int64, n)
	s := make([]int64, n + 1)

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

	if s[n] % 3 != 0 {
		fmt.Println(0)
		return
	}

	var first, second int64
	factor := s[n] / 3
	for i := 0; i < n; i++ {
		if (s[i + 1] == factor) && (i + 1 < n - 1) {
			first++
		}

		if (s[i + 1] == 2*factor) && (i + 1 > 1) && (i + 1 < n )  {
			second++
		}
	}

	fmt.Println(first * second)
}

package main

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

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

var (
	n   int
	ans int64
	ss  int64
	sum int64
)

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

	read(&n)
	a := make([]int64, n)
	sum = 0

	for i := 0; i < n; i++ {
		readI64(&a[i])
		sum += int64(a[i])
	}

	if sum%3 != 0 {
		writer.WriteByte('0')
		writer.Flush()
		os.Exit(0)
	}
	cnt := make([]int64, n)

	ss = 0
	if a[n-1] == sum/3 {
		cnt[n-1] = 1
	}

	for i := n - 2; i >= 0; i-- {
		ss += a[i]
		cnt[i] = cnt[i+1]
		if ss == sum/3 {
			cnt[i] += 1
		}
	}

	/*	for _, value := range cnt {
			writeI64(value)
		}
		writer.WriteByte('\n')
	*/
	ss = 0
	for i := 0; i < n-2; i++ {
		ss += a[i]
		if ss == sum/3 {
			ans += cnt[i+2]
		}
	}

	writeI64(ans)
}

func writeI64(n int64) {
	str := strconv.FormatInt(n, 10) + " "
	writer.WriteString(str)
}

func read(n *int) {
	scanner.Scan()
	*n, _ = strconv.Atoi(scanner.Text())
}

func readI64(n *int64) {
	scanner.Scan()
	*n, _ = strconv.ParseInt(scanner.Text(), 10, 64)
}

package main

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

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

	var n int
	Fscan(in, &n)
	if n < 3 {
		Fprintln(out, 0)
		return
	}
	var val int64
	sum := make([]int64, n+1)
	for i := 1; i <= n; i++ {
		Fscan(in, &val)
		sum[i] = sum[i-1] + val
	}

	if sum[n]%3 != 0 {
		Fprintln(out, 0)
		return
	}
	if sum[n] == 0 {
		cnt0 := int64(0)
		for _, s := range sum[1:] {
			if s == 0 {
				cnt0++
			}
		}
		Fprintln(out, (cnt0-1)*(cnt0-2)/2)
		return
	}
	partSum := sum[n] / 3
	var cnt0, cnt1, cnt2 int64
	for _, s := range sum[1:] {
		if s == partSum {
			cnt0++
		} else if s == 2*partSum {
			cnt1++
		} else if s == 3*partSum {
			cnt2++
		}
	}
	Fprintln(out, cnt0*cnt1*cnt2)
}

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

package main

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

//var solve [2][]int
//
//func main() {
//	var a []int
//	var n int
//	reader := bufio.NewReader(os.Stdin)
//	fmt.Fscanln(reader, &n)
//	var sum int
//	a = make([]int, n)
//	for i := 0; i < 2; i++ {
//		solve[i] = make([]int, n)
//	}
//	for i := 0; i < 2; i++ {
//		for j := 0; j < n; j++ {
//			solve[i][j] = -1
//		}
//	}
//	for i := 0; i < n; i++ {
//		fmt.Fscan(reader, &a[i])
//		sum += a[i]
//	}
//	fmt.Fscanln(reader)
//	if sum%3 != 0 {
//		fmt.Println(0)
//		return
//	}
//	average := sum / 3
//	fmt.Println(dfs2(a, 3, average))
//}
//
//func dfs2(a []int, count int, average int) int {
//	if count > len(a) {
//		return 0
//	}
//	if count == 1 {
//		return 1
//	}
//	add := 0
//	resCount := 0
//	for i, v := range a {
//		add += v
//		if add == average && i+1 < len(a) {
//			if solve[count-2][i+1] != -1 {
//				resCount += solve[count-2][i+1]
//			} else {
//				x := dfs2(a[i+1:], count-1, average)
//				solve[count-2][i+1] = x
//				resCount += x
//			}
//			//fmt.Println(resCount, a[i+1:], count-1, average)
//		}
//	}
//	return resCount
//}

func main() {
	var a []int
	var n int
	var head []bool
	var tail []bool
	var tailCount []int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscanln(reader, &n)
	var sum int
	a = make([]int, n)
	head = make([]bool, n)
	tail = make([]bool, n)
	tailCount = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
		sum += a[i]
	}
	fmt.Fscanln(reader)
	if sum%3 != 0 {
		fmt.Println(0)
		return
	}
	average := sum / 3

	headAdd := 0
	for i := 0; i < n; i++ {
		headAdd += a[i]
		if headAdd == average {
			head[i] = true
		}
	}
	tailAdd := 0
	for i := n - 1; i >= 0; i-- {
		tailAdd += a[i]
		if tailAdd == average {
			tail[i] = true
		}
	}
	if tail[n-1] {
		tailCount[n-1] = 1
	}
	for i := n - 2; i >= 0; i-- {
		if tail[i] {
			tailCount[i] = tailCount[i+1] + 1
		} else {
			tailCount[i] = tailCount[i+1]
		}
	}
	//fmt.Println(head)
	//fmt.Println(tailCount)

	var count int64
	for i := 0; i < n-2; i++ {
		if head[i] {
			count += int64(tailCount[i+2])
		}
	}

	fmt.Println(count)
}

package main

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

//var solve [2][]int
//
//func main() {
//	var a []int
//	var n int
//	reader := bufio.NewReader(os.Stdin)
//	fmt.Fscanln(reader, &n)
//	var sum int
//	a = make([]int, n)
//	for i := 0; i < 2; i++ {
//		solve[i] = make([]int, n)
//	}
//	for i := 0; i < 2; i++ {
//		for j := 0; j < n; j++ {
//			solve[i][j] = -1
//		}
//	}
//	for i := 0; i < n; i++ {
//		fmt.Fscan(reader, &a[i])
//		sum += a[i]
//	}
//	fmt.Fscanln(reader)
//	if sum%3 != 0 {
//		fmt.Println(0)
//		return
//	}
//	average := sum / 3
//	fmt.Println(dfs2(a, 3, average))
//}
//
//func dfs2(a []int, count int, average int) int {
//	if count > len(a) {
//		return 0
//	}
//	if count == 1 {
//		return 1
//	}
//	add := 0
//	resCount := 0
//	for i, v := range a {
//		add += v
//		if add == average && i+1 < len(a) {
//			if solve[count-2][i+1] != -1 {
//				resCount += solve[count-2][i+1]
//			} else {
//				x := dfs2(a[i+1:], count-1, average)
//				solve[count-2][i+1] = x
//				resCount += x
//			}
//			//fmt.Println(resCount, a[i+1:], count-1, average)
//		}
//	}
//	return resCount
//}

func main() {
	var a []int
	var n int
	var head []bool
	var tail []bool
	var tailCount []int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscanln(reader, &n)
	var sum int
	a = make([]int, n)
	head = make([]bool, n)
	tail = make([]bool, n)
	tailCount = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
		sum += a[i]
	}
	fmt.Fscanln(reader)
	if sum%3 != 0 {
		fmt.Println(0)
		return
	}
	average := sum / 3

	headAdd := 0
	for i := 0; i < n; i++ {
		headAdd += a[i]
		if headAdd == average {
			head[i] = true
		}
	}
	tailAdd := 0
	for i := n - 1; i >= 0; i-- {
		tailAdd += a[i]
		if tailAdd == average {
			tail[i] = true
		}
	}
	if tail[n-1] {
		tailCount[n-1] = 1
	}
	for i := n - 2; i >= 0; i-- {
		if tail[i] {
			tailCount[i] = tailCount[i+1] + 1
		} else {
			tailCount[i] = tailCount[i+1]
		}
	}
	//fmt.Println(head)
	//fmt.Println(tailCount)

	count := 0
	for i := 0; i < n-2; i++ {
		if head[i] {
			count += tailCount[i+2]
		}
	}

	fmt.Println(count)
}

package main

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

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

	an := make([]int, n, n)
	sum := 0
	bs := bufio.NewScanner(os.Stdin)
	bs.Split(bufio.ScanWords)
	for i := 0; i < n; i++ {
		bs.Scan()
		an[i], _ = strconv.Atoi(bs.Text())
		sum += an[i]
	}

	if sum%3 != 0 {
		fmt.Println(0)
		return
	}

	sum /= 3
	count := make([]int, n, n)
	s := 0
	for i := n - 1; i >= 0; i-- {
		s += an[i]
		if s == sum {
			count[i] = 1
		}
	}

	for i := n - 2; i >= 0; i-- {
		count[i] += count[i+1]
	}

	s = 0
	ans := 0
	for i := 0; i < n-2; i++ {
		s += an[i]
		if s == sum {
			ans += count[i+2]
		}
	}

	fmt.Println(ans)
}

package main

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

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

	an := make([]int, n, n)
	sum := 0
	bs := bufio.NewScanner(os.Stdin)
	bs.Split(bufio.ScanWords)
	for i := 0; i < n; i++ {
		bs.Scan()
		an[i], _ = strconv.Atoi(bs.Text())
		sum += an[i]
	}

	if sum%3 != 0 {
		fmt.Println(0)
		return
	}

	sum /= 3
	count := make([]int, n, n)
	s := 0
	for i := n - 1; i >= 0; i-- {
		s += an[i]
		if s == sum {
			count[i] = 1
		}
	}

	for i := n - 2; i >= 0; i-- {
		count[i] += count[i+1]
	}

	s = 0
	var ans int64 = 0
	for i := 0; i < n-2; i++ {
		s += an[i]
		if s == sum {
			ans += int64(count[i+2])
		}
	}

	fmt.Println(ans)
}

package main;

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

func solve() int64 {
  var n int;
  in := bufio.NewReader(os.Stdin)
  var a[10e6] int;
  var prefix[10e6] int64;
  fmt.Fscan(in, &n);
  for i := 0; i < n; i++ {
    fmt.Fscan(in, &a[i]);
    if (i == 0) {
      prefix[i] = int64(a[i]);
    } else {
      prefix[i] = prefix[i-1] + int64(a[i]);
    }
  }

  if n < 3 || prefix[n - 1] % 3 != 0 {
    return 0;
  }

  ans := prefix[n - 1] / 3;

  i := 0;
  for prefix[i] != ans && i < n {
    i++;
  }

  if (i == n) {
    return 0;
  }
  firstZeros := int64(0);
  j := i + 1;
  for prefix[j] - prefix[i] != ans && j < n {
    if prefix[j] - prefix[i] == 0 {
      firstZeros++;
    }
    j++;
  }
  if (j == n || prefix[n - 1] - prefix[j] != ans) {
    return 0;
  }
  secondZeros := int64(0);
  k := j + 1;
  for k < n - 1 {
    if prefix[k] - prefix[j] == 0 {
      secondZeros++;
    }
    k++;
  }
  return int64((firstZeros + 1) * (secondZeros + 1));
}

func main() {
  fmt.Print(solve());
}


You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci.Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu :  cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}.Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color.

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge.  It is guaranteed that the given graph has no self-loops or multiple edges.

Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color.

package main

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

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	n, m := scanInt(scanner), scanInt(scanner)
	vertices := make([]int, n)
	neighbors := map[int]map[int]bool{}
	for i := range vertices {
		color := scanInt(scanner)
		vertices[i] = color
		_, present := neighbors[color]
		if !present {
			neighbors[color] = map[int]bool{}
		}
	}
	for i := 0; i < m; i++ {
		a, b := vertices[scanInt(scanner)-1], vertices[scanInt(scanner)-1]
		if a != b {
			neighbors[a][b] = true
			neighbors[b][a] = true
		}
		//writer.WriteString(fmt.Sprintf("a = %d, b = %d\n", a, b))
	}
	bestColor, bestCount := -1, -1
	for color, group := range neighbors {
		//writer.WriteString(fmt.Sprintf("color %d: %d neighbors\n", color, len(group)))
		if len(group) > bestCount {
			bestCount = len(group)
			bestColor = color
		} else if len(group) == bestCount && color < bestColor {
			bestColor = color
		}
	}
	writer.WriteString(fmt.Sprintf("%d\n", bestColor))
}

package main

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

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

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

func main() {
	defer writer.Flush()

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

	c := make([]int, n)

	for i := 0; i < n; i++ {
		if i != n-1 {
			scanf("%d ", &c[i])
		} else {
			scanf("%d\n", &c[i])
		}
	}

	neighbours := map[int]map[int]bool{}

	for _, i := range c {
		_, ok := neighbours[i]
		if !ok {
			neighbours[i] = map[int]bool{}
		}
	}

	for m > 0 {
		m--
		var a, b int
		scanf("%d %d\n", &a, &b)

		a = c[a-1]
		b = c[b-1]
		if a != b {
			neighbours[a][b] = true
			neighbours[b][a] = true
		}
	}
	maxColor, maxCount := -1, -1
	for color, set := range neighbours {
		if(len(set) > maxCount) {
			maxColor = color
			maxCount = len(set)
		} else if len(set) == maxCount && color < maxColor {
			maxColor = color
		}
	}
	printf("%d \n", maxColor)
}


You are given an array consisting of all integers from $$$[l, r]$$$ inclusive. For example, if $$$l = 2$$$ and $$$r = 5$$$, the array would be $$$[2, 3, 4, 5]$$$. What's the minimum number of elements you can delete to make the bitwise AND of the array non-zero?A bitwise AND is a binary operation that takes two equal-length binary representations and performs the AND operation on each pair of the corresponding bits.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq 2 \cdot 10^5$$$) — the description of the array.

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

NoteIn the first test case, the array is $$$[1, 2]$$$. Currently, the bitwise AND is $$$0$$$, as $$$1\ \& \ 2 = 0$$$. However, after deleting $$$1$$$ (or $$$2$$$), the array becomes $$$[2]$$$ (or $$$[1]$$$), and the bitwise AND becomes $$$2$$$ (or $$$1$$$). This can be proven to be the optimal, so the answer is $$$1$$$.In the second test case, the array is $$$[2, 3, 4, 5, 6, 7, 8]$$$. Currently, the bitwise AND is $$$0$$$. However, after deleting $$$4$$$, $$$5$$$, and $$$8$$$, the array becomes $$$[2, 3, 6, 7]$$$, and the bitwise AND becomes $$$2$$$. This can be proven to be the optimal, so the answer is $$$3$$$. Note that there may be other ways to delete $$$3$$$ elements.

package main

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

const MOD int64 = 1000000007

var l, r int

var w = bufio.NewWriter(os.Stdout)

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

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

var pref [19][]int

func main() {

	read := bufio.NewReader(os.Stdin)

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

	prec()

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

		fmt.Fscan(read, &l, &r)

		a := solve()

		fmt.Fprintln(w, a)
	}
	w.Flush()
}

type pair struct {
	v int
	idx []int
}

func prec() {

	for j := 0; j <= 18; j++ {
		pref[j] = make([]int, 2e5 + 1)
	}

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

		b := (1 >> uint(i)) & 0x1

		if b == 0 {
			pref[i][1] = 1
		}
	}

	for j := 0; j <= 18; j++ {

		for i := 2; i <= 2e5; i++ {
			b := (i >> uint(j)) & 0x1

			pref[j][i] = pref[j][i - 1]

			if b == 0 {
				pref[j][i]++
			}
		}
	}

}

func solve() int {

	var min int = 1e9

	for i := 0; i < len(pref); i++ {
		p := pref[i]

		var v int

		if l == 1 {
			v = p[r]
		} else {
			v = p[r] - p[l - 1]
		}

		if v < min {
			min = v
		}

	}

	return min
}

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

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	defer writer.Flush()
// 	redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var l, r int
	scan(&l, &r)
	var ans = 1 << 30
	for bit := 0; bit < 20; bit++ {
		cnt := c(r, bit) - c(l-1, bit)
		if ans > cnt {
			ans = cnt
		}
	}
	printf("%v\n", ans)
}

func c(x, b int) (r int) {
	x++
	r += (1 << b) * (x / (1 << (b + 1)))
	x %= 1 << (b + 1)
	if x > (1 << b) {
		x = (1 << b)
	}
	r += x
	return
}

package main

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

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

	m := make([][18]int, 2e5+1)
	for i := 1; i <= 2e5; i++ {
		t := i
		var j int
		for t > 0 {
			m[i][j] = m[i-1][j] + (t & 1)
			j++
			t >>= 1
		}
	}

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var l, r int
		fmt.Fscan(in, &l, &r)

		var max int
		for i := 0; i < 18; i++ {
			if m[r][i]-m[l-1][i] > max {
				max = m[r][i] - m[l-1][i]
			}
		}

		fmt.Fprintln(out, r-l-max+1)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1615B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	const mx int = 2e5
	s := [mx + 1][18]int{}
	for i := 1; i <= mx; i++ {
		s[i] = s[i-1]
		for x, j := i, 0; x > 0; x >>= 1 {
			s[i][j] += x & 1
			j++
		}
	}

	var T, l, r int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &l, &r)
		l--
		max := 0
		for i := 0; i < 18; i++ {
			if c := s[r][i] - s[l][i]; c > max {
				max = c
			}
		}
		Fprintln(out, r-l-max)
	}
}

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

package main

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

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

var cnt [200005][20]int

func preprocess() {
	for i := 1; i <= 200000; i++ {
		for j := 0; j < 20; j++ {
			if i&(1<<j) > 0 {
				cnt[i][j] = cnt[i-1][j] + 1
			} else {
				cnt[i][j] = cnt[i-1][j]
			}
		}
	}
}

func solve(t int) {
	l := readInt()
	r := readInt()
	res := 999999
	for j := 0; j < 20; j++ {
		printlnErr(l, cnt[l-1][j], r, cnt[r-1][j])
		if (r-l+1)-(cnt[r][j]-cnt[l-1][j]) < res {
			res = (r - l + 1) - (cnt[r][j] - cnt[l-1][j])
		}
	}
	println(res)

}

func main() {
	preprocess()
	var t int
	fmt.Fscan(in, &t)

	for i := 0; i < t; i++ {
		solve(i)
	}
}

// READ
func readInt() int {
	var res int
	fmt.Fscan(in, &res)
	return res
}

func readInt64() int64 {
	var res int64
	fmt.Fscan(in, &res)
	return res
}

func readString() string {
	var res string
	fmt.Fscan(in, &res)
	return res
}

// PRINT
func print(args ...interface{}) {
	fmt.Fprint(out, args...)
	out.Flush()
}

func println(args ...interface{}) {
	fmt.Fprintln(out, args...)
	out.Flush()
}

func printErr(args ...interface{}) {
	fmt.Fprint(err, args...)
	err.Flush()
}

func printlnErr(args ...interface{}) {
	fmt.Fprintln(err, args...)
	err.Flush()
}

package main

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

var (
	rr = bufio.NewReader(os.Stdin)
	ww = bufio.NewWriter(os.Stdout)
)

func main() {

	// ar count 0
	var ar [][]int64
	var check int64
	check = int64(1)

	for i := int64(0); i < 20; i++ {
		var arr []int64
		arr = append(arr, 1)
		for j := int64(1); j < 200100; j++ {
			last := arr[j-1]
			if (j & check) == 0 {
				last++
			}
			arr = append(arr, last)
		}

		check *= 2
		ar = append(ar, arr)
	}

	var t int64
	fmt.Fscan(rr, &t)

	for i := int64(0); i < t; i++ {

		var l int64
		fmt.Fscan(rr, &l)

		var r int64
		fmt.Fscan(rr, &r)

		numberOfInt := r - l + 1

		var ans int64
		ans = numberOfInt

		for i := int64(0); i < 20; i++ {
			var tmp int64

			tmp = ar[i][r] - ar[i][l-1]
			// fmt.Println(tmp)
			if tmp < ans {
				ans = tmp
			}
		}

		fmt.Fprintln(ww, ans)
		ww.Flush()

	}
	ww.Flush()
}

package main

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

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

func count1(a, bit int) int {
	a++
	var p2 = (1 << bit)
	var remainder = a%(p2*2) - p2
	if remainder < 0 {
		remainder = 0
	}
	return p2*(a/(p2*2)) + remainder
}

func solve() {
	var a, b int
	fmt.Fscan(in, &a, &b)
	var ans = b - a + 1
	for bit := 0; bit <= 22; bit++ {
		var c1 = count1(b, bit) - count1(a-1, bit)
		var bitAns = (b - a + 1) - c1
		if bitAns < ans {
			ans = bitAns
		}
	}
	fmt.Fprintf(out, "%d\n", ans)
}

func main() {
	var ntc int
	fmt.Fscan(in, &ntc)
	for t := 0; t < ntc; t++ {
		solve()
	}
	out.Flush()
}


Alice became interested in periods of integer numbers. We say positive $$$X$$$ integer number is periodic with length $$$L$$$ if there exists positive integer number $$$P$$$ with $$$L$$$ digits such that $$$X$$$ can be written as $$$PPPP…P$$$. For example:$$$X = 123123123$$$ is periodic number with length $$$L = 3$$$ and $$$L = 9$$$$$$X = 42424242$$$ is periodic number with length $$$L = 2,L = 4$$$ and $$$L = 8$$$$$$X = 12345$$$ is periodic number with length $$$L = 5$$$For given positive period length $$$L$$$ and positive integer number $$$A$$$, Alice wants to find smallest integer number $$$X$$$ strictly greater than $$$A$$$ that is periodic with length L.

First line contains one positive integer number $$$L \ (1 \leq L \leq 10^5)$$$ representing length of the period. Second line contains one positive integer number $$$A \ (1 \leq A \leq 10^{100 000})$$$.

One positive integer number representing smallest positive number that is periodic with length $$$L$$$ and is greater than $$$A$$$.

NoteIn first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124).In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)

package main

import (
	"bufio"
	"fmt"
	"math/big"
	"os"
	"strconv"
	"strings"
)

var (
	cin    *bufio.Reader
	bigOne *big.Int
)

func init() {
	cin = bufio.NewReader(os.Stdin)
	bigOne = big.NewInt(1)
}

func main() {

	L, _ := InputInt64()
	A, _ := InputString()

	N := int64(len(A)) / L

	// A len doesn't mod to L -> 100...
	if (int64(len(A)) % L) != 0 {
		N++
		base := buildZeroBase(L)

		output(base, N)
		return
	}

	base := big.NewInt(0)
	{
		baseString := A[:L]
		base.SetString(baseString, 10)
	}

	for i := int64(1); i < N; i++ {
		part := big.NewInt(0)
		{
			partString := A[i*L : (i+1)*L]
			part.SetString(partString, 10)
		}

		if base.Cmp(part) == -1 {
			base.Add(base, bigOne)
			baseStr := base.String()

			// 999 case
			if int64(len(baseStr)) > L {
				baseStr = buildZeroBase(L)
				N++
			}

			output(baseStr, N)
			return
		}
		if base.Cmp(part) == 1 {
			output(base.String(), N)
			return
		}
	}

	// all are equal to base -> upping it
	base.Add(base, bigOne)
	baseStr := base.String()

	// 999 case
	if int64(len(baseStr)) > L {
		baseStr = buildZeroBase(L)
		N++
	}

	output(baseStr, N)
	return
}

func output(base string, n int64) {
	X := strings.Builder{}
	for i := int64(0); i < n; i++ {
		X.WriteString(base)
	}
	Output(X.String())
}

func InputString() (string, error) {
	line, err := inputLine()
	if err != nil {
		return "", err
	}

	return line[0], nil
}

func InputInt64() (int64, error) {
	line, err := inputLine()
	if err != nil {
		return 0, err
	}

	return strconv.ParseInt(line[0], 10, 64)

}

func InputLineString() ([]string, error) {
	return inputLine()
}

func InputLineInt64() ([]int64, error) {

	words, err := inputLine()
	if err != nil {
		return nil, err
	}

	a := make([]int64, 0, len(words))
	for _, word := range words {
		num, err := strconv.ParseInt(word, 10, 64)
		if err != nil {
			return nil, err
		}
		a = append(a, num)
	}

	return a, nil

}

func inputLine() ([]string, error) {

	line, err := cin.ReadString('\r')
	if err != nil {
		return nil, err
	}
	_, _ = cin.ReadString('\n')

	// remove '\r'
	line = line[:len(line)-1]

	return strings.Split(line, " "), nil

}

func Output(vals ...interface{}) error {
	outStr := strings.Builder{}
	for _, val := range vals {
		outStr.WriteString(fmt.Sprintf("%v ", val))
	}
	_, err := os.Stdout.WriteString(outStr.String())
	return err
}

func buildZeroBase(l int64) string {
	baseBuilder := strings.Builder{}
	baseBuilder.Grow(int(l))

	baseBuilder.WriteString("1")
	for i := int64(0); i < l-1; i++ {
		baseBuilder.WriteString("0")
	}
	return baseBuilder.String()
}

package main

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

var cin *bufio.Reader

func init() {
	cin = bufio.NewReader(os.Stdin)
}

func main() {

	L, _ := InputInt64()
	A, _ := InputString()

	N := int64(len(A)) / L

	// A len doesn't mod to L -> 100...
	if (int64(len(A)) % L) != 0 {
		N++

		baseBuilder := strings.Builder{}
		baseBuilder.Grow(int(N))

		baseBuilder.WriteString("1")
		for i := int64(0); i < L-1; i++ {
			baseBuilder.WriteString("0")
		}
		base := baseBuilder.String()

		output(base, N)
		return
	}

	var base int64
	{
		baseString := A[:L]
		base, _ = strconv.ParseInt(baseString, 10, 64)
	}

	for i := int64(1); i < N; i++ {
		var part int64
		{
			partString := A[i*L : (i+1)*L]
			part, _ = strconv.ParseInt(partString, 10, 64)
		}

		if base < part {
			base++
			output(strconv.FormatInt(base, 10), N)
			return
		}
		if base > part {
			output(strconv.FormatInt(base, 10), N)
			return
		}
	}

	// all are equal to base -> upping it
	base++
	output(strconv.FormatInt(base, 10), N)
	return
}

func output(base string, n int64) {
	X := strings.Builder{}
	for i := int64(0); i < n; i++ {
		X.WriteString(base)
	}
	Output(X.String())
}

func InputString() (string, error) {
	line, err := inputLine()
	if err != nil {
		return "", err
	}

	return line[0], nil
}

func InputInt64() (int64, error) {
	line, err := inputLine()
	if err != nil {
		return 0, err
	}

	return strconv.ParseInt(line[0], 10, 64)

}

func InputLineString() ([]string, error) {
	return inputLine()
}

func InputLineInt64() ([]int64, error) {

	words, err := inputLine()
	if err != nil {
		return nil, err
	}

	a := make([]int64, 0, len(words))
	for _, word := range words {
		num, err := strconv.ParseInt(word, 10, 64)
		if err != nil {
			return nil, err
		}
		a = append(a, num)
	}

	return a, nil

}

func inputLine() ([]string, error) {

	line, err := cin.ReadString('\r')
	if err != nil {
		return nil, err
	}
	_, _ = cin.ReadString('\n')

	// remove '\r'
	line = line[:len(line)-1]

	return strings.Split(line, " "), nil

}

func Output(vals ...interface{}) error {
	outStr := strings.Builder{}
	for _, val := range vals {
		outStr.WriteString(fmt.Sprintf("%v ", val))
	}
	_, err := os.Stdout.WriteString(outStr.String())
	return err
}

package main

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

var cin *bufio.Reader

func init() {
	cin = bufio.NewReader(os.Stdin)
}

func main() {

	L, _ := InputInt64()
	A, _ := InputString()

	N := int64(len(A)) / L

	// A len doesn't mod to L -> 100...
	if (int64(len(A)) % L) != 0 {
		N++
		base := buildZeroBase(L)

		output(base, N)
		return
	}

	var base int64
	{
		baseString := A[:L]
		base, _ = strconv.ParseInt(baseString, 10, 64)
	}

	for i := int64(1); i < N; i++ {
		var part int64
		{
			partString := A[i*L : (i+1)*L]
			part, _ = strconv.ParseInt(partString, 10, 64)
		}

		if base < part {
			base++
			baseStr := strconv.FormatInt(base, 10)

			// 999 case
			if int64(len(baseStr)) > L {
				baseStr = buildZeroBase(L)
				N++
			}

			output(baseStr, N)
			return
		}
		if base > part {
			output(strconv.FormatInt(base, 10), N)
			return
		}
	}

	// all are equal to base -> upping it
	base++
	baseStr := strconv.FormatInt(base, 10)

	// 999 case
	if int64(len(baseStr)) > L {
		baseStr = buildZeroBase(L)
		N++
	}

	output(baseStr, N)
	return
}

func output(base string, n int64) {
	X := strings.Builder{}
	for i := int64(0); i < n; i++ {
		X.WriteString(base)
	}
	Output(X.String())
}

func InputString() (string, error) {
	line, err := inputLine()
	if err != nil {
		return "", err
	}

	return line[0], nil
}

func InputInt64() (int64, error) {
	line, err := inputLine()
	if err != nil {
		return 0, err
	}

	return strconv.ParseInt(line[0], 10, 64)

}

func InputLineString() ([]string, error) {
	return inputLine()
}

func InputLineInt64() ([]int64, error) {

	words, err := inputLine()
	if err != nil {
		return nil, err
	}

	a := make([]int64, 0, len(words))
	for _, word := range words {
		num, err := strconv.ParseInt(word, 10, 64)
		if err != nil {
			return nil, err
		}
		a = append(a, num)
	}

	return a, nil

}

func inputLine() ([]string, error) {

	line, err := cin.ReadString('\r')
	if err != nil {
		return nil, err
	}
	_, _ = cin.ReadString('\n')

	// remove '\r'
	line = line[:len(line)-1]

	return strings.Split(line, " "), nil

}

func Output(vals ...interface{}) error {
	outStr := strings.Builder{}
	for _, val := range vals {
		outStr.WriteString(fmt.Sprintf("%v ", val))
	}
	_, err := os.Stdout.WriteString(outStr.String())
	return err
}

func buildZeroBase(l int64) string {
	baseBuilder := strings.Builder{}
	baseBuilder.Grow(int(l))

	baseBuilder.WriteString("1")
	for i := int64(0); i < l-1; i++ {
		baseBuilder.WriteString("0")
	}
	return baseBuilder.String()
}


After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:  There is at least one digit in the string,  There is at least one lowercase (small) letter of the Latin alphabet in the string,  There is at least one of three listed symbols in the string: '#', '*', '&'.   Considering that these are programming classes it is not easy to write the password.For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.

The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols.  Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password.

Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.

NoteIn the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.   In the second test one of possible algorithms will be:   to move the pointer of the second symbol once to the right.  to move the pointer of the third symbol twice to the right.

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"reflect"
	"unicode"
)

func main() {
	var n, m int
	fmt.Fscan(reader, &n, &m)
	pointers := make([]string, n)
	for i := range pointers {
		fmt.Fscan(reader, &pointers[i])
	}
	digit, letter, special := getAllInfo(pointers)
	//fmt.Println(digit)
	//fmt.Println(letter)
	//fmt.Println(special)
	ans := int(1e6)
	for d := 0; d < n; d++ {
		for l := 0; l < n; l++ {
			if d != l {
				for s := 0; s < n; s++ {
					if s != d && s != l {
						if max(digit[d], max(letter[l], special[s])) < m {
							ans = min(ans, digit[d]+letter[l]+special[s])
							//fmt.Println(d, l, s, ans)
						}
					}
				}
			}
		}
	}
	fmt.Fprintln(writer, ans)
	writer.Flush()
}

func getAllInfo(pointers []string) (digit, letter, special []int) {
	for _, pointer := range pointers {
		d, l, s := getInfo(pointer)
		digit = append(digit, d)
		letter = append(letter, l)
		special = append(special, s)
	}
	return
}

func getInfo(pointer string) (digit, letter, special int) {
	digit, letter, special = len(pointer), len(pointer), len(pointer)
	for i, char := range pointer {
		if unicode.IsDigit(char) {
			digit = min(digit, min(i, len(pointer)-i))
		} else if unicode.IsLetter(char) {
			letter = min(letter, min(i, len(pointer)-i))
		} else {
			special = min(special, min(i, len(pointer)-i))
		}
	}
	return
}

func found(k, s []int, l int) bool {
	s = decrease(s, 0, l)
	for i := range k {
		tempK := decrease(k, i, l)
		if reflect.DeepEqual(s, tempK) {
			return true
		}
	}
	return false
}

func decrease(values []int, pos, l int) []int {
	ans := make([]int, len(values))
	for i := range ans {
		ans[(i-pos+len(ans))%len(ans)] = (values[i] - values[pos] + l) % l
	}
	return ans
}

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

func abs64(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

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

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

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

func min64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

var (
	reader = bufio.NewReaderSize(os.Stdin, 1<<13)
	writer = bufio.NewWriterSize(os.Stdout, 1<<13)
)

func readi() int {
	return int(readi64())
}

func read2i() (int, int) {
	return readi(), readi()
}

func readis(n int) []int {
	res := make([]int, n)
	for i := range res {
		res[i] = readi()
	}
	return res
}

func readi64() int64 {
	b, err := reader.ReadByte()
	for !isValid(b, err) {
		b, err = reader.ReadByte()
	}
	sign, res := int64(1), int64(0)
	if b == '-' {
		sign *= -1
		b, err = reader.ReadByte()
	}
	for isValid(b, err) {
		res = res*10 + int64(b-'0')
		b, err = reader.ReadByte()
	}
	return res * sign
}

func readline() string {
	res := new(bytes.Buffer)
	for {
		line, isPrefix, err := reader.ReadLine()
		if err != nil {
			panic(err)
		}
		res.Write(line)
		if !isPrefix {
			break
		}
	}
	return res.String()
}

func isValid(b byte, err error) bool {
	return err == nil && (('0' <= b && b <= '9') || b == '-')
}

package main

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

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

type Int int64

func main() {
	defer w.Flush()
	var n, m Int
	for I(&n, &m) == nil {
		solve(n, m)
	}
}

func solve(n, m Int) {
	t := make([]string, n)
	for i := Int(0); i < n; i++ {
		I(&t[i])
	}
	o := make([][3]Int, n)
	for i := Int(0); i < n; i++ {
		o[i] = [3]Int{1e4, 1e4, 1e4}
	}
	for i := Int(0); i < n; i++ {
		for j := Int(0); j < m; j++ {
			min(&o[i][c(t[i][j])], j)
			min(&o[i][c(t[i][j])], m-j)
		}
	}
	ans := Int(1e13)
	for i := Int(0); i < n; i++ {
		for j := Int(0); j < n; j++ {
			for p := Int(0); p < n; p++ {
				if i != j && j != p && i != p {
					min(&ans, o[i][0]+o[j][1]+o[p][2])
				}
			}
		}
	}
	O(ans, "\n")
}

func min(a *Int, b Int) {
	if *a > b {
		*a = b
	}
}

func c(a byte) Int {
	if a >= 'a' && a <= 'z' {
		return 0
	} else if a >= '0' && a <= '9' {
		return 1
	}
	return 2
}

package main

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

var best = 100000

func solve() {
	n := readInt()
	m := readInt()
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = readString()
		a[i] += a[i]
	}
	res := make([][]int, n)
	for k, v := range a {
		res[k] = make([]int, 3)
		minL := 10000
		minS := 10000
		minN := 10000
		for i := 0; i < len(v); i++ {
			ch := v[i]
			if ch >= '0' && ch <= '9' {
				minN = min(minN, abs(i-m))
			} else if ch == '#' || ch == '&' || ch == '*' {
				minS = min(minS, abs(i-m))
			} else {
				minL = min(minL, abs(i-m))
			}
		}
		res[k][0] = minL
		res[k][1] = minS
		res[k][2] = minN
	}
	visited := make([]bool, n)
	dfs(res, 0, visited, 0)
	fmt.Println(best)
}

func dfs(cost [][]int, column int, visited []bool, res int) {
	if column == 3 {
		best = min(best, res)
		return
	}
	for i := 0; i < len(visited); i++ {
		if !visited[i] && cost[i][column] != 10000 {
			visited[i] = true
			dfs(cost, column+1, visited, res+cost[i][column])
			visited[i] = false
		}
	}
}

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

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

var scanner *bufio.Scanner

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

// IO

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

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

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

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

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

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

package main

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

const INF int = 5555

func Solve(io *FastIO) {
	bit := make(map[rune]uint)
	for c := '0'; c <= '9'; c++ {
		bit[c] = 0
	}
	for c := 'a'; c <= 'z'; c++ {
		bit[c] = 1
	}
	bit['#'] = 2
	bit['*'] = 2
	bit['&'] = 2

	N := io.NextInt()
	M := io.NextInt()

	dp := make([]int, 8)
	FillArray(dp, INF)
	dp[0] = 0

	for i := 0; i < N; i++ {
		S := io.NextLine()

		next := make([]int, 8)
		copy(next, dp)

		for j, c := range S {
			dist := Min(j, M - j)
			mask := 1 << bit[c]
			for k, v := range dp {
				nextMask := k | mask
				next[nextMask] = Min(next[nextMask], v + dist)
			}
		}

		copy(dp, next)
	}
	io.Println(dp[7])
}

func Min(args ...int) int {
	min := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] < min {
			min = args[i]
		}
	}
	return min
}

func FillArray(arr []int, val int) {
	for i := range arr {
		arr[i] = val
	}
}

type FastIO struct {
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}

func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = (res * 10) + int(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = (res * 10) + int64(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}

func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextInt()
	}
	return arr
}

func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}

func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextLong()
	}
	return arr
}

func (io *FastIO) NextString() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}

func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}

func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}

func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}

func IsLineBreakChar(c byte) bool {
	switch c {
		case 0, '\n', '\r':
			return true
		default:
			return false
	}
}

func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Solve(&io)
	io.FlushOutput()
}

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"reflect"
	"unicode"
)

func main() {
	var n, m int
	fmt.Fscan(reader, &n, &m)
	pointers := make([]string, n)
	for i := range pointers {
		fmt.Fscan(reader, &pointers[i])
	}
	digit, letter, special := getAllInfo(pointers)
	//fmt.Println(digit)
	//fmt.Println(letter)
	//fmt.Println(special)
	ans := int(1e6)
	for d := 0; d < n; d++ {
		for l := 0; l < n; l++ {
			if d != l {
				for s := 0; s < n; s++ {
					if s != d && s != l {
						if max(digit[d], max(letter[l], special[s])) < m {
							ans = min(ans, n-3+digit[d]+letter[l]+special[s])
						}
					}
				}
			}
		}
	}
	fmt.Fprintln(writer, ans)
	writer.Flush()
}

func getAllInfo(pointers []string) (digit, letter, special []int) {
	for _, pointer := range pointers {
		d, l, s := getInfo(pointer)
		digit = append(digit, d)
		letter = append(letter, l)
		special = append(special, s)
	}
	return
}

func getInfo(pointer string) (digit, letter, special int) {
	digit, letter, special = len(pointer), len(pointer), len(pointer)
	for i, char := range pointer {
		if unicode.IsDigit(char) {
			digit = min(digit, min(i, len(pointer)-i))
		} else if unicode.IsLetter(char) {
			letter = min(letter, min(i, len(pointer)-i))
		} else {
			special = min(special, min(i, len(pointer)-i))
		}
	}
	return
}

func found(k, s []int, l int) bool {
	s = decrease(s, 0, l)
	for i := range k {
		tempK := decrease(k, i, l)
		if reflect.DeepEqual(s, tempK) {
			return true
		}
	}
	return false
}

func decrease(values []int, pos, l int) []int {
	ans := make([]int, len(values))
	for i := range ans {
		ans[(i-pos+len(ans))%len(ans)] = (values[i] - values[pos] + l) % l
	}
	return ans
}

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

func abs64(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

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

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

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

func min64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

var (
	reader = bufio.NewReaderSize(os.Stdin, 1<<13)
	writer = bufio.NewWriterSize(os.Stdout, 1<<13)
)

func readi() int {
	return int(readi64())
}

func read2i() (int, int) {
	return readi(), readi()
}

func readis(n int) []int {
	res := make([]int, n)
	for i := range res {
		res[i] = readi()
	}
	return res
}

func readi64() int64 {
	b, err := reader.ReadByte()
	for !isValid(b, err) {
		b, err = reader.ReadByte()
	}
	sign, res := int64(1), int64(0)
	if b == '-' {
		sign *= -1
		b, err = reader.ReadByte()
	}
	for isValid(b, err) {
		res = res*10 + int64(b-'0')
		b, err = reader.ReadByte()
	}
	return res * sign
}

func readline() string {
	res := new(bytes.Buffer)
	for {
		line, isPrefix, err := reader.ReadLine()
		if err != nil {
			panic(err)
		}
		res.Write(line)
		if !isPrefix {
			break
		}
	}
	return res.String()
}

func isValid(b byte, err error) bool {
	return err == nil && (('0' <= b && b <= '9') || b == '-')
}


Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.

The first line contains integer n (1 ≤ n ≤ 105) — the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105.  The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.

In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.

7
i
am
not
main
in
the
family
<3i<>3am<3the<3<main<3in<3the<3><3family<3

NotePlease note that Dima got a good old kick in the pants for the second sample from the statement.

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n int
	fmt.Scan(&n)
	words := make([]string, n + 2)
	for i := 1; i <= n; i++ {
		fmt.Scan(&words[i])
	}
	msg := strings.Join(words, "<3")
	var msgrnd string
	fmt.Scan(&msgrnd)
	var i int
Loop:
	for j := range msg {
		for ; i < len(msgrnd); i++ {
			if msgrnd[i] == msg[j] {
				i++
				continue Loop
			}
		}
		fmt.Println("no")
		return
	}
	fmt.Println("yes")
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n,i int
	var s string
	fmt.Scan(&n)
	in := make([]string,n+2)
	for i := 1; i <= n; i++ {
		fmt.Scan(&in[i])
	}
	complete := strings.Join(in,"<3")
	fmt.Scan(&s)

again:
	for j := range complete {
		for ;i<len(s);i++ {
			if s[i]==complete[j] {
				i++
				continue again
			}
		}
		fmt.Println("no")
		return
	}
	fmt.Println("yes")
	return
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n int
	fmt.Scan(&n)
	words := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&words[i])
	}
	msg := strings.Join(words, "<3")
	var msgrnd string
	fmt.Scan(&msgrnd)
	var i int
Loop:
	for j := range msg {
		for ; i < len(msgrnd); i++ {
			if msgrnd[i] == msg[j] {
				i++
				continue Loop
			}
		}
		fmt.Println("no")
		return
	}
	fmt.Println("yes")
}

package main
import (
	"fmt"
	"bufio"
	"os"
	"strconv"
)
func main() {
	var i,n,j int
	reader:= bufio.NewReader(os.Stdin)
	input := bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanLines)
	var s,ch,z string
	input.Scan()
	b,_:= strconv.Atoi(input.Text())
	n=b
	//fmt.Scan(&n)
	s+="<3"
	for i=0;i<n;i++ {
		//input.Scan()
		//z=input.Text()
		fmt.Fscan(reader,&z)
		s+=z+"<3"
	}
	input.Scan()
	ch=input.Text()
	//fmt.Fscan(reader,&ch)
	if len(ch)<len(s) {
		fmt.Println("no")
		return
	} else {
	j=0
	for i=0;i<len(s) && j<len(ch) && len(ch)-j>=len(s)-i;i++ {
		for ch[j]!=s[i] && j!=len(ch) {
			j++
		}
		j++
	}

	if i==len(s) {
		fmt.Println("yes")
	} else {
		fmt.Println("no")
	}}
}

package main
import (
	"fmt"
	"bufio"
	"os"
)
func main() {
	var i,n,a int
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	var x,z,v string
	fmt.Scan(&n)
	z="<3"
	for i=0;i<n;i++ {
		input.Scan()
		x=input.Text()
		//fmt.Fscan(reader,&x)
		z=z+x+"<3"
	}
	flag:=false
	input.Scan()
	v=input.Text()
	//fmt.Fscan(reader,&v)
	a=0
	r:=make([]rune,len(z))
	for i,zz:=range z {
		r[i]=zz
	}

	for _,vv := range v {
		if vv==r[a] {
			a++
		}
		if a==len(z) {
			flag=true
			break
		}
	}

	if flag==true {
		fmt.Println("yes")
	} else {
		fmt.Println("no")
	}
}

package main
import (
	"fmt"
	"bufio"
	"os"
)
func main() {
	var i,n,j int
	reader:= bufio.NewReader(os.Stdin)
	input := bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	var s,ch string
	fmt.Scan(&n)
	s+="<3"
	for i=0;i<n;i++ {
		input.Scan()
		ch=input.Text()
		//fmt.Fscan(reader,&ch)
		s+=ch+"<3"
	}
	fmt.Fscan(reader,&ch)
	if len(ch)<len(s) {
		fmt.Println("no")
		return
	} else {
	j=0
	for i=0;i<len(s) && j<len(ch) && len(ch)-j>=len(s)-i;i++ {
		for ch[j]!=s[i] && j!=len(ch) {
			j++
		}
		j++
	}

	if i==len(s) {
		fmt.Println("yes")
	} else {
		fmt.Println("no")
	}}
}

package main
import (
	"fmt"
	"bufio"
	"os"
)
func main() {
	var i,n,j int
	reader:= bufio.NewReader(os.Stdin)
	input := bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	var s,ch,z string
	fmt.Scan(&n)
	s+="<3"
	for i=0;i<n;i++ {
		input.Scan()
		z=input.Text()
		//fmt.Fscan(reader,&ch)
		s+=z+"<3"
	}
	fmt.Fscan(reader,&ch)
	if len(ch)<len(s) {
		fmt.Println("no")
		return
	} else {
	j=0
	for i=0;i<len(s) && j<len(ch) && len(ch)-j>=len(s)-i;i++ {
		for ch[j]!=s[i] && j!=len(ch) {
			j++
		}
		j++
	}

	if i==len(s) {
		fmt.Println("yes")
	} else {
		fmt.Println("no")
	}}
}

package main
import (
	"fmt"
	"bufio"
	"os"
	"strconv"
)
func main() {
	var i,n,j int
	//reader:= bufio.NewReader(os.Stdin)
	input := bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanLines)
	var s,ch string
	input.Scan()
	b,_:= strconv.Atoi(input.Text())
	n=b
	//fmt.Scan(&n)
	s+="<3"
	for i=0;i<n;i++ {
		input.Scan()
		//z=input.Text()
		//fmt.Fscan(reader,&ch)
		s+=input.Text()+"<3"
	}
	input.Scan()
	ch=input.Text()
	//fmt.Fscan(reader,&ch)
	if len(ch)<len(s) {
		fmt.Println("no")
		return
	} else {
	j=0
	for i=0;i<len(s) && j<len(ch) && len(ch)-j>=len(s)-i;i++ {
		for ch[j]!=s[i] && j!=len(ch) {
			j++
		}
		j++
	}

	if i==len(s) {
		fmt.Println("yes")
	} else {
		fmt.Println("no")
	}}
}


Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies.In order to avoid this representatives of both companies decided to make an agreement on the sets the companies should present. The sets should be chosen in the way that maximizes the total income of the companies.All elements are enumerated with integers. The ChemForces company has discovered $$$n$$$ distinct chemical elements with indices $$$a_1, a_2, \ldots, a_n$$$, and will get an income of $$$x_i$$$ Berland rubles if the $$$i$$$-th element from this list is in the set of this company.The TopChemist company discovered $$$m$$$ distinct chemical elements with indices $$$b_1, b_2, \ldots, b_m$$$, and it will get an income of $$$y_j$$$ Berland rubles for including the $$$j$$$-th element from this list to its set.In other words, the first company can present any subset of elements from $$$\{a_1, a_2, \ldots, a_n\}$$$ (possibly empty subset), the second company can present any subset of elements from $$$\{b_1, b_2, \ldots, b_m\}$$$ (possibly empty subset). There shouldn't be equal elements in the subsets.Help the representatives select the sets in such a way that no element is presented in both sets and the total income is the maximum possible.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$)  — the number of elements discovered by ChemForces. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$x_i$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$1 \leq x_i \leq 10^9$$$)  — the index of the $$$i$$$-th element and the income of its usage on the exhibition. It is guaranteed that all $$$a_i$$$ are distinct. The next line contains a single integer $$$m$$$ ($$$1 \leq m \leq 10^5$$$)  — the number of chemicals invented by TopChemist. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$b_j$$$ and $$$y_j$$$, ($$$1 \leq b_j \leq 10^9$$$, $$$1 \leq y_j \leq 10^9$$$)  — the index of the $$$j$$$-th element and the income of its usage on the exhibition. It is guaranteed that all $$$b_j$$$ are distinct.

Print the maximum total income you can obtain by choosing the sets for both companies in such a way that no element is presented in both sets.

NoteIn the first example ChemForces can choose the set ($$$3, 7$$$), while TopChemist can choose ($$$1, 2, 4$$$). This way the total income is $$$(10 + 2) + (4 + 4 + 4) = 24$$$.In the second example ChemForces can choose the only element $$$10^9$$$, while TopChemist can choose ($$$14, 92, 35$$$). This way the total income is $$$(239) + (15 + 65 + 89) = 408$$$.

package main

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

var in = bufio.NewScanner(os.Stdin)

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

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

	income := make(map[int64]int64, 2e5)

	n := int(readInt())
	for i := 0; i < n; i++ {
		a := readInt()
		x := readInt()
		income[a] = x
	}

	m := int(readInt())
	for i := 0; i < m; i++ {
		b := readInt()
		y := readInt()
		if income[b] < y {
			income[b] = y
		}
	}

	ans := int64(0)
	for _, i := range income {
		ans += i
	}
	fmt.Println(ans)
}

package main

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

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

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

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

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

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

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

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

// https://codeforces.com/contest/981/problem/B
func problem(C *Contest) {
	n := C.InInt()
	c := make(map[int]int64, n)

	var sum int64
	for i := 0; i < n; i++ {
		a := C.InInt()
		x := C.InInt64()

		c[a] = x
		sum += x
	}

	m := C.InInt()
	for j := 0; j < m; j++ {
		b := C.InInt()
		y := C.InInt64()

		d := y - c[b]
		if d > 0 {
			sum += d
		}
	}

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

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

package main

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

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

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

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

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

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

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

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

// https://codeforces.com/contest/981/problem/B
func problem(C *Contest) {
	//n := C.InInt()
	//c := make(map[int]int64, n)
	//
	//var sum int64
	//for i := 0; i < n; i++ {
	//	a := C.InInt()
	//	x := C.InInt64()
	//
	//	c[a] = x
	//	sum += x
	//}
	//
	//m := C.InInt()
	//for j := 0; j < m; j++ {
	//	b := C.InInt()
	//	y := C.InInt64()
	//
	//	if d := y - c[b]; d > 0 {
	//		sum += d
	//	}
	//}
	//
	//C.Out("%d\n", sum)

	var ai, xi int
	var bi, yi int
	var sum int64

	map1 := map[int]int{}
	map2 := map[int]int{}

	n := C.InInt()
	for i:= 0; i<n; i++{
		ai = C.InInt()
		xi = C.InInt()
		map1[ai] = xi
	}

	m := C.InInt()
	for i:= 0; i<m; i++{
		bi = C.InInt()
		yi = C.InInt()

		tmp, ok := map1[bi]
		if ok {
			if tmp < yi {
				map1[bi] = 0
				map2[bi] = yi
			}
			continue
		}
		map2[bi] = yi
	}

	for _, v := range map1 {
		sum += int64(v)
	}
	for _, v := range map2 {
		sum += int64(v)
	}

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

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

package main

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

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

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

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

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

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

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

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

// https://codeforces.com/contest/981/problem/B
func problem(C *Contest) {
	n := C.InInt()
	c := make(map[int]int64, n)

	var sum int64
	for i := 0; i < n; i++ {
		a := C.InInt()
		x := C.InInt64()

		c[a] = x
		sum += x
	}

	m := C.InInt()
	for j := 0; j < m; j++ {
		b := C.InInt()
		y := C.InInt64()

		if d := y - c[b]; d > 0 {
			sum += d
		}
	}

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

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

package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

var ai, xi int
var bi, yi int
var sum int64
func main(){
	sc.Split(bufio.ScanWords)
	map1 := map[int]int{}
	map2 := map[int]int{}

	n := nextInt()
	for i:= 0; i<n; i++{
		ai = nextInt()
		xi = nextInt()
		map1[ai] = xi
	}

	m := nextInt()
	for i:= 0; i<m; i++{
		bi = nextInt()
		yi = nextInt()

		tmp, ok := map1[bi]
		if ok {
			if tmp < yi {
				map1[bi] = 0
				map2[bi] = yi
			}
			continue
		}
		map2[bi] = yi
	}

	for _, v := range map1 {
		sum += int64(v)
	}
	for _, v := range map2 {
		sum += int64(v)
	}
	fmt.Printf("%d", sum)

}

package main

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

type contestIn struct {
	reader io.Reader
}

type contestOut struct {
	writer io.Writer
}

type contestFunc struct {}

type Contest struct {
	In contestIn
	Out contestOut
	F contestFunc
}

func NewSubmitContest() Contest {
	return Contest{contestIn{os.Stdin}, contestOut{os.Stdout}, contestFunc{}}
}

func NewTestContest(testIn string, testOut *bytes.Buffer) Contest  {
	return Contest{contestIn{strings.NewReader(testIn)}, contestOut{testOut}, contestFunc{}}
}

func (in contestIn) N() {
	fmt.Fscanln(in.reader)
}

func (in contestIn) Var(a interface{}) {
	fmt.Fscan(in.reader, a)
}

func (in contestIn) VarN(a interface{}) {
	in.Var(a)
	in.N()
}

func (in contestIn) Vars(a ...interface{}) {
	fmt.Fscanln(in.reader, a...)
}

func (in contestIn) Str() string {
	var s string
	in.Var(&s)

	return s
}

func (in contestIn) StrN() string {
	defer in.N()
	return in.Str()
}

func (in contestIn) Int() int {
	var i int
	in.Var(&i)

	return i
}

func (in contestIn) IntN() int {
	defer in.N()
	return in.Int()
}

func (in contestIn) Ints(len int) []int {
	arr := make([]int, 0, len)
	for ; len > 0; len-- {
		var i int
		in.Var(&i)
		arr = append(arr, i)
	}

	return arr
}

func (out contestOut) F(format string, a ...interface{}) contestOut {
	fmt.Fprintf(out.writer, format, a...)
	return out
}

func (out contestOut) Str(s string) contestOut {
	fmt.Fprint(out.writer, s)
	return out
}

func (out contestOut) Int(i int) contestOut {
	out.F("%d", i)
	return out
}

func (out contestOut) N() contestOut {
	fmt.Fprintln(out.writer)
	return out
}

func (f contestFunc) MinInt(x, y int) int {
	if x > y {
		return y
	}
	return x
}

func (f contestFunc) MaxInt(x, y int) int {
	if x < y {
		return y
	}
	return x
}

// https://codeforces.com/contest/981/problem/B
func problem(C Contest) {
	c := map[int]int{}

	var a, x int
	for k := 0; k < 2; k++ {
		n := C.In.IntN()
		for i := 0; i < n; i++ {
			C.In.Vars(&a, &x)
			c[a] = C.F.MaxInt(x, c[a])
		}
	}

	sum := 0
	for _, v := range c {
		sum += v
	}

	C.Out.Int(sum).N()
}

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


Don't you tell me what you think that I can beIf you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct hero in the beginning of the game.There are $$$2$$$ teams each having $$$n$$$ players and $$$2n$$$ heroes to distribute between the teams. The teams take turns picking heroes: at first, the first team chooses a hero in its team, after that the second team chooses a hero and so on. Note that after a hero is chosen it becomes unavailable to both teams.The friends estimate the power of the $$$i$$$-th of the heroes as $$$p_i$$$. Each team wants to maximize the total power of its heroes. However, there is one exception: there are $$$m$$$ pairs of heroes that are especially strong against each other, so when any team chooses a hero from such a pair, the other team must choose the other one on its turn. Each hero is in at most one such pair.This is an interactive problem. You are to write a program that will optimally choose the heroes for one team, while the jury's program will play for the other team. Note that the jury's program may behave inefficiently, in this case you have to take the opportunity and still maximize the total power of your team. Formally, if you ever have chance to reach the total power of $$$q$$$ or greater regardless of jury's program choices, you must get $$$q$$$ or greater to pass a test.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^3$$$, $$$0 \le m \le n$$$) — the number of players in one team and the number of special pairs of heroes. The second line contains $$$2n$$$ integers $$$p_1, p_2, \ldots, p_{2n}$$$ ($$$1 \le p_i \le 10^3$$$) — the powers of the heroes. Each of the next $$$m$$$ lines contains two integer $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 2n$$$, $$$a \ne b$$$) — a pair of heroes that are especially strong against each other. It is guaranteed that each hero appears at most once in this list. The next line contains a single integer $$$t$$$ ($$$1 \le t \le 2$$$) — the team you are to play for. If $$$t = 1$$$, the first turn is yours, otherwise you have the second turn. Hacks In order to hack, use the format described above with one additional line. In this line output $$$2n$$$ distinct integers from $$$1$$$ to $$$2n$$$ — the priority order for the jury's team. The jury's team will on each turn select the first possible hero from this list. Here possible means that it is not yet taken and does not contradict the rules about special pair of heroes.

NoteIn the first example the first turn is yours. In example, you choose $$$6$$$, the other team is forced to reply with $$$2$$$. You choose $$$5$$$, the other team chooses $$$4$$$. Finally, you choose $$$3$$$ and the other team choose $$$1$$$.In the second example you have the second turn. The other team chooses $$$6$$$, you choose $$$5$$$, forcing the other team to choose $$$1$$$. Now you choose $$$4$$$, the other team chooses $$$3$$$ and you choose $$$2$$$.

package main

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

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

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

func main() {
	//defer writer.Flush()
	var n, m, t1, t2, tmp, pdiff int
	scanf("%d %d\n", &n, &m)
	p := make([]int, 2*n+1)
	isp := make([]int, 2*n+1)
	taken := make([]bool, 2*n+1)
	pairs := []int{}
	for i := 0; i < 2*n; i++ {
		scanf("%d", &p[i+1])
		//fmt.Println("hiciify", n,m)
		isp[i+1] = -1
		taken[i+1] = false
	}
	scanf("\n")
	//fmt.Println("hic", n,m)
	for i := 0; i < m; i++ {
		scanf("%d %d\n", &t1, &t2)
		//fmt.Println("hic", t1, t2)
		isp[t1] = t2
		isp[t2] = t1
		tmp = p[t1] - p[t2]
		if tmp < 0 {
			tmp *= -1
			pairs = append(pairs, t1)
			pairs = append(pairs, t2)
		} else {
			pairs = append(pairs, t2)
			pairs = append(pairs, t1)
		}
		pdiff += tmp
	}
	var t, cur, w, m1 int
	scanf("%d\n", &t)
	cur = 0
	for cur < 2*n {
		if t == 2 {
			scanf("%d\n", &w)
			cur++
			if cur == 2*n {
				break
			}
			taken[w] = true
			if isp[w] != -1 && taken[isp[w]] == false {
				m1 = isp[w]
				taken[m1] = true
				printf("%d\n", m1)
				cur++
				if p[w] >= p[m1] {
					pdiff -= p[w] - p[m1]
				} else {
					pdiff -= p[m1] - p[w]
				}
				writer.Flush()
			} else {
				flag := false
				for i := 0; i < len(pairs); i += 2 {
					if !taken[pairs[i]] {
						printf("%d\n", pairs[i+1])
						writer.Flush()
						taken[pairs[i+1]] = true
						flag = true
						pdiff -= p[pairs[i+1]] - p[pairs[i]]
						cur++
						break
					}
				}

				if flag == false {
					mx1, ps1 := -1, 0
					for i := 1; i <= 2*n; i++ {
						if !taken[i] && p[i] > mx1 {
							mx1 = p[i]
							ps1 = i
						}
					}
					printf("%d\n", ps1)
					writer.Flush()
					taken[ps1] = true
					cur++
				}
				t = 2
			}
		} else {
			flag := false
			for i := 0; i < len(pairs); i += 2 {
				if !taken[pairs[i]] {
					printf("%d\n", pairs[i+1])
					writer.Flush()
					taken[pairs[i+1]] = true
					flag = true
					pdiff -= p[pairs[i+1]] - p[pairs[i]]
					cur++
					break
				}
			}

			if flag == false {
				mx1, ps1 := -1, 0
				for i := 1; i <= 2*n; i++ {
					if !taken[i] && p[i] > mx1 {
						mx1 = p[i]
						ps1 = i
					}
				}
				printf("%d\n", ps1)
				writer.Flush()
				taken[ps1] = true
				cur++
			}
			t = 2
		}
	}

}