You are given a matrix consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell of this matrix contains $$$0$$$ or $$$1$$$.Let's call a square of size $$$2 \times 2$$$ without one corner cell an L-shape figure. In one operation you can take one L-shape figure, with at least one cell containing $$$1$$$ and replace all numbers in it with zeroes.Find the maximum number of operations that you can do with the given matrix.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 500$$$) — the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n, m \leq 500$$$) — the size of the matrix. Each of the following $$$n$$$ lines contains a binary string of length $$$m$$$ — the description of the matrix. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases does not exceed $$$1000$$$.

For each test case output the maximum number of operations you can do with the given matrix.

NoteIn the first testcase one of the optimal sequences of operations is the following (bold font shows l-shape figure on which operation was performed):   Matrix before any operation was performed:  101111011110  Matrix after $$$1$$$ operation was performed:  100101011110  Matrix after $$$2$$$ operations were performed:  100100011110  Matrix after $$$3$$$ operations were performed:  100100010110  Matrix after $$$4$$$ operations were performed:  100000010110  Matrix after $$$5$$$ operations were performed:  100000010100  Matrix after $$$6$$$ operations were performed:  100000000100  Matrix after $$$7$$$ operations were performed:  000000000100  Matrix after $$$8$$$ operations were performed:  000000000000 In the third testcase from the sample we can not perform any operation because the matrix doesn't contain any ones.In the fourth testcase it does not matter which L-shape figure we pick in our first operation. We will always be left with single one. So we will perform $$$2$$$ operations.

package main

import (
	"fmt"
	"math"
)

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

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

func solve(m, n int, arr [][]int, nOfOne int) int {
	if nOfOne == 0 {
		return 0
	}
	minn := math.MaxInt
	for i := 0; i < n-1; i++ {
		for j := 0; j < m-1; j++ {
			tmp := arr[i][j] + arr[i+1][j] + arr[i][j+1] + arr[i+1][j+1]
			if tmp == 0 {
				continue
			}
			minn = min(minn, max(1, tmp-1))
		}
	}
	// fmt.Println(minn)
	return 1 + nOfOne - minn
}

func main() {
	t, n, m := 0, 0, 0
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&n, &m)
		input := make([][]int, n)
		for j := 0; j < n; j++ {
			input[j] = make([]int, m)
		}
		numOfOne := 0
		for j := 0; j < n; j++ {
			tmp := ""
			fmt.Scan(&tmp)
			for k, v := range tmp {
				if string(v) == "1" {
					input[j][k] = 1
					numOfOne++
				} else {
					input[j][k] = 0
				}
			}
		}
		fmt.Println(solve(m, n, input, numOfOne))
	}
}

	package main

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

	var in *bufio.Reader = bufio.NewReader(os.Stdin)

	func main() {
		var t int
		fmt.Fscanf(in, "%d\n", &t)
		for t > 0 {
			solve()
			t--
		}
	}
	func solve() {
		var n, m int
		fmt.Fscanf(in, "%d %d\n", &n, &m)
		a := make([][]int, n)
		// 构造矩阵
		for i := range a {
			a[i] = make([]int, m)
		}
		zero := 0
		for i := 0; i < n; i++ {
			var s string
			fmt.Fscanln(in, &s)
			for j := range s {
				a[i][j] = int(s[j] - '0')
				if a[i][j] == 0 {
					zero++
				}
			}
		}
		one := n*m - zero
		if one == 0 {
			fmt.Println(0)
		} else if zero == 0 {
			fmt.Println(1 + one - 3)
		} else {
			flag := false

		out:
			for i := 0; i < n; i++ {
				for j := 0; j < m; j++ {
					if a[i][j] == 0 {
						if (i-1 >= 0 && a[i-1][j] == 0) ||
							(j-1 >= 0 && a[i][j-1] == 0) ||
							(i+1 < n && a[i+1][j] == 0) ||
							(j+1 < m && a[i][j+1] == 0) {
							flag = true
							break out
						}
					}
					if a[i][j] == 1 {
						if (i-1 >= 0 && a[i-1][j] == 0 && (j-1 >= 0 && a[i][j-1] == 0 || j+1 < m && a[i][j+1] == 0)) ||
							(i+1 < n && a[i+1][j] == 0 && (j-1 >= 0 && a[i][j-1] == 0 || j+1 < m && a[i][j+1] == 0)) {
							flag = true
							break out
						}
					}
				}
			}
			if flag {
				fmt.Println(one)
			} else {
				fmt.Println(1 + one - 2)
			}
		}
	}

package main

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

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

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

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

		aa := make([]string, m)
		var c int
		for i := 0; i < m; i++ {
			fmt.Fscan(in, &aa[i])
			for _, ch := range aa[i] {
				if ch == '1' {
					c++
				}
			}
		}

		// fmt.Println(aa)
		val := func(ch byte) int {
			return int(ch - '0')
		}
		d := 5
		for i := 0; i < m-1; i++ {
			for j := 0; j < n-1; j++ {
				d = min(d, val(aa[i][j])+val(aa[i+1][j])+val(aa[i][j+1])+val(aa[i+1][j+1]))
			}
		}
		c -= d
		c += min(2, d)
		fmt.Fprintln(out, c)
	}
}

package main

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

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

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

// func min3(a, b, c int) int {
// 	return min(min(a, b), c)
// }

// func maxSquare(a int) int {
// 	tmp := int(math.Sqrt(float64(a)))
// 	if tmp*tmp == a {
// 		return tmp * tmp
// 	} else {
// 		return (tmp + 1) * (tmp + 1)
// 	}
// }

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var niter int
	fmt.Fscan(in, &niter)
	for iiter := 0; iiter < niter; iiter++ {
		var n, m int
		fmt.Fscan(in, &n, &m)
		table := make([][]rune, n)
		for i := 0; i < n; i++ {
			table[i] = make([]rune, m)
		}
		for i := 0; i < n*m; i++ {
			//fmt.Fscan(in, &table[i/m][i%m])
			b, _, _ := in.ReadRune()
			for b != '0' && b != '1' {
				b, _, _ = in.ReadRune()
			}
			table[i/m][i%m] = b
		}
		ones := 0
		zeroes := 0
		for i := 0; i < n*m; i++ {
			if table[i/m][i%m] == '1' {
				ones++
			} else {
				zeroes++
			}
		}
		mode := 0
		if zeroes > 0 {
			mode = 1
		}
		// check for 2 horizontal, vertical, diagonal (x2)
		for i := 0; i < n-1; i++ {
			for j := 0; j < m; j++ {
				if table[i][j] == table[i+1][j] && table[i][j] == '0' {
					mode = 2
				}
			}
		}
		for i := 0; i < n; i++ {
			for j := 0; j < m-1; j++ {
				if table[i][j] == table[i][j+1] && table[i][j] == '0' {
					mode = 2
				}
			}
		}
		// diag x2
		for i := 0; i < n-1; i++ {
			for j := 0; j < m-1; j++ {
				if table[i][j] == table[i+1][j+1] && table[i][j] == '0' {
					mode = 2
				}
			}
		}
		for i := 1; i < n; i++ {
			for j := 0; j < m-1; j++ {
				if table[i][j] == table[i-1][j+1] && table[i][j] == '0' {
					mode = 2
				}
			}
		}
		if mode == 0 {
			fmt.Fprintln(out, ones-2)
		}
		if mode == 1 {
			fmt.Fprintln(out, ones-1)
		}
		if mode == 2 {
			fmt.Fprintln(out, ones)
		}
	}
}

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	cases := readInt(input)
	for asdf := 0; asdf < cases; asdf++ {
		tmp := readArrInt(input)
		n := tmp[0]
		m := tmp[1]
		lines := [][]rune{}
		for i := 0; i < n; i++ {
			line := readLine(input)
			lines = append(lines, []rune(line))
		}
		fmt.Println(solve(n, m, lines))
	}
}

func solve(n, m int, arr [][]rune) int {
	ones := 0
	zeros := 0
	coupled_zeros := false
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if arr[i][j] == '1' {
				ones++
			} else {
				if coupled_zeros == false {
					sub := 0
					for k := max(0, i-1); k <= min(i+1, n-1); k++ {
						for l := max(0, j-1); l <= min(j+1, m-1); l++ {
							if arr[k][l] == '0' {
								sub++
							}
						}
					}
					if sub > 1 {
						coupled_zeros = true
					}
				}
				zeros++
			}
		}
	}
	if zeros == 0 {
		return ones - 2
	} else if coupled_zeros {
		return ones
	} else {
		return ones - 1
	}
}

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

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

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readInt64(in *bufio.Reader) int64 {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return int64(n)
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readLine(in *bufio.Reader) string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	return line
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

package main

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

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

func slove() {
	var n, m int
	fmt.Fscan(rr, &n, &m)
	g := make([]string, n)
	sum := 0
	for i := range g {
		fmt.Fscan(rr, &g[i])
		for j := range g[i] {
			if g[i][j] == '1' {
				sum++
			}
		}
	}
	flag := false
	for i := range g {
		for j:=0;j<m-1;j++ {
			if g[i][j] == g[i][j+1] && g[i][j] == '0' {
				flag = true
			}
		}
	}
	for i:=0;i<n-1;i++ {
		for j:=0;j<m-1;j++ {
			if g[i][j] == g[i+1][j+1] && g[i][j] == '0' {
				flag = true
			}
		}
	}
	for i:=0;i<n-1;i++ {
		for j:=1;j<m;j++ {
			if g[i][j] == g[i+1][j-1] && g[i][j] == '0' {
				flag = true
			}
		}
	}
	for j := range g[0] {
		for i:=0;i<n-1;i++ {
			if g[i][j] == g[i+1][j] && g[i][j] == '0' {
				flag = true
			}
		}
	}
	has0 := sum != n*m
	if flag {
		fmt.Fprintln(ww, sum)
	} else if has0 {
		fmt.Fprintln(ww, sum-1)
	} else {
		fmt.Fprintln(ww, sum-2)
	}
}

func main() {
	defer ww.Flush()
	var n int
	fmt.Fscan(rr, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}

package main

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

var _, _, _ = main, rw, do

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()
	rw(r, w)
}

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n, m int
		fmt.Fscan(r, &n, &m)
		a := make([]string, n)
		for i := range a {
			fmt.Fscan(r, &a[i])
		}
		w1 := do(n, m, a)
		fmt.Fprintln(w, w1)
	}
}

func do(n, m int, a []string) int {
	c0, c1 := 0, 0
	for _, s := range a {
		for _, c := range s {
			if c == '0' {
				c0++
			} else {
				c1++
			}
		}
	}
	pat := [][]string{
		{"0*", "*0"},
		{"*0", "0*"},
		{"00"},
		{"0", "0"},
	}
	for _, v := range pat {
		ok := search(n, m, a, v)
		if ok {
			return c1
		}
	}
	if c0 > 0 {
		return c1 - 1
	}
	return c1 - 2
}

func search(n, m int, a []string, v []string) bool {
	for i := 0; i+len(v)-1 < n; i++ {
		for j := 0; j+len(v[0])-1 < m; j++ {
			ok := true
			for x := 0; x < len(v); x++ {
				for y := 0; y < len(v[x]); y++ {
					if v[x][y] != '*' && v[x][y] != a[i+x][j+y] {
						ok = false
					}
				}
			}
			if ok {
				return true
			}
		}
	}
	return false
}

package main

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

func Sol(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var t int
	Fscan(in, &t)
	for t > 0 {
		t--
		var n, m int
		Fscan(in, &n, &m)
		a := make([]string, n)
		for i := 0; i < n; i++ {
			Fscan(in, &a[i])
		}
		cnt := 0
		flag1 := false
		flag23 := false
		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				if a[i][j] == '1' {
					cnt++
				}
				x, y := i, j
				cnt0 := 0
				if x - 1 >= 0 && y - 1 >= 0 {
					cnt0 = 0
					if a[x - 1][y - 1] == '0' {
						cnt0++
					}
					if a[x - 1][y] == '0' {
						cnt0++
					}
					if a[x][y - 1] == '0' {
						cnt0++
					}
					if a[x][y] == '0' {
						cnt0++
					}
					if cnt0 >= 2 {
						flag23 = true
					} else if cnt0 == 1 {
						flag1 = true
					}
				}
				if x - 1 >= 0 && y + 1 < m {
					cnt0 = 0
					if a[x - 1][y + 1] == '0' {
						cnt0++
					}
					if a[x - 1][y] == '0' {
						cnt0++
					}
					if a[x][y + 1] == '0' {
						cnt0++
					}
					if a[x][y] == '0' {
						cnt0++
					}
					if cnt0 >= 2 {
						flag23 = true
					} else if cnt0 == 1 {
						flag1 = true
					}
				}
				if x + 1 < n && y - 1 >= 0 {
					cnt0 = 0
					if a[x + 1][y - 1] == '0' {
						cnt0++
					}
					if a[x + 1][y] == '0' {
						cnt0++
					}
					if a[x][y - 1] == '0' {
						cnt0++
					}
					if a[x][y] == '0' {
						cnt0++
					}
					if cnt0 >= 2 {
						flag23 = true
					} else if cnt0 == 1 {
						flag1 = true
					}
				}
				if x + 1 < n && y + 1 < m {
					cnt0 = 0
					if a[x + 1][y + 1] == '0' {
						cnt0++
					}
					if a[x + 1][y] == '0' {
						cnt0++
					}
					if a[x][y + 1] == '0' {
						cnt0++
					}
					if a[x][y] == '0' {
						cnt0++
					}
					if cnt0 >= 2 {
						flag23 = true
					} else if cnt0 == 1 {
						flag1 = true
					}
				}
			}
		}
		if flag23 {
			Fprintln(out, cnt)
		} else if flag1 {
			Fprintln(out, cnt - 1)
		} else {
			Fprintln(out, cnt - 2)
		}
	}
}

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

package main

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

var in *bufio.Reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscanf(in, "%d\n", &t)
	for t > 0 {
		solve()
		t--
	}
}
func solve() {
	var n, m int
	fmt.Fscanf(in, "%d %d\n", &n, &m)
	a := make([][]int, n)
	// 构造矩阵
	for i := range a {
		a[i] = make([]int, m)
	}
	zero := 0
	for i := 0; i < n; i++ {
		var s string
		fmt.Fscanln(in, &s)
		for j := range s {
			a[i][j] = int(s[j] - '0')
			if a[i][j] == 0 {
				zero++
			}
		}
	}
	one := n*m - zero
	if one == 0 {
		fmt.Println(0)
	} else if zero == 0 {
		fmt.Println(1 + one - 3)
	} else {
		flag := false

	out:
		for i := 0; i < n-1; i++ {
			for j := 0; j < m-1; j++ {
				if a[i][j] == 0 && (a[i+1][j] == 0 || a[i][j+1] == 0) {
					flag = true
					break out
				}
			}
		}
		if flag {
			fmt.Println(one)
		} else {
			fmt.Println(1 + one - 2)
		}
	}
}

package main

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

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

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

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

		aa := make([]string, m)
		var c int
		for i := 0; i < m; i++ {
			fmt.Fscan(in, &aa[i])
			for _, ch := range aa[i] {
				if ch == '1' {
					c++
				}
			}
		}

		// fmt.Println(aa)
		val := func(ch byte) int {
			return int(ch - '0')
		}
		d := 5
		d = min(d, val(aa[0][0])+val(aa[0][1])+val(aa[1][0])+val(aa[1][1]))
		d = min(d, val(aa[m-2][0])+val(aa[m-2][1])+val(aa[m-1][0])+val(aa[m-1][1]))
		d = min(d, val(aa[0][n-2])+val(aa[0][n-1])+val(aa[1][n-2])+val(aa[1][n-1]))
		d = min(d, val(aa[m-2][n-2])+val(aa[m-2][n-1])+val(aa[m-1][n-2])+val(aa[m-1][n-1]))

		c -= d
		c += min(2, d)
		fmt.Fprintln(out, c)
	}
}

package main

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

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

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

// func min3(a, b, c int) int {
// 	return min(min(a, b), c)
// }

// func maxSquare(a int) int {
// 	tmp := int(math.Sqrt(float64(a)))
// 	if tmp*tmp == a {
// 		return tmp * tmp
// 	} else {
// 		return (tmp + 1) * (tmp + 1)
// 	}
// }

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var niter int
	fmt.Fscan(in, &niter)
	for iiter := 0; iiter < niter; iiter++ {
		var n, m int
		fmt.Fscan(in, &n, &m)
		table := make([][]rune, n)
		for i := 0; i < n; i++ {
			table[i] = make([]rune, m)
		}
		for i := 0; i < n*m; i++ {
			//fmt.Fscan(in, &table[i/m][i%m])
			b, _, _ := in.ReadRune()
			if b == '\n' {
				b, _, _ = in.ReadRune()
			}
			table[i/m][i%m] = b
		}
		ones := 0
		zeroes := 0
		for i := 0; i < n*m; i++ {
			if table[i/m][i%m] == '1' {
				ones++
			} else {
				zeroes++
			}
		}
		mode := 0
		if zeroes > 0 {
			mode = 1
		}
		// check for 2 horizontal, vertical, diagonal (x2)
		for i := 0; i < n-1; i++ {
			for j := 0; j < m; j++ {
				if table[i][j] == table[i+1][j] && table[i][j] == '0' {
					mode = 2
				}
			}
		}
		for i := 0; i < n; i++ {
			for j := 0; j < m-1; j++ {
				if table[i][j] == table[i][j+1] && table[i][j] == '0' {
					mode = 2
				}
			}
		}
		// diag x2
		for i := 0; i < n-1; i++ {
			for j := 0; j < m-1; j++ {
				if table[i][j] == table[i+1][j+1] && table[i][j] == '0' {
					mode = 2
				}
			}
		}
		for i := 1; i < n; i++ {
			for j := 0; j < m-1; j++ {
				if table[i][j] == table[i-1][j+1] && table[i][j] == '0' {
					mode = 2
				}
			}
		}
		if mode == 0 {
			fmt.Fprintln(out, ones-2)
		}
		if mode == 1 {
			fmt.Fprintln(out, ones-1)
		}
		if mode == 2 {
			fmt.Fprintln(out, ones)
		}
	}
}

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	cases := readInt(input)
	for asdf := 0; asdf < cases; asdf++ {
		tmp := readArrInt(input)
		n := tmp[0]
		m := tmp[1]
		lines := [][]rune{}
		for i := 0; i < n; i++ {
			line := readLine(input)
			lines = append(lines, []rune(line))
		}
		fmt.Println(solve(n, m, lines))
	}
}

func solve(n, m int, arr [][]rune) int {
	ones := 0
	zeros := 0
	coupled_zeros := false
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if arr[i][j] == '1' {
				ones++
			} else {
				if coupled_zeros == false {
					sub := 0
					for k := max(0, i-1); k < min(i+1, n); k++ {
						for l := max(0, j-1); l < min(j+1, m); l++ {
							if arr[k][l] == '0' {
								sub++
							}
						}
					}
					if sub > 1 {
						coupled_zeros = true
					}
				}
				zeros++
			}
		}
	}
	if zeros == 0 {
		return ones - 2
	} else if coupled_zeros {
		return ones
	} else {
		return ones - 1
	}
}

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

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

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readInt64(in *bufio.Reader) int64 {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return int64(n)
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readLine(in *bufio.Reader) string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	return line
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

package main

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

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

func slove() {
	var n, m int
	fmt.Fscan(rr, &n, &m)
	g := make([]string, n)
	sum := 0
	for i := range g {
		fmt.Fscan(rr, &g[i])
		for j := range g[i] {
			if g[i][j] == '1' {
				sum++
			}
		}
	}
	flag := false
	for i := range g {
		for j:=0;j<m-1;j++ {
			if g[i][j] == g[i][j+1] && g[i][j] == '0' {
				flag = true
			}
		}
	}
	for j := range g[0] {
		for i:=0;i<n-1;i++ {
			if g[i][j] == g[i+1][j] && g[i][j] == '0' {
				flag = true
			}
		}
	}
	has0 := sum != n*m
	if flag {
		fmt.Fprintln(ww, sum)
	} else if has0 {
		fmt.Fprintln(ww, sum-1)
	} else {
		fmt.Fprintln(ww, sum-2)
	}
}

func main() {
	defer ww.Flush()
	var n int
	fmt.Fscan(rr, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}


Limak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only.The distance between two letters is defined as the difference between their positions in the alphabet. For example, , and .Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, , and .Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that . Find any s' satisfying the given conditions, or print "-1" if it's impossible to do so.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 106). The second line contains a string s of length n, consisting of lowercase English letters.

If there is no string satisfying the given conditions then print "-1" (without the quotes). Otherwise, print any nice string s' that .

package main

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

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

//Wrong
func main() {
	defer writer.Flush()

	s, _ := reader.ReadString('\n')
	scanner = bufio.NewScanner(strings.NewReader(s))
	scanner.Split(bufio.ScanWords)

	n, k := nextInt(), nextInt()

	s, _ = reader.ReadString('\n')
	s = strings.TrimSpace(s)
	t := make([]uint8, n)

	for i := range t {
		if k == 0 {
			t[i] = s[i]
			continue
		}

		l, r := int(s[i]-'a'), int('z'-s[i])
		// println(l, r, k)
		if k >= l && k >= r {
			if l > r {
				t[i] = 'a'
				k -= l
			} else {
				t[i] = 'z'
				k -= r
			}
		} else {
			if k < r {
				t[i] = s[i] + uint8(k)
			} else if k < l {
				t[i] = s[i] - uint8(k)
			}
			k = 0
		}
	}

	if k > 0 {
		println(-1)
	} else {
		for i := range t {
			printf("%c", t[i])
		}
		println()
	}
}

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

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

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

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

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	line1, _ := in.ReadString('\n')
	var n, k int
	fmt.Sscanf(line1, "%d%d", &n, &k)
	s, _ := in.ReadString('\n')
	for len(s) > 0 && (s[len(s)-1] == '\n' || s[len(s)-1] == '\r') {
		s = s[:len(s)-1]
	}
	s2 := make([]byte, len(s))
	for i := 0; i < len(s); i++ {
		l := s[i] - 'a'
		r := 'z' - s[i]
		d := min(k, max(int(l), int(r)))
		k -= d
		if l > r {
			d = -d
		}
		s2[i] = s[i] + byte(d)
	}
	if k == 0 {
		out.Write(s2)
	} else {
		out.WriteString("-1")
	}
	out.WriteString("\n")
}

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

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

package main

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

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

type writerImpl struct {
	*bufio.Writer
}

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

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

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

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

type wordScannerImpl struct {
	*bufio.Scanner
}

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

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

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

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

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

func main() {
	defer writer.Flush()
	_, k := reader.NextInt64(), reader.NextInt64()
	s := reader.NextString()
	res := []rune{}
	for _, r := range s {
		if k == 0 {
			res = append(res, r)
			continue
		}
		if int64('z' - r) >= k {
			res = append(res, r + rune(k))
			k = 0
			continue
		}
		if int64(r - 'a') >= k {
			res = append(res, r - rune(k))
			k = 0
			continue
		}
		if r - 'a' > 'z' - r {
			res = append(res, 'a')
			k -= int64(r - 'a')
		} else {
			res = append(res, 'z')
			k -= int64('z' - r)
		}
	}
	if k > 0 {
		writer.Printf("-1\n")
	} else {
		writer.Printf("%s\n", string(res))
	}
}

package main

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

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

type writerImpl struct {
	*bufio.Writer
}

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

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

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

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

type wordScannerImpl struct {
	*bufio.Scanner
}

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

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

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

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

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

func main() {
	defer writer.Flush()
	_, k := reader.NextInt64(), reader.NextInt64()
	s := reader.NextString()
	res := []rune{}
	for _, r := range s {
		if k == 0 {
			res = append(res, r)
			continue
		}
		if int64('z' - r) > k {
			res = append(res, r + rune(k))
			k = 0
			continue
		}
		if int64(r - 'a') > k {
			res = append(res, r - rune(k))
			k = 0
			continue
		}
		if r - 'a' > 'z' - r {
			res = append(res, 'a')
			k -= int64(r - 'a')
		} else {
			res = append(res, 'z')
			k -= int64('z' - r)
		}
	}
	if k > 0 {
		writer.Printf("-1\n")
	} else {
		writer.Printf("%s\n", string(res))
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	line1, _ := in.ReadString('\n')
	var n, k int
	fmt.Sscanf(line1, "%d%d", &n, &k)
	s, _ := in.ReadString('\n')
	s = s[:len(s)-1]
	s2 := make([]byte, len(s))
	for i := 0; i < len(s); i++ {
		l := s[i] - 'a'
		r := 'z' - s[i]
		d := min(k, max(int(l), int(r)))
		k -= d
		if l > r {
			d = -d
		}
		s2[i] = s[i] + byte(d)
	}
	if k == 0 {
		out.Write(s2)
	} else {
		out.WriteString("-1")
	}
	out.WriteString("\n")
}

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

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


Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires ad liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.Help Igor find the maximum number he can write on the fence.

The first line contains a positive integer v (0 ≤ v ≤ 106). The second line contains nine positive integers a1, a2, ..., a9 (1 ≤ ai ≤ 105).

Print the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1.

package main

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

func main(){
	var v int
	var a [10]int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	v, _ = strconv.Atoi(r.Text())
	min := 100000
	m := 0
	for i:=1; i<=9; i++ {
		r.Scan()
		a[i], _ = strconv.Atoi(r.Text())
		if a[i] <= min {
			min = a[i]
			m = i
		}
	}
	size := v/min
	v -= min * size
	if size == 0 {
		w.WriteString("-1\n")
		w.Flush()
		return
	}
	for j:=0; j<size; j++ {
		for k:=9; k>=m; k-- {
			if v >= a[k]-a[m] {
				w.WriteString(strconv.Itoa(k))
				v -= a[k]-a[m]
				break
			}
		}
	}
	w.WriteString("\n")
	w.Flush()
}

// 349B
package main

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

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func main() {
	var l, n int
	var a [10]int
	s := 10000000
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Scan(&n)
	for i := 1; i < 10; i++ {
		fmt.Fscan(in, &a[i])
		s = min(s, a[i])
	}
	l = n / s
	if l == 0 {
		fmt.Println(-1)
	}
	for ; l >= 0; l-- {
		for i := 9; i > 0; i-- {
			if (n-a[i])/s == l && n >= a[i] {
				fmt.Fprint(out, i)
				n -= a[i]
				break
			}
		}
	}
	out.Flush()
}

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	v, min := 0, int(1e9)
	a := [10]int{}
	Scan(&v)
	for i := 1; i <= 9; i++ {
		Scan(&a[i])
		if a[i] < min {
			min = a[i]
		}
	}

	l := v / min
	if l == 0 {
		Fprint(out, -1)
		return
	}
	for ; l >= 0; l-- {
		for i := 9; i > 0; i-- {
			if c := a[i]; c <= v && (v-c)/min == l {
				v -= c
				Fprint(out, i)
				break
			}
		}
	}
}

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

type Reader struct{
    scanner *bufio.Scanner
}

func (read *Reader) init(){
    if read.scanner == nil {
        read.scanner = bufio.NewScanner(os.Stdin)
    }
}

func (read *Reader) setWord(){
    read.scanner.Split(bufio.ScanWords)
}

func (read *Reader) setByte(){
    read.scanner.Split(bufio.ScanBytes)
}

func (read *Reader) setLine(){
    read.scanner.Split(bufio.ScanLines)
}

func (read *Reader) read() string{
    read.scanner.Scan()
    return read.scanner.Text()
}

func (read *Reader) readInt() int{
    res,_ := strconv.Atoi(read.read())
    return res
}

func (read *Reader) readByte(length int) string{
    bt := make([]byte, length+2)
    for i := 0; i < length; i++ {
        bt[i] = read.read()[0]
    }

    return string(bt)
}

var read Reader

var writer *bufio.Writer

var cost [9]int
var mem [1000006]int

func f(v int) int{
    if(v <= 0){
        return 0
    }
    if mem[v] > -1{
        return mem[v]
    }
    mx := 0
    for i := 0; i < 9; i++{
        if cost[i] <= v {
            cur := 1 + f(v-cost[i])
            if mx < cur{
                mx = cur
            }
        }
    }
    mem[v] = mx
    return mx
}

func prt(v, len int){
    if len == 0{
        writer.Flush()
        return
    }

    for i := 8; i >= 0; i--{
        if cost[i] <= v{
            if len == 1+f(v-cost[i]){
                fmt.Fprint(writer, i+1)
                prt(v-cost[i], len-1)
                return
            }
        }
    }
}

func main(){

    writer = bufio.NewWriter(os.Stdout)
    read.init()
    read.setWord()

    for i := 0; i <= 1000002; i++{
        mem[i] = -1
    }

    v := read.readInt()
    mn := 1000000
    for i := 0; i < 9; i++ {
        cost[i] = read.readInt()
        if cost[i] < mn {
            mn = cost[i]
        }
    }
    mxLen := v / mn
    // fmt.Println("bal", mxLen, v, f(v))
    if mxLen == 0{
        fmt.Print(-1)
    } else{
        prt(v, mxLen)
    }

}

// 349B
package main

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

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func main() {
	var l, n int
	var a [10]int
	s := 10000000
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Scan(&n)
	for i := 1; i < 10; i++ {
		fmt.Fscan(in, &a[i])
		s = min(s, a[i])
	}
	l = n / s
	if l == 0 {
		fmt.Println(-1)
	}
	for ; l >= 0; l-- {
		for i := 9; i > 0; i-- {
			if (n-a[i])/s == l && n >= a[i] {
				fmt.Fprint(out, i)
				n -= a[i]
				break
			}
		}
	}
}


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z".

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$.

Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$.

NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda".

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	var s string
	fmt.Scan(&s)
	idx := 0
	for i, c := range s {
		if i == len(s)-1 || (i <= len(s)-2 && rune(s[i+1]) < c) {
			idx = i
			break
		}
	}
	fmt.Println(s[:idx] + s[idx+1:])
}

package main

import (
	"fmt"
	"os"
)

func main() {
	var n int
	fmt.Fscan(os.Stdin, &n)
	var s string
	fmt.Fscan(os.Stdin, &s)
	for i := 1; i < len(s); i++ {
		if s[i] < s[i-1] {
			fmt.Printf("%s%s\n", s[:i-1], s[i:])
			return
		}
	}
	fmt.Println(s[:len(s)-1])
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	s := ""
	fmt.Fscanf(in, "%s\n", &s)
	if s[0] > s[1] {
		fmt.Fprintf(out, "%s\n", s[1:])
		return
	}
	for i := 1; i < n; i++ {
		if s[i] < s[i-1] {
			fmt.Fprintf(out, "%s\n", s[:i-1]+s[i:])
			return
		}
	}
	fmt.Fprintf(out, "%s\n", s[:n-1])
	return
}

package main

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

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 300000)
	n, s := 0, ""
	fmt.Fscanf(reader, "%d\n%s\n", &n, &s)
	for i := 0; i < (len(s) - 1); i++ {
		if s[i] > s[i+1] {
			fmt.Println(s[:i] + s[i+1:])
			os.Exit(0)
		}
	}
	fmt.Println(s[:len(s)-1])
}


Dima got into number sequences. Now he's got sequence a1, a2, ..., an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence:  f(0) = 0;  f(2·x) = f(x);  f(2·x + 1) = f(x) + 1. Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤ n) are there, such that f(ai) = f(aj). Help him, count the number of such pairs.

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). The numbers in the lines are separated by single spaces.

In a single line print the answer to the problem. Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample any pair (i, j) will do, so the answer is 3.In the second sample only pair (1, 2) will do.

package main

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

func main() {
    var s [50]int64
    var n,i,sum,u,o int64
    sum=0
    fmt.Scan(&n)
    input:= bufio.NewScanner(os.Stdin)
    input.Split(bufio.ScanWords)

    for i=0;i<n;i++ {
    	input.Scan()
	bb,_:=strconv.ParseInt(input.Text(),0,64)
	u=bb
	o=0
	for u!=1 {
		if u%2!=0 {
			o++
		}
		u/=2
	}
	s[o]++
    }
    for i=0;i<50;i++ {
    	sum+=s[i]*(s[i]-1)/2
    }
    fmt.Println(sum)
}

package main

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

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	n := scanInt(scanner)
	counts := make(map[int]int64)
	for i := 0; i < n; i++ {
		x := scanInt(scanner)
		f := 1
		for x != 1 {
			if x%2 == 1 {
				x--
				f++
			}
			x /= 2
		}
		counts[f]++
	}
	total := int64(0)
	for _, count := range counts {
		total += (count*count - count) / 2
	}
	writer.WriteString(fmt.Sprintf("%d\n", total))
}

package main

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

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	n := scanInt(scanner)
	counts := make(map[int]int64)
	for i := 0; i < n; i++ {
		x := scanInt(scanner)
		f := 1
		for x != 1 {
			f += (x&1)
			x /= 2
		}
		counts[f]++
	}
	total := int64(0)
	for _, count := range counts {
		total += (count*count - count) / 2
	}
	writer.WriteString(fmt.Sprintf("%d\n", total))
}


A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.

The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.

In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.

package main
import (
	"fmt"
)

func main() {
	var input, x int
	x=1
	fmt.Scan(&input)
	for i:=1; i<input; i++ {
		x+=i
		if x>input {
			if x%input==0 {
				fmt.Println(input)
			} else {
				fmt.Println(x%input)
			}
		} else {
			fmt.Println(x)
		}
	}
}

package main

import "fmt"

func main() {
    var n int
    fmt.Scan(&n)
    pos, plus := 0, 1
    for i := 1; i < n; i++ {
        pos = (pos+plus)%n
        fmt.Print(pos+1)
        if i != (n-1) { fmt.Print(" ") } else { fmt.Println() }
        plus++
    }
}

// 46A
package main

import (
	"fmt"
)

func main() {
	var n int
	now := 0
	fmt.Scan(&n)
	for i := 1; i < n; i++ {
		now += i
		now %= n
		fmt.Print(now+1, " ")
	}
}

// 46A-mic_rizal
package main

import (
    "fmt"
)

func main() {
    var n int
    fmt.Scan(&n)
    cou := 1
    for i := 1; i < n; i++ {
        cou = cou + i
        if cou > n {
            cou = cou - n
        }
        fmt.Print(cou)
        fmt.Print(" ")
    }
    fmt.Println()
}

package main
import (
	"fmt"
)

func main() {
	var input, x int
	x=1
	fmt.Scan(&input)
	for i:=1; i<input; i++ {
		x+=i
		if x>input {
			fmt.Println(x%input)
		} else {
			fmt.Println(x)
		}
	}
}


During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.

The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.  Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist. The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.

Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.

NoteThe picture illustrates the queue for the first sample.

package main

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

func main() {
	m1 := make(map[int]int)
	m2 := make(map[int]int)
	var n int
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	n,_ = strconv.Atoi(scanner.Text())
	for i := 0; i < n; i++ {
		scanner.Scan()
		f,_ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		s,_ := strconv.Atoi(scanner.Text())
		m1[f] = s
		m2[s] = f
	}
	arr := make([]int,n)
	h := 0
	for i := 0; i*2+1 < n; i++ {
		arr[i*2+1] = m1[h]
		h = arr[i*2+1]
	}

	//find the head
	deg := make(map[int]int)
	for k,v := range m1{
		deg[k]++
		deg[v]--
	}

	for k,v := range deg{
		if v == 1{
			h = k
			break
		}
	}
	arr[0] = h

	for i:=1; i*2 < n; i++  {
		arr[2*i] = m1[h]
		h = arr[2*i]
	}

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

package main

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

const (
	SIZE = 1000005
)

var (
	n      int
	a      []int
	b      []int
	ids    map[int]struct{}
	m      map[int]int
	first  int
	second int
	last   int
	result int
)

func in() {
	read(&n)
	a = make([]int, n)
	b = make([]int, n)
	m = make(map[int]int)
	ids = make(map[int]struct{})
	for i := 0; i < n; i++ {
		read(&a[i], &b[i])
		m[a[i]] = b[i]
		if a[i] == 0 {
			second = b[i]
		}
		if a[i] != 0 {
			ids[a[i]] = struct{}{}
		}
		if b[i] != 0 {
			ids[b[i]] = struct{}{}
		}
	}
}

func out() {
	defer output.Flush()
}

func run() {
	var count [SIZE]int
	for _, v := range a {
		count[v] = 1
	}
	for _, v := range b {
		count[v] += 2
	}
	for k := range ids {
		if count[k] == 1 {
			first = k
		} else if count[k] == 2 {
			last = k
		}
	}

	for first != last {
		printf("%d ", first)
		first, second = second, m[first]
	}
	println(last)
}

/** main **/
func main() {
	in()
	run()
	out()
}

// Input & Output
var (
	input  = bufio.NewReader(os.Stdin)
	output = bufio.NewWriter(os.Stdout)
)

func read(a ...interface{}) {
	_, err := fmt.Fscan(input, a...)
	if err != nil {
		println(err)
	}
}

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

func printf(format string, a ...interface{}) {
	fmt.Fprintf(output, format, a...)
}

package main

import (
    "fmt"
    "os"
    "bufio"
)
type node struct {
    s, x,c int

}
const MAXN = int(1e6 + 10)

var  data [MAXN]node
var ans ,mark  [MAXN]int

func main(){

   reader := bufio.NewReader(os.Stdin)
   var n,x,y int
   fmt.Fscan(reader,&n)
   for i := 1; i<= n; i ++ {
      var a,b int
      fmt.Fscan(reader,&a,&b)
      data[a].x = b
      data[a].c = 1
      data[b].s = a
      data[b].c = 2
      mark[a] ++
      mark[b] ++
      if 0 ==  b {
        x = a
      }
   }
   for i := 1; i< MAXN;i ++{
        if 1 == mark[i]{
            if 2 == data[i].c {
                y = i
            }

        }

   }
   idex1 := n
   idex2 := n - 1
   for i := 1;i <= n; i ++ {
       if idex1 >= 1 {
           ans[idex1] = y

       }
       if idex2 >= 1 {
           ans[idex2] = x
       }
       idex1 -= 2
       idex2 -= 2
       y = data[y].s
       x = data[x].s

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

}

/*

3
0 2
1 3
2 0
*/

package main

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

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

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

	forwardPos := make(map[int]int)
	backwardPos := make(map[int]int)

	N := ReadInt32()
	position := make([]int, N)
	for i := 0; i < N; i += 1 {
		x, y := ReadInt32(), ReadInt32()
		forwardPos[x] = y
		backwardPos[y] = x
	}

	startId := 0
	startPos := 1
	for {
		if backId, ok := forwardPos[startId]; ok && startPos < N {
			position[startPos] = backId
			startId = backId
			startPos += 2
		} else {
			break
		}
	}
	for fId := range forwardPos {
		if _, ok := backwardPos[fId]; !ok {
			startId = fId
			break
		}
	}
	position[0] = startId
	startPos = 2
	for {
		if backId, ok := forwardPos[startId]; ok && startPos < N {
			position[startPos] = backId
			startId = backId
			startPos += 2
		} else {
			break
		}
	}
	PrintInts(position...)
}

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

func PrintInts(ints ...int) {
	for _, value := range ints {
		writer.WriteString(strconv.Itoa(value))
		writer.WriteByte(' ')
	}
}

package main

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

// import bufio, os, strconv
var sc *bufio.Scanner

func scInit() {
	sc = bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
}

func scanOne() {
	if !sc.Scan() {
		panic("could not scan the reader")
	}
}

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

func nextLong() int64 {
	scanOne()
	i, e := strconv.ParseInt(sc.Text(), 10, 64)
	if e != nil {
		panic(e)
	}
	return i
}

func next() string {
	scanOne()
	return sc.Text()
}

func main() {
	scInit()
	n := nextInt()
	mf, mb := make(map[int]int), make(map[int]int)
	for i := 0; i < n; i++ {
		x, y := nextInt(), nextInt()
		mf[x] = y
		mb[y] = x
	}
	z := make([]int, n)
	for p, i := 0, 1; i < n; i += 2 {
		z[i] = mf[p]
		p = z[i]
	}
	for p, i := 0, n-2; i >= 0; i -= 2 {
		z[i] = mb[p]
		p = z[i]
	}
	if n%2 == 1 {
		v := make(map[int]bool)
		for k := range mb {
			v[k] = true
		}
		var head int
		for k := range mf {
			if !v[k] {
				head = k
				break
			}
		}
		for p, i := head, 0; i < n; i += 2 {
			z[i] = p
			p = mf[p]
		}
	}
	for i := 0; i < n; i++ {
		fmt.Printf("%d", z[i])
		if i < n-1 {
			fmt.Print(" ")
		}
	}
	fmt.Println()
}

package main

import (
    "fmt"
    "os"
    "bufio"
)
type node struct {
    s, x int

}
const MAXN = int(1e6 + 10)

var  data [MAXN]node
var ans [MAXN]int

func main(){

   reader := bufio.NewReader(os.Stdin)
   var n, last ,first int
   fmt.Fscan(reader,&n)
   for i := 1; i<= n; i ++ {
      var a,b int
      fmt.Fscan(reader,&a,&b)
      data[a].x = b
      data[b].s = a
      if 0 ==  b {
        first = a
      }else if 0 == a {

          last = b
      }
   }
   now := 2

   for i := 1;i <= n; i ++ {
        ans[now] = last
        last = data[last].x
        now += 2
        if now > n {
            break
        }

   }
   now = n - 1
   for i := 1;i <=   n; i ++ {

      ans[now] = first
     first = data[first].s
     now -= 2
    if now <= 0{
        break
      }
   }
   for i := 1;i <=  n; i++{
       fmt.Printf("%d ",ans[i])
   }
   fmt.Println()

}

package main

import (
    "fmt"
    "os"
    "bufio"
)
type node struct {
    s, x int

}
const MAXN = int(1e6 + 10)

var  data [MAXN]node
var ans [MAXN]int

func main(){

   reader := bufio.NewReader(os.Stdin)
   var n, last ,first int
   fmt.Fscan(reader,&n)
   for i := 1; i<= n; i ++ {
      var a,b int
      fmt.Fscan(reader,&a,&b)
      data[a].x = b
      data[b].s = a
      if 0 ==  b {
        first = a
      }else if 0 == a {

          last = b
      }
      if 3 == n{
        if 0 != a && 0 != b{
            ans[1] = a
            ans[3] = b
        }else  {
            ans[2] = b
        }

      }
   }
   now := 2

   for i := 1;i <= n; i ++ {
        ans[now] = last
        last = data[last].x
        now += 2
        if now > n {
            break
        }

   }
   now = n - 1
   for i := 1;i <=   n; i ++ {

      ans[now] = first
     first = data[first].s
     now -= 2
    if now <= 0{
        break
      }
   }

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

}

/*

3
0 2
1 3
2 0
*/

package main

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

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

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

	forwardPos := make(map[int]int)
	backwardPos := make(map[int]int)

	N := ReadInt32()
	position := make([]int, N)
	for i := 0; i < N; i += 1 {
		x, y := ReadInt32(), ReadInt32()
		forwardPos[x] = y
		backwardPos[y] = x
	}

	startId := 0
	startPos := -1
	for {
		if backId, ok := forwardPos[startId]; ok && startPos < N {
			position[startPos+2] = backId
			startId = backId
			startPos += 2
		} else {
			break
		}
	}
	startId = 0
	startPos = N
	for {
		if frontId, ok := backwardPos[startId]; ok && startPos >= 0 {
			position[startPos-2] = frontId
			startId = frontId
			startPos -= 2
		} else {
			break
		}
	}
	fmt.Println(position)
}

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

func PrintInts(ints ...int) {
	for _, value := range ints {
		writer.WriteString(strconv.Itoa(value))
		writer.WriteByte(' ')
	}
}

package main

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

// import bufio, os, strconv
var sc *bufio.Scanner

func scInit() {
	sc = bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
}

func scanOne() {
	if !sc.Scan() {
		panic("could not scan the reader")
	}
}

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

func nextLong() int64 {
	scanOne()
	i, e := strconv.ParseInt(sc.Text(), 10, 64)
	if e != nil {
		panic(e)
	}
	return i
}

func next() string {
	scanOne()
	return sc.Text()
}

func main() {
	scInit()
	n := nextInt()
	mf, mb := make(map[int]int), make(map[int]int)
	for i := 0; i < n; i++ {
		x, y := nextInt(), nextInt()
		mf[x] = y
		mb[y] = x
	}
	z := make([]int, n)
	for p, i := 0, 1; i < n; i += 2 {
		z[i] = mf[p]
		p = z[i]
	}
	for p, i := 0, n-2; i >= 0; i -= 2 {
		z[i] = mb[p]
		p = z[i]
	}
	for i := 0; i < n; i++ {
		fmt.Printf("%d", z[i])
		if i < n-1 {
			fmt.Print(" ")
		}
	}
	fmt.Println()
}


You are given a weighted undirected graph on $$$n$$$ vertices along with $$$q$$$ triples $$$(u, v, l)$$$, where in each triple $$$u$$$ and $$$v$$$ are vertices and $$$l$$$ is a positive integer. An edge $$$e$$$ is called useful if there is at least one triple $$$(u, v, l)$$$ and a path (not necessarily simple) with the following properties:  $$$u$$$ and $$$v$$$ are the endpoints of this path,  $$$e$$$ is one of the edges of this path,  the sum of weights of all edges on this path doesn't exceed $$$l$$$. Please print the number of useful edges in this graph.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2\leq n\leq 600$$$, $$$0\leq m\leq \frac{n(n-1)}2$$$).  Each of the following $$$m$$$ lines contains three integers $$$u$$$, $$$v$$$ and $$$w$$$ ($$$1\leq u, v\leq n$$$, $$$u\neq v$$$, $$$1\leq w\leq 10^9$$$), denoting an edge connecting vertices $$$u$$$ and $$$v$$$ and having a weight $$$w$$$. The following line contains the only integer $$$q$$$ ($$$1\leq q\leq \frac{n(n-1)}2$$$) denoting the number of triples. Each of the following $$$q$$$ lines contains three integers $$$u$$$, $$$v$$$ and $$$l$$$ ($$$1\leq u, v\leq n$$$, $$$u\neq v$$$, $$$1\leq l\leq 10^9$$$) denoting a triple $$$(u, v, l)$$$. It's guaranteed that:    the graph doesn't contain loops or multiple edges;  all pairs $$$(u, v)$$$ in the triples are also different.

Print a single integer denoting the number of useful edges in the graph.

NoteIn the first example each edge is useful, except the one of weight $$$5$$$.In the second example only edge between $$$1$$$ and $$$2$$$ is useful, because it belongs to the path $$$1-2$$$, and $$$10 \leq 11$$$. The edge between $$$3$$$ and $$$4$$$, on the other hand, is not useful.In the third example both edges are useful, for there is a path $$$1-2-3-2$$$ of length exactly $$$5$$$. Please note that the path may pass through a vertex more than once.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1483D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}

	var n, m, v, w, wt, q, ans int
	Fscan(in, &n, &m)
	type edge struct{ v, w, wt int }
	es := make([]edge, m)
	d := make([][]int64, n)
	for i := range d {
		d[i] = make([]int64, n)
		for j := range d[i] {
			d[i][j] = 1e18
		}
		d[i][i] = 0
	}
	for i := range es {
		Fscan(in, &v, &w, &wt)
		v--
		w--
		es[i] = edge{v, w, wt}
		d[v][w] = int64(wt)
		d[w][v] = int64(wt)
	}
	for k := range d {
		for i := range d {
			for j := range d {
				d[i][j] = min(d[i][j], d[i][k]+d[k][j])
			}
		}
	}

	upp := make([][]int64, n)
	for i := range upp {
		upp[i] = make([]int64, n)
	}
	for Fscan(in, &q); q > 0; q-- {
		Fscan(in, &v, &w, &wt)
		v--
		w--
		upp[v][w] = int64(wt)
		upp[w][v] = int64(wt)
	}
	// 修改枚举方式，找一侧和另一侧的最大值
	for k := range d {
		for i := range d {
			for j := range d {
				upp[i][k] = max(upp[i][k], upp[i][j]-d[k][j])
				upp[k][j] = max(upp[k][j], upp[i][j]-d[i][k])
			}
		}
	}
	for _, e := range es {
		if int64(e.wt) <= upp[e.v][e.w] {
			ans++
		}
	}
	Fprint(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1483D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, m, v, w, wt, q, ans int
	Fscan(in, &n, &m)
	type edge struct{ v, w, wt int }
	es := make([]edge, m)
	dis := make([][]int, n)
	for i := range dis {
		dis[i] = make([]int, n)
		for j := range dis[i] {
			dis[i][j] = 1e9
		}
		dis[i][i] = 0
	}
	for i := range es {
		Fscan(in, &v, &w, &wt)
		v--
		w--
		es[i] = edge{v, w, wt}
		dis[v][w] = wt
		dis[w][v] = wt
	}
	for k := range dis {
		for i := range dis {
			for j := range dis {
				dis[i][j] = min(dis[i][j], dis[i][k]+dis[k][j])
			}
		}
	}

	g := make([][]int, n)
	for i := range g {
		g[i] = make([]int, n)
	}
	for Fscan(in, &q); q > 0; q-- {
		Fscan(in, &v, &w, &wt)
		v--
		w--
		g[v][w] = wt
		g[w][v] = wt
	}
	for k, dk := range dis {
		for i, di := range dis {
			for j, d := range dk {
				g[i][k] = max(g[i][k], g[i][j]-d)
				g[k][j] = max(g[k][j], g[i][j]-di[k])
			}
		}
	}
	for _, e := range es {
		if e.wt <= g[e.v][e.w] {
			ans++
		}
	}
	Fprint(out, ans)
}

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

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1483D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, m, v, w, wt, q, ans int
	Fscan(in, &n, &m)
	type edge struct{ v, w, wt int }
	es := make([]edge, m)
	dis := make([][]int, n)
	for i := range dis {
		dis[i] = make([]int, n)
		for j := range dis[i] {
			dis[i][j] = 1e9
		}
		dis[i][i] = 0
	}
	for i := range es {
		Fscan(in, &v, &w, &wt)
		v--
		w--
		es[i] = edge{v, w, wt}
		dis[v][w] = wt
		dis[w][v] = wt
	}
	for k := range dis {
		for i := range dis {
			for j := range dis {
				dis[i][j] = min(dis[i][j], dis[i][k]+dis[k][j])
			}
		}
	}

	g := make([][]int, n)
	for i := range g {
		g[i] = make([]int, n)
	}
	for Fscan(in, &q); q > 0; q-- {
		Fscan(in, &v, &w, &wt)
		v--
		w--
		g[v][w] = wt
		g[w][v] = wt
	}
	for k := range dis {
		for i := range dis {
			for j := range dis {
				g[i][k] = max(g[i][k], g[i][j]-dis[k][j])
				g[k][j] = max(g[k][j], g[i][j]-dis[i][k])
			}
		}
	}
	for _, e := range es {
		if e.wt <= g[e.v][e.w] {
			ans++
		}
	}
	Fprint(out, ans)
}

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

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


Consider the infinite sequence $$$s$$$ of positive integers, created by repeating the following steps:  Find the lexicographically smallest triple of positive integers $$$(a, b, c)$$$ such that   $$$a \oplus b \oplus c = 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.  $$$a$$$, $$$b$$$, $$$c$$$ are not in $$$s$$$.  Here triple of integers $$$(a_1, b_1, c_1)$$$ is considered to be lexicographically smaller than triple $$$(a_2, b_2, c_2)$$$ if sequence $$$[a_1, b_1, c_1]$$$ is lexicographically smaller than sequence $$$[a_2, b_2, c_2]$$$.  Append $$$a$$$, $$$b$$$, $$$c$$$ to $$$s$$$ in this order.  Go back to the first step. You have integer $$$n$$$. Find the $$$n$$$-th element of $$$s$$$.You have to answer $$$t$$$ independent test cases.A sequence $$$a$$$ is lexicographically smaller than a sequence $$$b$$$ if in the first position where $$$a$$$ and $$$b$$$ differ, the sequence $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1\le n \le 10^{16}$$$) — the position of the element you want to know.

In each of the $$$t$$$ lines, output the answer to the corresponding test case.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1338C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	mp := [3][4]int64{{0, 1, 2, 3}, {0, 2, 3, 1}, {0, 3, 1, 2}}

	var t, n int64
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		n--
		tp := n % 3
		i := 0
		for n /= 3; 1<<i <= n; i += 2 {
			n -= 1 << i
		}
		tail := int64(0)
		for i := 0; n > 0; n >>= 2 {
			tail |= mp[tp][n&3] << i
			i += 2
		}
		Fprintln(out, int64(1)<<i*(tp+1)|tail)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1338C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	mp := [3][4]int64{{0, 1, 2, 3}, {0, 2, 3, 1}, {0, 3, 1, 2}}

	var t, n int64
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		n--
		tp := n % 3
		n /= 3
		i := 0
		for ; 1<<i <= n; i += 2 {
			n -= 1 << i
		}
		head := int64(1) << i
		if tp == 1 {
			head <<= 1
		} else if tp == 2 {
			head |= head << 1
		}
		tail := int64(0)
		for i := 0; n > 0; n >>= 2 {
			tail |= mp[tp][n&3] << i
			i += 2
		}
		Fprintln(out, head|tail)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1338C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	mp := [3][4]int64{{0, 1, 2, 3}, {0, 2, 3, 1}, {0, 3, 1, 2}}

	var t, n int64
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		n--
		tp := n % 3
		n /= 3
		i := 0
		for ; 1<<i <= n; i += 2 {
			n -= 1 << i
		}
		tail := int64(0)
		for i := 0; n > 0; n >>= 2 {
			tail |= mp[tp][n&3] << i
			i += 2
		}
		Fprintln(out, int64(1)<<i*(tp+1)|tail)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	mp := [3][4]int64{{0, 1, 2, 3}, {0, 2, 3, 1}, {0, 3, 1, 2}}

	var t, n int64
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		n--
		tp := n % 3
		i := 0
		for n /= 3; 1<<i <= n; i += 2 {
			n -= 1 << i
		}
		tail := int64(0)
		for i := 0; n > 0; n >>= 2 {
			tail |= mp[tp][n&3] << i
			i += 2
		}
		Fprintln(out, int64(1)<<i*(tp+1)|tail)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1338C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	mp := [3][4]int64{{0, 1, 2, 3}, {0, 2, 3, 1}, {0, 3, 1, 2}}

	var t, n int64
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		n--
		tp := n % 3
		n /= 3
		sum := int64(0)
		low := int64(1)
		for i := 0; sum+1<<i <= n; i += 2 {
			sum += 1 << i
			low = 1 << (i + 2)
		}
		if tp == 1 {
			low <<= 1
		} else if tp == 2 {
			low |= low << 1
		}
		m := int64(0)
		i := 0
		for n -= sum; n > 0; n >>= 2 {
			m |= mp[tp][n&3] << i
			i += 2
		}
		Fprintln(out, low|m)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1338C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	mp := [3][4]int64{{0, 1, 2, 3}, {0, 2, 3, 1}, {0, 3, 1, 2}}

	var t, n int64
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		n--
		tp := n % 3
		n /= 3
		sum := int64(0)
		low := int64(1)
		for i := 0; sum+1<<i <= n; i += 2 {
			sum += 1 << i
			low = 1 << (i + 2)
		}
		if tp == 1 {
			low <<= 1
		} else if tp == 2 {
			low |= low << 1
		}
		m := int64(0)
		for n -= sum; n > 0; n >>= 2 {
			m = m<<2 | mp[tp][n&3]
		}
		Fprintln(out, low|m)
	}
}

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


The mayor of the Central Town wants to modernize Central Street, represented in this problem by the $$$(Ox)$$$ axis.On this street, there are $$$n$$$ antennas, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th antenna lies on the position $$$x_i$$$ and has an initial scope of $$$s_i$$$: it covers all integer positions inside the interval $$$[x_i - s_i; x_i + s_i]$$$.It is possible to increment the scope of any antenna by $$$1$$$, this operation costs $$$1$$$ coin. We can do this operation as much as we want (multiple times on the same antenna if we want).To modernize the street, we need to make all integer positions from $$$1$$$ to $$$m$$$ inclusive covered by at least one antenna. Note that it is authorized to cover positions outside $$$[1; m]$$$, even if it's not required.What is the minimum amount of coins needed to achieve this modernization?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 80$$$ and $$$n \le m \le 100\ 000$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$s_i$$$ ($$$1 \le x_i \le m$$$ and $$$0 \le s_i \le m$$$). On each position, there is at most one antenna (values $$$x_i$$$ are pairwise distinct).

You have to output a single integer: the minimum amount of coins required to make all integer positions from $$$1$$$ to $$$m$$$ inclusive covered by at least one antenna.

NoteIn the first example, here is a possible strategy:  Increase the scope of the first antenna by $$$40$$$, so that it becomes $$$2 + 40 = 42$$$. This antenna will cover interval $$$[43 - 42; 43 + 42]$$$ which is $$$[1; 85]$$$  Increase the scope of the second antenna by $$$210$$$, so that it becomes $$$4 + 210 = 214$$$. This antenna will cover interval $$$[300 - 214; 300 + 214]$$$, which is $$$[86; 514]$$$  Increase the scope of the third antenna by $$$31$$$, so that it becomes $$$10 + 31 = 41$$$. This antenna will cover interval $$$[554 - 41; 554 + 41]$$$, which is $$$[513; 595]$$$ Total cost is $$$40 + 210 + 31 = 281$$$. We can prove that it's the minimum cost required to make all positions from $$$1$$$ to $$$595$$$ covered by at least one antenna.Note that positions $$$513$$$ and $$$514$$$ are in this solution covered by two different antennas, but it's not important.—In the second example, the first antenna already covers an interval $$$[0; 2]$$$ so we have nothing to do.Note that the only position that we needed to cover was position $$$1$$$; positions $$$0$$$ and $$$2$$$ are covered, but it's not important.

package main

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

type nodes [][]int

func (n nodes) Less(i, j int) bool {
	return n[i][0] < n[j][0]
}

func (n nodes) Swap(i, j int) {
	n[i], n[j] = n[j], n[i]
}

func (n nodes) Len() int {
	return len(n)
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, m := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &m)
	a := nodes([][]int{})
	for i := 0; i < n; i++ {
		p, s := 0, 0
		fmt.Fscanf(in, "%d %d\n", &p, &s)
		a = append(a, []int{p, s})
	}
	sort.Sort(a)
	f := make([][]int, n)
	for i := 0; i < n; i++ {
		f[i] = make([]int, m+1)
	}
	for i := 1; i<= m; i++{
		if i <= a[0][0] + a[0][1] {
			f[0][i] = max(0, a[0][0] - a[0][1] - 1)
		} else {
			f[0][i] = max(0, max(i-a[0][0] - a[0][1], a[0][0] - a[0][1] - 1))
		}
	}
	ans := f[0][m]
	for i := 1; i < n; i++ {
		for j := 1; j <= m; j++ {
			f[i][j] = f[i-1][j]
			if j <= a[i][0] - a[i][1] {
				f[i][j] = min(f[i][j], a[i][0] - a[i][1] - j + f[i-1][j-1])
			} else if j >= a[i][0] - a[i][1] && j <= a[i][0] + a[i][1] {
				f[i][j] = min(f[i][j], f[i-1][max(0,a[i][0]-a[i][1]-1)])
			} else {
				incScope := j - (a[i][0] + a[i][1])
				from := max(0,a[i][0] - a[i][1] - incScope-1)
				f[i][j] = min(f[i][j], f[i-1][from] + incScope)
			}
		}
		if f[i][m] < ans {
			ans = f[i][m]
		}
		//fmt.Println(ans)
	}
	//fmt.Println(f[3][95])
	fmt.Fprintf(out, "%d\n", ans)
	return
}

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

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

package main

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

type nodes [][]int

func (n nodes) Less(i, j int) bool {
	return n[i][0] < n[j][0]
}

func (n nodes) Swap(i, j int) {
	n[i], n[j] = n[j], n[i]
}

func (n nodes) Len() int {
	return len(n)
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, m := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &m)
	a := nodes([][]int{})
	for i := 0; i < n; i++ {
		p, s := 0, 0
		fmt.Fscanf(in, "%d %d\n", &p, &s)
		a = append(a, []int{p, s})
	}
	sort.Sort(a)
	b := make([][]int, 0)
	b = append(b, a[0])
	for i := 1; i < len(a); i++ {
		if a[i][0] + a[i][1] > b[len(b)-1][0] + b[len(b)-1][1] {
			b = append(b, a[i])
		}
	}
	a = b
	n = len(a)
	f := make([][]int, n)
	for i := 0; i < n; i++ {
		f[i] = make([]int, m+1)
	}
	for i := 1; i<= m; i++{
		if i <= a[0][0] + a[0][1] {
			f[0][i] = max(0, a[0][0] - a[0][1] - 1)
		} else {
			f[0][i] = max(0, max(i-a[0][0] - a[0][1], a[0][0] - a[0][1] - 1))
		}
		//if f[0][i] < f[0][i-1] {
		//	fmt.Println(0, i, f[0][i-1], f[0][i])
		//	panic(i)
		//}
	}
	ans := f[0][m]
	for i := 1; i < n; i++ {
		for j := 1; j <= m; j++ {
			f[i][j] = f[i-1][j]
			if j <= a[i][0] - a[i][1] {
				f[i][j] = min(f[i][j], a[i][0] - a[i][1] - j + f[i-1][j-1])
			} else if j >= a[i][0] - a[i][1] && j <= a[i][0] + a[i][1] {
				f[i][j] = min(f[i][j], f[i-1][max(0,a[i][0]-a[i][1]-1)])
			} else {
				incScope := j - (a[i][0] + a[i][1])
				from := max(0,a[i][0] - a[i][1] - incScope-1)
				f[i][j] = min(f[i][j], f[i-1][from] + incScope)
				//fmt.Println("debug incScope", j, incScope)
			}
			//fmt.Println(f[i][j])
			//if f[i][j] < f[i][j-1] {
			//	fmt.Println(i, j, f[i][j-1], f[i][j])
			//	fmt.Println(a[0], a[1])
			//	panic(i)
			//}
		}
		for j := m -1; j >= 1; j-- {
			if f[i][j] > f[i][j+1] {
				f[i][j] = f[i][j+1]
			}
		}
		if f[i][m] < ans {
			ans = f[i][m]
		}
		//fmt.Println(ans)
	}

	//fmt.Println(f[3][95])
	fmt.Fprintf(out, "%d\n", ans)
	return
}

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

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


They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so.Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right.Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid.Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?

The first line of the input contains two integers h and w (1 ≤ h, w ≤ 500) – the number of rows and the number of columns, respectively. The next h lines describe a grid. Each line contains a string of the length w. Each character is either '.' or '#' — denoting an empty or forbidden cell, respectively. The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of queries. Each of the next q lines contains four integers r1i, c1i, r2i, c2i (1 ≤ r1i ≤ r2i ≤ h, 1 ≤ c1i ≤ c2i ≤ w) — the i-th query. Numbers r1i and c1i denote the row and the column (respectively) of the upper left cell of the rectangle. Numbers r2i and c2i denote the row and the column (respectively) of the bottom right cell of the rectangle.

Print q integers, i-th should be equal to the number of ways to put a single domino inside the i-th rectangle.

NoteA red frame below corresponds to the first query of the first sample. A domino can be placed in 4 possible ways.

package main

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

const (
	MAX_HW = 510
)

var H, W int
var Q int
var board [MAX_HW]string

var domino [MAX_HW][MAX_HW][2]int
var dp [MAX_HW][MAX_HW]int
var sumH [MAX_HW][MAX_HW]int
var sumW [MAX_HW][MAX_HW]int

func main() {
	fsc := NewFastScanner()
	H, W = fsc.NextInt(), fsc.NextInt()
	for i := 0; i < H; i++ {
		board[i] = fsc.NextLine()
	}
	for i := 0; i < H; i++ {
		for j := 0; j < W; j++ {
			if board[i][j] == '.' {
				if i-1 >= 0 {
					if board[i-1][j] == '.' {
						domino[i+1][j+1][0] += 1
					}
				}
				if j-1 >= 0 {
					if board[i][j-1] == '.' {
						domino[i+1][j+1][1] += 1
					}
				}
			}
		}
	}
	//sumW
	for j := 1; j <= W; j++ {
		for i := 1; i <= H; i++ {
			sumW[i][j] += sumW[i-1][j] + domino[i][j][1]
		}
	}
	//sumH
	for i := 1; i <= H; i++ {
		for j := 1; j <= W; j++ {
			sumH[i][j] += sumH[i][j-1] + domino[i][j][0]
		}
	}
	for i := 1; i <= H; i++ {
		for j := 1; j <= W; j++ {
			dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + domino[i][j][0] + domino[i][j][1]
		}
	}

	var result []int
	Q = fsc.NextInt()
	for i := 0; i < Q; i++ {
		r1, c1, r2, c2 := fsc.NextInt(), fsc.NextInt(), fsc.NextInt(), fsc.NextInt()
		_, _, _, _ = r1, c1, r2, c2
		// tmp := dp[r2][c2] - dp[r2][c1-1] - dp[r1-1][c2] + dp[r1-1][c1-1]
		a := dp[r2][c2]
		b := dp[r2][c1-1]
		c := dp[r1-1][c2]
		d := dp[r1-1][c1-1]
		tmp := a - b - c + d

		// tmp := 0
		diff := sumW[r2][c1] - sumW[r1-1][c1] + sumH[r1][c2] - sumH[r1][c1-1]
		tmp -= diff
		result = append(result, tmp)
	}
	for _, val := range result {
		fmt.Println(val)
	}
}

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

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

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

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

func Int64Max(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func Float64Max(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

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

func Int64Min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func Float64Min(a, b float64) float64 {
	if a > b {
		return b
	}
	return a
}

package main

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

const (
	MAX_HW = 510
)

var H, W int
var Q int
var board [MAX_HW]string

var domino [MAX_HW][MAX_HW][2]int
var dp [MAX_HW][MAX_HW]int
var sumH [MAX_HW][MAX_HW]int
var sumW [MAX_HW][MAX_HW]int

func main() {
	fsc := NewFastScanner()
	H, W = fsc.NextInt(), fsc.NextInt()
	for i := 0; i < H; i++ {
		board[i] = fsc.NextLine()
	}
	for i := 0; i < H; i++ {
		for j := 0; j < W; j++ {
			if board[i][j] == '.' {
				if i-1 >= 0 {
					if board[i-1][j] == '.' {
						domino[i+1][j+1][0] += 1
					}
				}
				if j-1 >= 0 {
					if board[i][j-1] == '.' {
						domino[i+1][j+1][1] += 1
					}
				}
			}
		}
	}
	//sumW
	for j := 1; j <= W; j++ {
		for i := 1; i <= H; i++ {
			sumW[i][j] += sumW[i-1][j] + domino[i][j][1]
		}
	}
	//sumH
	for i := 1; i <= H; i++ {
		for j := 1; j <= W; j++ {
			sumH[i][j] += sumH[i][j-1] + domino[i][j][0]
		}
	}
	for i := 1; i <= H; i++ {
		for j := 1; j <= W; j++ {
			dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + domino[i][j][0] + domino[i][j][1]
		}
	}

	var result []int
	Q = fsc.NextInt()
	for i := 0; i < Q; i++ {
		r1, c1, r2, c2 := fsc.NextInt(), fsc.NextInt(), fsc.NextInt(), fsc.NextInt()
		_, _, _, _ = r1, c1, r2, c2
		// tmp := dp[r2][c2] - dp[r2][c1-1] - dp[r1-1][c2] + dp[r1-1][c1-1]
		b := dp[r2][c1-1]
		tmp := dp[r2][c2] - b

		// tmp := 0
		diff := sumW[r2][c1] - sumW[r1-1][c1] + sumH[r1][c2] - sumH[r1][c1-1]
		tmp -= diff
		result = append(result, tmp)
	}
	for _, val := range result {
		fmt.Println(val)
	}
}

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

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

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

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

func Int64Max(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func Float64Max(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

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

func Int64Min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func Float64Min(a, b float64) float64 {
	if a > b {
		return b
	}
	return a
}

package main

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

const (
	MAX_HW = 510
)

var H, W int
var Q int
var board [MAX_HW]string

var domino [MAX_HW][MAX_HW][2]int
var dp [MAX_HW][MAX_HW]int
var sumH [MAX_HW][MAX_HW]int
var sumW [MAX_HW][MAX_HW]int

func main() {
	fsc := NewFastScanner()
	H, W = fsc.NextInt(), fsc.NextInt()
	for i := 0; i < H; i++ {
		board[i] = fsc.NextLine()
	}
	for i := 0; i < H; i++ {
		for j := 0; j < W; j++ {
			if board[i][j] == '.' {
				if i-1 >= 0 {
					if board[i-1][j] == '.' {
						domino[i+1][j+1][0] += 1
					}
				}
				if j-1 >= 0 {
					if board[i][j-1] == '.' {
						domino[i+1][j+1][1] += 1
					}
				}
			}
		}
	}
	//sumW
	for j := 1; j <= W; j++ {
		for i := 1; i <= H; i++ {
			sumW[i][j] += sumW[i-1][j] + domino[i][j][1]
		}
	}
	//sumH
	for i := 1; i <= H; i++ {
		for j := 1; j <= W; j++ {
			sumH[i][j] += sumH[i][j-1] + domino[i][j][0]
		}
	}
	for i := 1; i <= H; i++ {
		for j := 1; j <= W; j++ {
			dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + domino[i][j][0] + domino[i][j][1]
		}
	}

	var result []int
	Q = fsc.NextInt()
	for i := 0; i < Q; i++ {
		r1, c1, r2, c2 := fsc.NextInt(), fsc.NextInt(), fsc.NextInt(), fsc.NextInt()
		// tmp := dp[r2][c2] - dp[r2][c1-1] - dp[r1-1][c2] + dp[r1-1][c1-1]
		tmp := 0
		diff := sumW[r2][c1] - sumW[r1-1][c1] + sumH[r1][c2] - sumH[r1][c1-1]
		tmp -= diff
		result = append(result, tmp)
	}
	for _, val := range result {
		fmt.Println(val)
	}
}

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

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

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

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

func Int64Max(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func Float64Max(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

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

func Int64Min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func Float64Min(a, b float64) float64 {
	if a > b {
		return b
	}
	return a
}

package main

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

const (
	MAX_HW = 510
)

var H, W int
var Q int
var board [MAX_HW]string

var domino [MAX_HW][MAX_HW][2]int
var dp [MAX_HW][MAX_HW]int
var sumH [MAX_HW][MAX_HW]int
var sumW [MAX_HW][MAX_HW]int

func main() {
	fsc := NewFastScanner()
	H, W = fsc.NextInt(), fsc.NextInt()
	for i := 0; i < H; i++ {
		board[i] = fsc.NextLine()
	}
	for i := 0; i < H; i++ {
		for j := 0; j < W; j++ {
			if board[i][j] == '.' {
				if i-1 >= 0 {
					if board[i-1][j] == '.' {
						domino[i+1][j+1][0] += 1
					}
				}
				if j-1 >= 0 {
					if board[i][j-1] == '.' {
						domino[i+1][j+1][1] += 1
					}
				}
			}
		}
	}
	//sumW
	for j := 1; j <= W; j++ {
		for i := 1; i <= H; i++ {
			sumW[i][j] += sumW[i-1][j] + domino[i][j][1]
		}
	}
	//sumH
	for i := 1; i <= H; i++ {
		for j := 1; j <= W; j++ {
			sumH[i][j] += sumH[i][j-1] + domino[i][j][0]
		}
	}
	for i := 1; i <= H; i++ {
		for j := 1; j <= W; j++ {
			dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + domino[i][j][0] + domino[i][j][1]
		}
	}

	var result []int
	Q = fsc.NextInt()
	for i := 0; i < Q; i++ {
		r1, c1, r2, c2 := fsc.NextInt(), fsc.NextInt(), fsc.NextInt(), fsc.NextInt()
		_, _, _, _ = r1, c1, r2, c2
		// tmp := dp[r2][c2] - dp[r2][c1-1] - dp[r1-1][c2] + dp[r1-1][c1-1]
		tmp := dp[r2][c2]

		// tmp := 0
		diff := sumW[r2][c1] - sumW[r1-1][c1] + sumH[r1][c2] - sumH[r1][c1-1]
		tmp -= diff
		result = append(result, tmp)
	}
	for _, val := range result {
		fmt.Println(val)
	}
}

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

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

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

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

func Int64Max(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func Float64Max(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

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

func Int64Min(a, b int64) int64 {
	if a > b {
		return b
	}
	return a
}
func Float64Min(a, b float64) float64 {
	if a > b {
		return b
	}
	return a
}