There is a robot staying at $$$X=0$$$ on the $$$Ox$$$ axis. He has to walk to $$$X=n$$$. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.The $$$i$$$-th segment of the path (from $$$X=i-1$$$ to $$$X=i$$$) can be exposed to sunlight or not. The array $$$s$$$ denotes which segments are exposed to sunlight: if segment $$$i$$$ is exposed, then $$$s_i = 1$$$, otherwise $$$s_i = 0$$$.The robot has one battery of capacity $$$b$$$ and one accumulator of capacity $$$a$$$. For each segment, you should choose which type of energy storage robot will use to go to the next point (it can be either battery or accumulator). If the robot goes using the battery, the current charge of the battery is decreased by one (the robot can't use the battery if its charge is zero). And if the robot goes using the accumulator, the current charge of the accumulator is decreased by one (and the robot also can't use the accumulator if its charge is zero).If the current segment is exposed to sunlight and the robot goes through it using the battery, the charge of the accumulator increases by one (of course, its charge can't become higher than it's maximum capacity).If accumulator is used to pass some segment, its charge decreases by 1 no matter if the segment is exposed or not.You understand that it is not always possible to walk to $$$X=n$$$. You want your robot to go as far as possible. Find the maximum number of segments of distance the robot can pass if you control him optimally.

The first line of the input contains three integers $$$n, b, a$$$ ($$$1 \le n, b, a \le 2 \cdot 10^5$$$) — the robot's destination point, the battery capacity and the accumulator capacity, respectively. The second line of the input contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$0 \le s_i \le 1$$$), where $$$s_i$$$ is $$$1$$$ if the $$$i$$$-th segment of distance is exposed to sunlight, and $$$0$$$ otherwise.

Print one integer — the maximum number of segments the robot can pass if you control him optimally.

NoteIn the first example the robot can go through the first segment using the accumulator, and charge levels become $$$b=2$$$ and $$$a=0$$$. The second segment can be passed using the battery, and charge levels become $$$b=1$$$ and $$$a=1$$$. The third segment can be passed using the accumulator, and charge levels become $$$b=1$$$ and $$$a=0$$$. The fourth segment can be passed using the battery, and charge levels become $$$b=0$$$ and $$$a=1$$$. And the fifth segment can be passed using the accumulator.In the second example the robot can go through the maximum number of segments using battery two times and accumulator one time in any order.

package main

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

func main() {
	defer os.Stdout.Sync()
	buf := bufio.NewReader(os.Stdin)
	var n, capa,capb int
	fmt.Fscanf(buf, "%d %d %d\n", &n,&capa,&capb)
	mat := make([]int, n+1)

	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &mat[i+1])
	}
	fmt.Fscanf(buf, "\n")
	a := capa
	b := capb
	for i:= 1;i <= n;i++{
		if mat[i] == 1{
			if b==0||(a > 0&&b < capb){
				a--
				b++
			}else{
				b--
			}
		}else{
			if b > 0{
				b--
			}else{
				a--
			}
		}
		if a==0&&b==0{
			fmt.Printf("%d\n",i)
			return
		}
	}
	fmt.Printf("%d\n",n)

}
/**
20 5 5
1 1 0 0 0 0 1 1 1 0 1 1 0 0 0 1 0 0 0 1
 */

package main

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

func solve(n int, b, a int64, s []bool) int {
	var (
		i int
	)

	bCur, aCur := b, a
	for ; i < n; i++ {
		if aCur <= 0 && bCur <= 0 {
			break
		}

		f := s[i]
		if f && bCur > 0 && aCur < a {
			aCur++
			bCur--
		} else {
			if aCur > 0 {
				aCur--
			} else {
				bCur--
			}
		}

	}

	return i
}

func main() {
	var (
		n    int
		b, a int64
		s    []bool
	)

	fmt.Scan(&n, &b, &a)

	s = make([]bool, n)

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range s {
		scanner.Scan()
		s[i] = '1' == (scanner.Bytes())[0]
	}

	r := solve(n, b, a, s)
	fmt.Println(r)
}

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

package main

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

func Solve(n int, b int, a int, s []int) int {
	segments := 0
	maxCapacity := a
	for _, elem := range s {
		if elem == 1 && b > 0 && a == maxCapacity {
			a -= 1
		} else if elem == 1 && b > 0 {
			a += 1
			b -= 1
		} else if elem == 1 && a > 0 {
			a -= 1
		} else if elem == 0 && a > 0 {
			a -= 1
		} else if elem == 0 && b > 0 {
			b -= 1
		} else {
			break
		}
		segments += 1
	}
	return segments
}

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

	var n, b, a int
	fmt.Fscanf(reader, "%d %d %d\n", &n, &b, &a)
	s := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &s[i])
	}

	fmt.Fprintf(writer, "%d\n", Solve(n, b, a, s))
}

package main

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

func main() {
	defer os.Stdout.Sync()
	buf := bufio.NewReader(os.Stdin)
	var n, capa,capb int
	fmt.Fscanf(buf, "%d %d %d\n", &n,&capa,&capb)
	mat := make([]int, n+1)

	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &mat[i+1])
	}
	fmt.Fscanf(buf, "\n")
	a := capa
	b := capb
	for i:= 1;i <= n;i++{
		if b > 0{
			b--
		}else{
			a--
			if mat[i]==1{
				b++
			}
		}
		if a==0&&b==0{
			fmt.Printf("%d\n",i)
			return
		}
	}
	fmt.Printf("%d\n",n)

}


You are given $$$n$$$ segments on the coordinate axis. The $$$i$$$-th segment is $$$[l_i, r_i]$$$. Let's denote the set of all integer points belonging to the $$$i$$$-th segment as $$$S_i$$$.Let $$$A \cup B$$$ be the union of two sets $$$A$$$ and $$$B$$$, $$$A \cap B$$$ be the intersection of two sets $$$A$$$ and $$$B$$$, and $$$A \oplus B$$$ be the symmetric difference of $$$A$$$ and $$$B$$$ (a set which contains all elements of $$$A$$$ and all elements of $$$B$$$, except for the ones that belong to both sets).Let $$$[\mathbin{op}_1, \mathbin{op}_2, \dots, \mathbin{op}_{n-1}]$$$ be an array where each element is either $$$\cup$$$, $$$\oplus$$$, or $$$\cap$$$. Over all $$$3^{n-1}$$$ ways to choose this array, calculate the sum of the following values:$$$$$$|(((S_1\ \mathbin{op}_1\ S_2)\ \mathbin{op}_2\ S_3)\ \mathbin{op}_3\ S_4)\ \dots\ \mathbin{op}_{n-1}\ S_n|$$$$$$In this expression, $$$|S|$$$ denotes the size of the set $$$S$$$.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$). Then, $$$n$$$ lines follow. The $$$i$$$-th of them contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 3 \cdot 10^5$$$).

Print one integer — the sum of $$$|(((S_1\ \mathbin{op}_1\ S_2)\ \mathbin{op}_2\ S_3)\ \mathbin{op}_3\ S_4)\ \dots\ \mathbin{op}_{n-1}\ S_n|$$$ over all possible ways to choose $$$[\mathbin{op}_1, \mathbin{op}_2, \dots, \mathbin{op}_{n-1}]$$$. Since the answer can be huge, print it modulo $$$998244353$$$.

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

const (
	DEBUG = false
)

func debug(a ...interface{}) {
	if !DEBUG {
		return
	}
	for _, e := range a {
		printf("%v ", e)
	}
	printf("\n")
	writer.Flush()
}

func debugCondn(condn bool, a ...interface{}) {
	if !DEBUG || !condn {
		return
	}
	for _, e := range a {
		printf("%v ", e)
	}
	printf("\n")
	writer.Flush()
}

func assert(condn bool) {
	if !condn {
		panic("assertion error")
	}
}

const N int64 = 3e5 + 10
const mod int64 = 998244353

func Poww(a, b, mod int64) int64 {
	if b == 0 {
		return 1
	}
	if b == 1 {
		return a % mod
	}
	res := Poww(a, b/2, mod)
	res = (res * res) % mod
	if b % 2 == 1 {
		res = (res * (a % mod)) % mod
	}
	return res
}

func solve() {
	var n int64
	scanf("%d\n", &n)

	type Value struct {
		rangeVal, pushVal, pushType int64
	}

	type UpdateValue struct {
		updateType int64
		updateVal int64
	}

	pushLazyValue := func(cur, left, right *SegmentTreeNode[Value]) {
		updateChildValue := func(child *Value) {
			assert(cur.Value.pushVal > 0)
			if cur.Value.pushType == 1 {
				assert(cur.Value.pushVal == cur.Value.rangeVal)
				child.rangeVal = cur.Value.pushVal
				child.pushVal = cur.Value.pushVal
				child.pushType = 1
				return
			}
			assert(cur.Value.pushType == 2)
			if child.pushType == 0 {
				child.rangeVal = (child.rangeVal * cur.Value.pushVal) % mod
				child.pushVal = cur.Value.pushVal
				child.pushType = 2
				return
			}
			if child.pushType == 1 {
				child.rangeVal = (child.rangeVal * cur.Value.pushVal) % mod
				child.pushVal = child.rangeVal
				child.pushType = 1
				return
			}
			assert(child.pushType == 2)
			child.rangeVal = (child.rangeVal * cur.Value.pushVal) % mod
			child.pushVal = (child.pushVal * cur.Value.pushVal) % mod
			child.pushType = 2
		}
		if cur.Value.pushType > 0 {
			updateChildValue(&left.Value)
			updateChildValue(&right.Value)
			cur.Value.pushType = 0
			cur.Value.pushVal = 0
		}
	}

	updateQueryFunc := func(cur *SegmentTreeNode[Value], updateValue any) {
		u := updateValue.(*UpdateValue)
		if u.updateType == 1 {
			debug("u", u.updateType, u.updateVal)
			cur.Value.rangeVal = u.updateVal
			cur.Value.pushVal = u.updateVal
			cur.Value.pushType = 1
			return
		}
		assert(u.updateType == 2)
		if cur.Value.pushType == 0 {
			cur.Value.rangeVal = (cur.Value.rangeVal * 2) % mod
			cur.Value.pushVal = 2
			cur.Value.pushType = 2
			return
		}
		if cur.Value.pushType == 1 {
			cur.Value.rangeVal = (cur.Value.rangeVal * 2) % mod
			cur.Value.pushVal = cur.Value.rangeVal
			cur.Value.pushType = 1
			return
		}
		assert(cur.Value.pushType == 2)
		cur.Value.rangeVal = (cur.Value.rangeVal * 2) % mod
		cur.Value.pushVal = (cur.Value.pushVal * 2) % mod
		cur.Value.pushType = 2
	}

	mergeFunc := func(cur, left, right *SegmentTreeNode[Value]) {
		return
	}

	initValues := make([]Value, N)
	segTree := New(N, initValues, mergeFunc, (*PushFunc[Value])(&pushLazyValue))

	for i:=int64(1); i<=n; i++ {
		var l, r int64
		scanf("%d %d\n", &l, &r)

		if i == 1 {
			segTree.UpdateInterval(l, r, updateQueryFunc, &UpdateValue{updateType: 1, updateVal: 1})
			continue
		}

		segTree.UpdateInterval(l, r,  updateQueryFunc, &UpdateValue{updateType: 1, updateVal: (2 * Poww(3, i-2, mod)) % mod})
		if l-1 >= 0 {
			segTree.UpdateInterval(0, l-1, updateQueryFunc, &UpdateValue{updateType: 2})
		}
		segTree.UpdateInterval(r+1, N-1, updateQueryFunc, &UpdateValue{updateType: 2})
	}

	var res int64 = 0
	for i:=int64(0); i<N; i++ {
		res = res + segTree.QueryPoint(i).rangeVal
		if res >= mod {
			res -= mod
		}
		debugCondn(i <= 10, "i", i, "res", res)
	}
	printf("%v\n", res)
}

func main() {
	defer writer.Flush()

	solve()
}

type SegmentTreeNode[V any] struct {
	id, leftEnd, rightEnd int64
	Value                 V
}

func (stn SegmentTreeNode[V]) GetLeftEnd() int64 {
	return stn.leftEnd
}

func (stn SegmentTreeNode[V]) GetRightEnd() int64 {
	return stn.rightEnd
}

// type ValueType interface {
// 	pushLazyValue(left, right ValueType)
// 	update(updateValue any)
// }

type MergeFunc[V any] func(cur, left, right *SegmentTreeNode[V])

type PushFunc[V any] func(cur, left, right *SegmentTreeNode[V])

type SegmentTree[V any] struct {
	n          	int64
	nodes      	[]*SegmentTreeNode[V]
	mergeFunc 	MergeFunc[V]
	pushFunc 	*PushFunc[V]
}

func New[V any](n int64, initValues []V, mergeFunc MergeFunc[V], pushFunc *PushFunc[V]) *SegmentTree[V] {
	segTree := &SegmentTree[V]{
		n:          n,
		nodes:      make([]*SegmentTreeNode[V], n << 2),
		mergeFunc: 	mergeFunc,
		pushFunc: 	pushFunc,
	}
	segTree.build(1, 0, n-1, initValues)
	return segTree
}

type MergeQueryFunc[V any] func(v1, v2 V) V

func (segTree *SegmentTree[V]) QueryInterval(leftEnd, rightEnd int64, mergeQueryFunc MergeQueryFunc[V], zeroValue V) V {
	return segTree.queryInterval(1, leftEnd, rightEnd, mergeQueryFunc, zeroValue)
}

func (segTree *SegmentTree[V]) QueryPoint(point int64) V {
	return segTree.queryPoint(1, point)
}

type UpdateQueryFunc[V any] func(cur *SegmentTreeNode[V], updateValue any)

func (segTree *SegmentTree[V]) UpdateInterval(leftEnd, rightEnd int64, updateQueryFunc UpdateQueryFunc[V], updateValue any) {
	segTree.updateInterval(1, leftEnd, rightEnd, updateQueryFunc, updateValue)
}

func (segTree *SegmentTree[V]) build(id, leftEnd, rightEnd int64, initValues []V) {
	segTree.nodes[id] = &SegmentTreeNode[V]{
		id:       id,
		leftEnd:  leftEnd,
		rightEnd: rightEnd,
	}
	if leftEnd == rightEnd {
		segTree.nodes[id].Value = initValues[leftEnd]
		return
	}
	mid := leftEnd + (rightEnd - leftEnd) / 2
	segTree.build(id << 1, leftEnd, mid, initValues)
	segTree.build(id << 1 | 1, mid+1, rightEnd, initValues)
	segTree.mergeFunc(segTree.nodes[id], segTree.nodes[id << 1], segTree.nodes[id << 1 | 1])
}

func (segTree *SegmentTree[V]) queryInterval(id, leftEnd, rightEnd int64, mergeQueryFunc MergeQueryFunc[V], zeroValue V) V {
	segTreeNode := segTree.nodes[id]
	if segTreeNode.leftEnd > rightEnd || segTreeNode.rightEnd < leftEnd {
		return zeroValue
	}
	if segTreeNode.leftEnd >= leftEnd && segTreeNode.rightEnd <= rightEnd {
		return segTreeNode.Value
	}
	if segTree.pushFunc != nil {
		(*segTree.pushFunc)(segTreeNode, segTree.nodes[id << 1], segTree.nodes[id << 1 | 1])
	}
	return mergeQueryFunc(segTree.queryInterval(id << 1, leftEnd, rightEnd, mergeQueryFunc, zeroValue),
							segTree.queryInterval(id << 1 | 1, leftEnd, rightEnd, mergeQueryFunc, zeroValue))
}

func (segTree *SegmentTree[V]) queryPoint(id, point int64) V {
	segTreeNode := segTree.nodes[id]
	if segTreeNode.leftEnd == segTreeNode.rightEnd {
		return segTreeNode.Value
	}
	if segTree.pushFunc != nil {
		(*segTree.pushFunc)(segTreeNode, segTree.nodes[id << 1], segTree.nodes[id << 1 | 1])
	}
	mid := segTreeNode.leftEnd + (segTreeNode.rightEnd - segTreeNode.leftEnd) / 2
	if point <= mid {
		return segTree.queryPoint(id << 1, point)
	}
	return segTree.queryPoint(id << 1 | 1, point)
}

func (segTree *SegmentTree[V]) updateInterval(id, leftEnd, rightEnd int64, updateQueryFunc UpdateQueryFunc[V], updateValue any) {
	segTreeNode := segTree.nodes[id]
	if segTreeNode.leftEnd > rightEnd || segTreeNode.rightEnd < leftEnd {
		return
	}
	if segTreeNode.leftEnd >= leftEnd && segTreeNode.rightEnd <= rightEnd {
		updateQueryFunc(segTreeNode, updateValue)
		return
	}
	if segTree.pushFunc != nil {
		(*segTree.pushFunc)(segTreeNode, segTree.nodes[id << 1], segTree.nodes[id << 1 | 1])
	}
	segTree.updateInterval(id << 1, leftEnd, rightEnd, updateQueryFunc, updateValue)
	segTree.updateInterval(id << 1 | 1, leftEnd, rightEnd, updateQueryFunc, updateValue)
	segTree.mergeFunc(segTreeNode, segTree.nodes[id << 1], segTree.nodes[id << 1 | 1])
}


A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $$$k$$$-balanced if every substring of size $$$k$$$ of this bitstring has an equal amount of 0 and 1 characters ($$$\frac{k}{2}$$$ of each).You are given an integer $$$k$$$ and a string $$$s$$$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $$$k$$$-balanced bitstring by replacing every ? characters in $$$s$$$ with either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 3 \cdot 10^5$$$, $$$k$$$ is even)  — the length of the string and the parameter for a balanced bitstring. The next line contains the string $$$s$$$ ($$$|s| = n$$$). It is given that $$$s$$$ consists of only 0, 1, and ?. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print YES if we can replace every ? in $$$s$$$ with 0 or 1 such that the resulting bitstring is $$$k$$$-balanced, or NO if it is not possible.

NoteFor the first test case, the string is already a $$$4$$$-balanced bitstring.For the second test case, the string can be transformed into 101.For the fourth test case, the string can be transformed into 0110.For the fifth test case, the string can be transformed into 1100110.

package main

import "fmt"

const NO_CONSTRAINT = -1

func main() {
    var t int
    fmt.Scanln(&t)
    for ca := 0; ca < t; ca++ {
        var n, k int
		fmt.Scanln(&n, &k)
		var s string
		fmt.Scanln(&s)
		valid := true
		constraints := make([]int, k)
		for i := 0; i < k; i++ {
			constraints[i] = NO_CONSTRAINT
		}
		for i := 0; i < n; i++ {
			if s[i] != '?' {
				c := int(s[i] - '0')
				if constraints[i % k] == NO_CONSTRAINT {
					constraints[i % k] = c
				} else if constraints[i % k] == c {
				} else {
					valid = false
					break
				}
			}
		}
		var cnt [2]int
		for i := 0; i < k; i++ {
			if constraints[i] != NO_CONSTRAINT {
				cnt[constraints[i]]++
			}
		}
		if cnt[0] > k / 2 || cnt[1] > k / 2 {
			valid = false
		}

		if valid {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
    }
}

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 tcases, n, k int
	scanf("%d\n", &tcases)

	for t := 0; t < tcases; t++ {
		scanf("%d %d\n", &n, &k)

		var str string
		scanf("%s\n", &str)

		digits := make([]rune, n, n)
		for i, r := range str {
			digits[i] = r
		}

		counts := map[rune]int{}
		counts['1'] = 0
		counts['0'] = 0
		counts['?'] = 0

		for i := 0; i < k; i++ {
			counts[digits[i]]++
		}

		// printState(digits, counts)

		valid := true
		for i := 0; i < k; i++ {
			for j := i; j < n; j += k {
				if i == j {
					continue
				}
				// printf("-%d %d\n", i, j)
				if digits[j] == '?' {
					continue
				} else {
					if digits[i] == '?' {
						digits[i] = digits[j]
						counts['?']--
						counts[digits[i]]++
					} else {
						if digits[i] != digits[j] {
							valid = false
							break
						}
					}
				}
			}
			if !valid {
				break
			}
		}

		// printState(digits, counts)

		if counts['1'] > k/2 || counts['0'] > k/2 {
			valid = false
		}

		if valid {
			printf("YES\n")
		} else {
			printf("NO\n")
		}
	}
}

func printState(digits []rune, counts map[rune]int) {
	printf("-------\n")
	for i := 0; i < len(digits); i++ {
		printf("%c ", digits[i])
	}
	printf("\n")

	printf("1: %d\n0: %d\n?: %d\n", counts['1'], counts['0'], counts['?'])
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1404A(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T, n, k int
	var s []byte
o:
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k, &s)
		for i, b := range s[k:] {
			if b != '?' {
				if s[i%k] == '?' {
					s[i%k] = b
				} else if s[i%k] != b {
					Fprintln(out, "NO")
					continue o
				}
			}
		}
		if bytes.Count(s[:k], []byte{'0'}) > k/2 || bytes.Count(s[:k], []byte{'1'}) > k/2 {
			Fprintln(out, "NO")
		} else {
			Fprintln(out, "YES")
		}
	}
}

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

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 tcases, n, k int
	scanf("%d\n", &tcases)

	for t := 0; t < tcases; t++ {
		scanf("%d %d\n", &n, &k)

		var str string
		scanf("%s\n", &str)

		digits := make([]rune, n, n)
		for i, r := range str {
			digits[i] = r
		}

		counts := map[rune]int{}
		counts['1'] = 0
		counts['0'] = 0
		counts['?'] = 0

		for i := 0; i < k; i++ {
			counts[digits[i]]++
		}

		// printState(digits, counts)

		for i := 0; i < k; i++ {
			assignDigit(digits, counts, i, k)
		}

		// printState(digits, counts)

		valid := true
		for l, r := 0, k; r <= n; l, r = l+1, r+1 {
			if l > 0 {
				counts[digits[l-1]]--
			}

			assignDigit(digits, counts, r-1, k)
			if counts['?'] > 0 {
				panic("unhandled ?")
			}

			if counts['1'] > k/2 || counts['0'] > k/2 {
				// printf("BREAKING")
				// printState(digits, counts)
				valid = false
				break
			}

			if r < n {
				counts[digits[r]]++
			}
		}

		if valid {
			printf("YES\n")
		} else {
			printf("NO\n")
		}
	}
}

func assignDigit(digits []rune, counts map[rune]int, i int, k int) {
	if digits[i] != '?' {
		return
	}
	if counts['1'] < k/2 {
		digits[i] = '1'
		counts['1']++
	} else if counts['0'] < k/2 {
		digits[i] = '0'
		counts['0']++
	} else {
		panic("this should never happen!")
	}

	counts['?']--
}

func printState(digits []rune, counts map[rune]int) {
	printf("-------\n")
	for i := 0; i < len(digits); i++ {
		printf("%c ", digits[i])
	}
	printf("\n")

	printf("1: %d\n0: %d\n?: %d\n", counts['1'], counts['0'], counts['?'])
}


Alice, the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of $$$p$$$ players playing in $$$p$$$ different positions. She also recognizes the importance of audience support, so she wants to select $$$k$$$ people as part of the audience.There are $$$n$$$ people in Byteland. Alice needs to select exactly $$$p$$$ players, one for each position, and exactly $$$k$$$ members of the audience from this pool of $$$n$$$ people. Her ultimate goal is to maximize the total strength of the club.The $$$i$$$-th of the $$$n$$$ persons has an integer $$$a_{i}$$$ associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person $$$i$$$ and for each position $$$j$$$, Alice knows $$$s_{i, j}$$$  — the strength added by the $$$i$$$-th person to the club if he is selected to play in the $$$j$$$-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.

The first line contains $$$3$$$ integers $$$n,p,k$$$ ($$$2 \leq n \leq 10^{5}, 1 \leq p \leq 7, 1 \le k, p+k \le n$$$). The second line contains $$$n$$$ integers $$$a_{1},a_{2},\ldots,a_{n}$$$. ($$$1 \leq a_{i} \leq 10^{9}$$$). The $$$i$$$-th of the next $$$n$$$ lines contains $$$p$$$ integers $$$s_{i, 1}, s_{i, 2}, \dots, s_{i, p}$$$. ($$$1 \leq s_{i,j} \leq 10^{9}$$$)

Print a single integer $$${res}$$$  — the maximum possible strength of the club.

NoteIn the first sample, we can select person $$$1$$$ to play in the $$$1$$$-st position and persons $$$2$$$ and $$$3$$$ as audience members. Then the total strength of the club will be equal to $$$a_{2}+a_{3}+s_{1,1}$$$.

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1010)

	n := NextInt()
	p := NextInt()
	k := NextInt()
	a := make([]int, n)
	perm := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = NextInt()
		perm[i] = i
	}
	s := make([][]int, n)
	var dp [2][][2]int64
	MAX_MASK := (1 << uint(p))
	dp[0] = make([][2]int64, MAX_MASK)
	dp[1] = make([][2]int64, MAX_MASK)
	for i := 0; i < n; i++ {
		s[i] = make([]int, p)
		for j := 0; j < p; j++ {
			s[i][j] = NextInt()
		}
	}
	sort.Slice(perm, func(i, j int) bool {
		return a[perm[i]] > a[perm[j]]
	})

	for i := 0; i < MAX_MASK; i++ {
		dp[1][i][0] = -int64(1000000000) * int64(100000000)
	}
	dp[1][0][0] = 0
	var res int64
	for i := 0; i < n; i++ {
		ind := i & 1
		pind := ind ^ 1
		for mask := 0; mask < MAX_MASK; mask++ {
			curr := dp[pind][mask][0]
			count := dp[pind][mask][1]
			if int(count) < k {
				count++
				curr += int64(a[perm[i]])
			}
			dp[ind][mask][0] = curr
			dp[ind][mask][1] = count
			for j := 0; j < p; j++ {
				if mask&(1<<uint(j)) == 0 {
					continue
				}
				nmask := mask & ^(1 << uint(j))
				curr := dp[pind][nmask][0]
				count := dp[pind][nmask][1]
				if dp[ind][mask][0] < curr+int64(s[perm[i]][j]) {
					dp[ind][mask][0] = curr + int64(s[perm[i]][j])
					dp[ind][mask][1] = count
				}
			}
			// fmt.Fprintf(os.Stderr, "%d %b = %d, %d\n", i, mask, dp[ind][mask][0], dp[ind][mask][1])
		}
		if dp[ind][MAX_MASK-1][0] > res {
			res = dp[ind][MAX_MASK-1][0]
		}
	}
	fmt.Fprintln(out, res)
}

package main

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

var dp [1 << 7]int64
var id []int
var a [100005]int
var s [100005][7]int

func main() {
	n := ReadInt()
	p := ReadInt()
	k := ReadInt()
	for i := 0; i < n; i++ {
		a[i] = ReadInt()
		id = append(id, i);
	}
	for i := 0; i < n; i++ {
		for j := 0; j < p; j++ {
			s[i][j] = ReadInt()
		}
	}
	sort.Slice(id,  func(i, j int) bool {
		return a[id[i]] > a[id[j]]
	})
	for i := 0; i < (1 << 7); i++ {
		dp[i] = -1
	}
	dp[0] = 0
	for i := 0; i < n; i++ {
		for j := (1 << uint(p)) - 1; j >= 0; j-- {
			var cnt int = 0
			for m := 0; m < p; m++ {
				if ((uint(j) >> uint(m)) & 1) != 0 {
					cnt++;
				}
			}
			cnt = i - cnt
			if cnt < k && dp[j] != -1 {
				dp[j] += int64(a[id[i]])
			}
			for m := 0; m < p; m++ {
				if ((uint(j) >> uint(m)) & 1) != 0 {
					if dp[j^(1<<uint(m))] != -1 {
						dp[j] = max(dp[j], dp[j^(1<<uint(m))]+int64(s[id[i]][m]))
					}
				}
			}
		}
	}
	fmt.Println(dp[(1<<uint(p))-1])
}

////////////////////////////////////

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

var out chan string
var in *bufio.Scanner
var outWg *sync.WaitGroup

func ReadString() string {
	in.Scan()
	return in.Text()
}
func ReadStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ReadString()
	}
	return s
}
func ReadInt() int {
	intStr := ReadString()
	i, _ := strconv.ParseInt(intStr, 10, 32)
	return int(i)
}
func ReadIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ReadInt()
	}
	return arr
}
func init() {
	//set input
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(2e+5))
	in.Split(bufio.ScanWords)

	//set output
	out = make(chan string, 16)
	outWg = &sync.WaitGroup{}
	outWg.Add(1)

	writer := bufio.NewWriterSize(os.Stdout, int(2e+5))
	go func(write *bufio.Writer) {
		defer outWg.Done()
		defer write.Flush()

		for line := range out {
			write.WriteString(line + "\n")
		}
	}(writer)
}

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

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

type Network struct {
	n     int
	m     int
	edges int
	fst   []int
	nxt   []int
	end   []int
	cost  []int
	cap   []int
}

func (g *Network) Add(a, b, cap, cost int) {
	g.nxt[g.edges] = g.fst[a]
	g.fst[a] = g.edges
	g.end[g.edges] = b
	g.cap[g.edges] = cap
	g.cost[g.edges] = cost
	g.edges++
	g.nxt[g.edges] = g.fst[b]
	g.fst[b] = g.edges
	g.end[g.edges] = a
	g.cap[g.edges] = 0
	g.cost[g.edges] = -cost
	g.edges++
}

func (g *Network) Adjacent(a int, fn func(u int)) {
	for u := g.fst[a]; u != -1; u = g.nxt[u] {
		fn(u)
	}
}

func (g *Network) MainEdges(fn func(u int)) {
	for u := 0; u < g.edges; u += 2 {
		fn(u)
	}
}

func (g *Network) inf() int64 {
	return int64(20000000000)
}

func (g *Network) updatePotentials(d, phi []int64) {
	for i := 0; i < g.n; i++ {
		phi[i] += d[i]
	}
}

func (g *Network) relax(s, t int, p []int) (int, int64) {
	minCapacity := 0
	var pathCost int64

	for v, step := t, 0; v != s; step++ {
		u := p[v]
		if step == 0 || minCapacity > g.cap[u] {
			minCapacity = g.cap[u]
		}
		v = g.end[u^1]
	}

	for v := t; v != s; {
		u := p[v]
		g.cap[u] -= minCapacity
		g.cap[u^1] += minCapacity
		pathCost += int64(minCapacity) * int64(g.cost[u])
		v = g.end[u^1]
	}
	return minCapacity, pathCost
}

func (g *Network) afterPhase(s, t int, d []int64, p []int, phi []int64) (int, int64) {
	if d[t] == g.inf() {
		return 0, 0
	}
	g.updatePotentials(d, phi)

	return g.relax(s, t, p)
}

func (g *Network) levit(s, t int, d []int64, id []int, p []int, q []int) {
	for i := 0; i < g.n; i++ {
		d[i] = g.inf()
	}
	qh, qt := 0, 0
	d[s] = 0
	q[qt] = s
	qt++
	for qh != qt {
		v := q[qh]
		qh++
		if qh == g.n {
			qh = 0
		}
		// stderr("going to ver", d[v])
		id[v] = 2
		for u := g.fst[v]; u != -1; u = g.nxt[u] {
			to := g.end[u]
			cost := int64(g.cost[u])
			if g.cap[u] > 0 && d[to] > d[v]+cost {
				d[to] = d[v] + cost
				if id[to] == 0 {
					q[qt] = to
					qt++
					if qt == g.n {
						qt = 0
					}
				} else if id[to] == 2 {
					qh--
					if qh == -1 {
						qh = g.n - 1
					}
					q[qh] = to
				}
				id[to] = 1
				p[to] = u
			}
		}
	}
}

func (g *Network) dijkstra(s, t int, d, phi []int64, p []int, heap *Heap) {
	// stderr("dijkstra")
	var mPhi int64
	for i := 0; i < g.n; i++ {
		d[i] = g.inf()
		if i == 0 || mPhi < phi[i] {
			mPhi = phi[i]
		}
	}
	// stderr("maxPhi", mPhi)
	d[s] = 0
	heap.Clear()
	heap.Add(s)

	for heap.Size() > 0 {
		// stderr("heap size", heap.Size())
		v := heap.Pop()
		if d[v] >= g.inf() {
			// stderr("weird")
			continue
		}

		g.Adjacent(v, func(u int) {
			to := g.end[u]
			cost := int64(g.cost[u])
			if g.cap[u] > 0 && cost+phi[v]-phi[to] < 0 {
				// stderr("negative edge", v, to, s, t, cost, phi[v], phi[to], phi[v]-phi[to])
				panic("negative edge")
			}
			if g.cap[u] > 0 && d[to] > d[v]+cost+phi[v]-phi[to] {
				d[to] = d[v] + cost + phi[v] - phi[to]
				heap.Update(to)
				p[to] = u
			}
		})
	}
}

type HeapComparator func(i, j int) bool

type Heap struct {
	n    int
	a    []int
	ind  []int
	less HeapComparator
}

func (t *Heap) Add(key int) {
	if t.n == len(t.a) {
		panic("Preset bigger heap size")
	}
	t.a[t.n] = key
	t.ind[key] = t.n
	t.n++
	t.pushUp(t.n - 1)
}

func (t *Heap) Remove(key int) {
	ind := t.ind[key]
	if ind == -1 {
		return
	}
	t.swap(ind, t.n-1)
	t.n--
	t.ind[key] = -1
	t.pushDown(ind)
	t.pushUp(ind)
}

func (t *Heap) Size() int {
	return t.n
}

func (t *Heap) Clear() {
	for i := 0; i < t.n; i++ {
		t.ind[t.a[i]] = -1
	}
	t.n = 0
}

func (t *Heap) pushUp(i int) {
	for i > 0 && i < t.n {
		upper := (i - 1) >> 1
		if t.less(t.a[upper], t.a[i]) {
			return
		}
		t.swap(upper, i)
		i = upper
	}
}

func (t *Heap) swap(i, j int) {
	t.a[i], t.a[j] = t.a[j], t.a[i]
	t.ind[t.a[i]] = i
	t.ind[t.a[j]] = j
}

func (t *Heap) print(out io.Writer) {
	fmt.Fprintln(out, t.a[:t.n])
}

func (t *Heap) pushDown(i int) {
	for i < t.n {
		left, right := i*2+1, i*2+2
		tt := i
		if left < t.n && t.less(t.a[left], t.a[i]) {
			tt = left
		}
		if right < t.n && t.less(t.a[right], t.a[tt]) {
			tt = right
		}
		if tt == i {
			break
		}
		t.swap(i, tt)
		i = tt
	}
}

func (t *Heap) Update(key int) {
	i := t.ind[key]
	if i == -1 {
		t.Add(key)
	} else {
		if t.a[i] != key {
			panic("heap is corrupted, the existed key heap position is incorrect")
		}
		t.pushDown(i)
		t.pushUp(i)
	}
}

func (t *Heap) Top() int {
	if t.n == 0 {
		panic("no more elements in Heap")
	}
	return t.a[0]
}

func (t *Heap) Pop() int {
	if t.n == 0 {
		panic("no more elements in Heap")
	}
	key := t.a[0]
	t.swap(0, t.n-1)
	t.n--
	t.ind[key] = -1
	t.pushDown(0)
	return key
}

func NewHeap(cap int, less HeapComparator) *Heap {
	a := make([]int, cap)
	ind := make([]int, cap)
	for i := 0; i < cap; i++ {
		ind[i] = -1
	}
	return &Heap{0, a, ind, less}
}

func (g *Network) MinCostMaxFlow(s, t int) (int, int64) {
	d := make([]int64, g.n)
	p := make([]int, g.n)
	phi := make([]int64, g.n)
	id := make([]int, g.n)
	q := make([]int, g.n)

	var maxFlow int
	var minCost int64

	heap := NewHeap(g.n, func(i, j int) bool {
		return d[i] < d[j] || d[i] == d[j] && i < j
	})

	g.levit(s, t, d, id, p, q)
	// stderr("first max flow")
	flow, cost := g.afterPhase(s, t, d, p, phi)

	for maxFlow, minCost = flow, cost; flow != 0; maxFlow, minCost = maxFlow+flow, minCost+cost {
		// stderr("flow and cost are", flow, cost)
		//s, t int, d, phi []int64, p []int, heap *Heap
		// g.levit(s, t, d, id, p, q)
		g.dijkstra(s, t, d, phi, p, heap)
		flow, cost = g.afterPhase(s, t, d, p, phi)
	}
	return maxFlow, minCost
}

func NewNetwork(n, m int) *Network {
	g := &Network{n, m, 0, make([]int, n), make([]int, m), make([]int, m), make([]int, m), make([]int, m)}
	for i := 0; i < n; i++ {
		g.fst[i] = -1
	}
	return g
}

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1010)

	n := NextInt()
	p := NextInt()
	k := NextInt()
	s := 0
	s1 := s + 1
	t := 1 + 1 + n + p
	g := NewNetwork(t+1, (1+n+n*p+n+p)*2)
	g.Add(s, s1, p+k, 0)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = NextInt()
		g.Add(s1, s1+1+i, 1, 0)
	}

	for i := 0; i < n; i++ {
		for j := 0; j < p; j++ {
			sij := NextInt()
			g.Add(s1+1+i, s1+1+n+j, 1, -(sij - a[i]))
		}
	}
	// var T int64
	for i := 0; i < p; i++ {
		g.Add(s1+1+n+i, t, 1, 0)
	}

	flow, cost := g.MinCostMaxFlow(s, t)
	stderr("flow", flow, "cost", cost)

	used := make([]bool, n)
	var result int64

	g.MainEdges(func(u int) {
		from := g.end[u^1]
		to := g.end[u]
		if from >= s1+1 && from <= s1+n &&
			to >= s1+n+1 && to <= s1+n+p && g.cap[u] == 0 {
			used[from-s1-1] = true
			result += int64(-g.cost[u]) + int64(a[from-s1-1])
		}
	})

	newLen := 0
	for i := 0; i < n; i++ {
		if !used[i] {
			a[newLen] = a[i]
			newLen++
		}
	}
	a = a[:newLen]
	n = newLen
	sort.Ints(a)
	for i := 0; i < k; i++ {
		result += int64(a[n-i-1])
	}

	fmt.Fprintln(out, result)
}

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1010)

	n := NextInt()
	p := NextInt()
	k := NextInt()
	a := make([]int, n)
	perm := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = NextInt()
		perm[i] = i
	}
	s := make([][]int, n)
	var dp [2][][2]int
	MAX_MASK := (1 << uint(p))
	dp[0] = make([][2]int, MAX_MASK)
	dp[1] = make([][2]int, MAX_MASK)
	for i := 0; i < n; i++ {
		s[i] = make([]int, p)
		for j := 0; j < p; j++ {
			s[i][j] = NextInt()
		}
	}
	sort.Slice(perm, func(i, j int) bool {
		return a[perm[i]] > a[perm[j]]
	})

	var res int
	for i := 0; i < n; i++ {
		ind := i & 1
		pind := ind ^ 1
		for mask := 0; mask < MAX_MASK; mask++ {
			curr := dp[pind][mask][0]
			count := dp[pind][mask][1]
			if count < k {
				count++
				curr += a[perm[i]]
			}
			dp[ind][mask][0] = curr
			dp[ind][mask][1] = count
			for j := 0; j < p; j++ {
				if mask&(1<<uint(j)) == 0 {
					continue
				}
				nmask := mask & ^(1 << uint(j))
				curr := dp[pind][nmask][0]
				count := dp[pind][nmask][1]
				if dp[ind][mask][0] < curr+s[perm[i]][j] {
					dp[ind][mask][0] = curr + s[perm[i]][j]
					dp[ind][mask][1] = count
				}
			}
			// fmt.Fprintf(os.Stderr, "%d %b = %d, %d\n", i, mask, dp[ind][mask][0], dp[ind][mask][1])
		}
		if dp[ind][MAX_MASK-1][0] > res {
			res = dp[ind][MAX_MASK-1][0]
		}
	}
	fmt.Fprintln(out, res)
}

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1010)

	n := NextInt()
	p := NextInt()
	k := NextInt()
	a := make([]int, n)
	perm := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = NextInt()
		perm[i] = i
	}
	s := make([][]int, n)
	var dp [2][][2]int64
	MAX_MASK := (1 << uint(p))
	dp[0] = make([][2]int64, MAX_MASK)
	dp[1] = make([][2]int64, MAX_MASK)
	for i := 0; i < n; i++ {
		s[i] = make([]int, p)
		for j := 0; j < p; j++ {
			s[i][j] = NextInt()
		}
	}
	sort.Slice(perm, func(i, j int) bool {
		return a[perm[i]] > a[perm[j]]
	})

	var res int64
	for i := 0; i < n; i++ {
		ind := i & 1
		pind := ind ^ 1
		for mask := 0; mask < MAX_MASK; mask++ {
			curr := dp[pind][mask][0]
			count := dp[pind][mask][1]
			if int(count) < k {
				count++
				curr += int64(a[perm[i]])
			}
			dp[ind][mask][0] = curr
			dp[ind][mask][1] = count
			for j := 0; j < p; j++ {
				if mask&(1<<uint(j)) == 0 {
					continue
				}
				nmask := mask & ^(1 << uint(j))
				curr := dp[pind][nmask][0]
				count := dp[pind][nmask][1]
				if dp[ind][mask][0] < curr+int64(s[perm[i]][j]) {
					dp[ind][mask][0] = curr + int64(s[perm[i]][j])
					dp[ind][mask][1] = count
				}
			}
			// fmt.Fprintf(os.Stderr, "%d %b = %d, %d\n", i, mask, dp[ind][mask][0], dp[ind][mask][1])
		}
		if dp[ind][MAX_MASK-1][0] > res {
			res = dp[ind][MAX_MASK-1][0]
		}
	}
	fmt.Fprintln(out, res)
}


There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one.  At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints.

The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists.

Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them.

NoteThe first test sample is the one in the picture.

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var s string
	var n,i int
	fmt.Scan(&n)
	fmt.Fscan(reader,&s)
	for i=0;s[i]=='.';i++ {}
	fmt.Print(i+1," ")
	for ;i<n;i++ {
		if s[i]!='R' {
			break
		}
	}
	if s[i]=='L' {
		fmt.Print(i)
	} else {
		fmt.Print(i+1)
	}
}

package main

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

var scanner *bufio.Scanner

func getI() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

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

  getI()
  road := getS()
  var a, b int
  r, l := strings.IndexByte(road, 'R'), strings.IndexByte(road, 'L')
  if r == -1 {
    a = strings.LastIndex(road, "L")
    b = l-1
  } else {
    a = r
    if l == -1 {
      b = strings.LastIndex(road, "R")+1
    } else {
      b = l-1
    }
  }
  writer.WriteString(fmt.Sprintf("%d %d\n", a+1, b+1))
}

package main

import "fmt"

func main() {
    var n int
    var r string
    fmt.Scan(&n)
    fmt.Scan(&r)
    s, t := -1, -1
    for i := 0; i < len(r); i++ {
        if r[i] == 'R' {
            s, t = i, i
            for ; r[t] == 'R'; t++ {}
            if r[t] == 'L' { t-- }
            break
        } else if r[i] == 'L' {
            s, t = i, i-1
            for ; r[s] == 'L'; s++ {}
            s--
            break
        }
    }
    fmt.Println(s+1,t+1)
}

package main

import "fmt"

func main() {
    var n int
    var r string
    fmt.Scan(&n)
    fmt.Scan(&r)
    s, t := -1, -1
    for k, v := range r {
        if v == 'R' {
            if s == -1 { s = k+1 }
        } else if v == 'L' {
            t = k-1
        } else if v == '.' {
            t = k
        }
    }
    fmt.Println(s,t)
}

package main

import "fmt"

func main() {
    var n int
    var r string
    fmt.Scan(&n)
    fmt.Scan(&r)
    s, t := -1, -1
    for k, v := range r {
        if v == 'R' {
            if s == -1 { s = k+1 }
        } else if v == 'L' {
            t = k-1
        } else if (v == '.') && (s != -1) {
            t = k
            break
        }
    }
    fmt.Println(s,t)
}

package main

import "fmt"

func main() {
    var n int
    var r string
    fmt.Scan(&n)
    fmt.Scan(&r)
    s, t := -1, -1
    for k, v := range r {
        if v == 'R' {
            if s == -1 { s = k+1 }
        } else if v == 'L' {
            t = k-1
        } else if v == '.' {
            t = k
            break
        }
    }
    fmt.Println(s,t)
}

package main

import "fmt"

func main() {
    var n int
    var r string
    fmt.Scan(&n)
    fmt.Scan(&r)
    s, t := -1, -1
    for k, v := range r {
        if v == 'R' {
            if s == -1 { s = k+1 }
            t = k+1
        }
    }
    fmt.Println(s,t)
}

package main

import "fmt"

func main() {
    var n int
    var r string
    fmt.Scan(&n)
    fmt.Scan(&r)
    s, t := -1, -1
    for i := 0; i < len(r); i++ {
        if r[i] == 'R' {
            s, t = i, i
            for ; r[t] == 'R'; t++ {}
            if r[t] == 'L' { t-- }
            break
        } else if r[i] == 'L' {
            s, t = i, i
            for ; r[s] == 'L'; s++ {}
            s--
            break
        }
    }
    fmt.Println(s+1,t+1)
}


You are given a pair of integers $$$(a, b)$$$ and an integer $$$x$$$.You can change the pair in two different ways:   set (assign) $$$a := |a - b|$$$;  set (assign) $$$b := |a - b|$$$,  where $$$|a - b|$$$ is the absolute difference between $$$a$$$ and $$$b$$$.The pair $$$(a, b)$$$ is called $$$x$$$-magic if $$$x$$$ is obtainable either as $$$a$$$ or as $$$b$$$ using only the given operations (i.e. the pair $$$(a, b)$$$ is $$$x$$$-magic if $$$a = x$$$ or $$$b = x$$$ after some number of operations applied). You can apply the operations any number of times (even zero).Your task is to find out if the pair $$$(a, b)$$$ is $$$x$$$-magic or not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains three integers $$$a$$$, $$$b$$$ and $$$x$$$ ($$$1 \le a, b, x \le 10^{18}$$$).

For the $$$i$$$-th test case, print YES if the corresponding pair $$$(a, b)$$$ is $$$x$$$-magic and NO otherwise.

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for u:=1;u<=t;u++{
		var a,b,x int64
		fmt.Fscan(in,&a,&b,&x)
		if a<b{
			temp := a
			a = b
			b = temp
		}
		flag := false
		for a>=x{
			if b==0{
				break
			}
			id := a/b
			if (a-x)%b==0{
				flag = true
				break
			}
			na := a - b*id
			a = b
			b = na
		}
		if flag {
			fmt.Fprintln(out, "YES")
		}else{
			fmt.Fprintln(out,"NO")
		}
	}
}

package main

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

var a, b, x int64

func main() {

	r := bufio.NewReader(os.Stdin)

	var t int

	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		fmt.Fscan(r, &a, &b, &x)

		a := solve()

		fmt.Println(a)
	}
}

type pair struct {
	v, id int
}

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

type item struct {
	la, ra int
	lb, rb int
}

const MAX int = 1e6

func solve() string {
	if a < b {
		temp := a
		a = b
		b = temp

	}
	if x > a && x > b {
		return "NO"
	}

	if x == a || x == b {
		return "YES"
	}

	for ;; {
		if b < x {
			if (a - x) % b == 0 {
				return "YES"
			} else {
				return "NO"
			}

		} else {
			k := a/b

			temp := a

			a = b
			b = temp - k * b

			if b == x {
				return "YES"
			}
			if b== 0 {
				return "NO"
			}
		}
	}

}

func gcdExtended(a int64, b int64, x *int64, y *int64) int64 {

	// Base Case
	if a == 0 {
		*x, *y = 0,1
		return b
	}

	// To store results of recursive call
	var x1, y1 int64
	gcd := gcdExtended(b%a, a, &x1, &y1);

	// Update x and y using results of recursive
	// call
	*x = y1 - (b/a)*x1;
	*y = x1
	return gcd
}

func add(idx int, delta int, bit *[]int, n int) {
	for ; idx <= n; idx += idx & -idx {
		(*bit)[idx] += delta
	}
}

func get(idx int, bit *[]int) int {
	ret := 0
	for ; idx > 0; idx -= idx & -idx {
		ret += (*bit)[idx];
	}
	return ret
}

//A -  1 3 5 3 1

//B -  4 3 6 1

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1612D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T, a, b, x int64
o:
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &a, &b, &x)
		if a > b {
			a, b = b, a
		}
		for a > 0 && x <= b {
			if x >= a && (b-x)%a == 0 {
				Fprintln(out, "YES")
				continue o
			}
			a, b = b%a, a
		}
		Fprintln(out, "NO")
	}
}

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


Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.

The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.

In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.

package main

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

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]int, n)
	b := make([]int, n)
	for i := 0;i < n - 1;i ++ {
		fmt.Fscanf(reader, "%d ", &a[i])
	}
	fmt.Fscanf(reader, "%d\n", &a[n - 1])
	for i := 0;i < n - 1;i ++ {
		fmt.Fscanf(reader, "%d ", &b[i])
	}
	fmt.Fscanf(reader, "%d\n", &b[n - 1])

	res := make([]int, 0, 10000)
	for i := 0;i < n;i ++ {
		if a[i] != b[i] {
			for j := i + 1;j < n;j ++ {
				if a[i] == b[j] {
					for k := j - 1;k >= i;k -- {
						res = append(res, k + 1)
						b[k], b[k + 1] = b[k + 1], b[k]
					}
					break
				}
			}
		}
	}
	fmt.Printf("%d\n", len(res))
	for i := 0;i < len(res);i ++ {
		fmt.Printf("%d %d\n", res[i], res[i] + 1)
	}
}

package main

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

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]int, n)
	b := make([]int, n)
	for i := 0;i < n - 1;i ++ {
		fmt.Fscanf(reader, "%d ", &a[i])
	}
	fmt.Fscanf(reader, "%d\n", &a[n - 1])
	for i := 0;i < n - 1;i ++ {
		fmt.Fscanf(reader, "%d ", &b[i])
	}
	fmt.Fscanf(reader, "%d\n", &b[n - 1])

	res := make([]int, 0, 10000)
	for i := 0;i < n;i ++ {
		if a[i] != b[i] {
			for j := i + 1;j < n;j ++ {
				if b[j] == a[i] {
					for k := j - 1;k >= i;k -- {
						res = append(res, k + 1)
						a[k], a[k + 1] = a[k + 1], a[k]
					}
					break
				}
			}
		}
	}
	fmt.Printf("%d\n", len(res))
	for i := 0;i < len(res);i ++ {
		fmt.Printf("%d %d\n", res[i], res[i] + 1)
	}
}

package main

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

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]int, n)
	b := make([]int, n)
	for i := 0;i < n - 1;i ++ {
		fmt.Fscanf(reader, "%d ", &a[i])
	}
	fmt.Fscanf(reader, "%d\n", &a[n - 1])
	for i := 0;i < n - 1;i ++ {
		fmt.Fscanf(reader, "%d ", &b[i])
	}
	fmt.Fscanf(reader, "%d\n", &b[n - 1])

	res := make([]int, 0, 10000)
	for i := 0;i < n;i ++ {
		if a[i] != b[i] {
			for j := i + 1;j < n;j ++ {
				if a[j] == b[i] {
					for k := j - 1;k >= i;k -- {
						res = append(res, k + 1)
						a[k], a[k + 1] = a[k + 1], a[k]
					}
					break
				}
			}
		}
	}
	fmt.Printf("%d\n", len(res))
	for i := 0;i < len(res);i ++ {
		fmt.Printf("%d %d\n", res[i], res[i] + 1)
	}
}


All of us love treasures, right? That's why young Vasya is heading for a Treasure Island.Treasure Island may be represented as a rectangular table $$$n \times m$$$ which is surrounded by the ocean. Let us number rows of the field with consecutive integers from $$$1$$$ to $$$n$$$ from top to bottom and columns with consecutive integers from $$$1$$$ to $$$m$$$ from left to right. Denote the cell in $$$r$$$-th row and $$$c$$$-th column as $$$(r, c)$$$. Some of the island cells contain impassable forests, and some cells are free and passable. Treasure is hidden in cell $$$(n, m)$$$.Vasya got off the ship in cell $$$(1, 1)$$$. Now he wants to reach the treasure. He is hurrying up, so he can move only from cell to the cell in next row (downwards) or next column (rightwards), i.e. from cell $$$(x, y)$$$ he can move only to cells $$$(x+1, y)$$$ and $$$(x, y+1)$$$. Of course Vasya can't move through cells with impassable forests.Evil Witch is aware of Vasya's journey and she is going to prevent him from reaching the treasure. Before Vasya's first move she is able to grow using her evil magic impassable forests in previously free cells. Witch is able to grow a forest in any number of any free cells except cells $$$(1, 1)$$$ where Vasya got off his ship and $$$(n, m)$$$ where the treasure is hidden.Help Evil Witch by finding out the minimum number of cells she has to turn into impassable forests so that Vasya is no longer able to reach the treasure.

First line of input contains two positive integers $$$n$$$, $$$m$$$ ($$$3 \le n \cdot m \le 1\,000\,000$$$), sizes of the island. Following $$$n$$$ lines contains strings $$$s_i$$$ of length $$$m$$$ describing the island, $$$j$$$-th character of string $$$s_i$$$ equals "#" if cell $$$(i, j)$$$ contains an impassable forest and "." if the cell is free and passable. Let us remind you that Vasya gets of his ship at the cell $$$(1, 1)$$$, i.e. the first cell of the first row, and he wants to reach cell $$$(n, m)$$$, i.e. the last cell of the last row. It's guaranteed, that cells $$$(1, 1)$$$ and $$$(n, m)$$$ are empty.

Print the only integer $$$k$$$, which is the minimum number of cells Evil Witch has to turn into impassable forest in order to prevent Vasya from reaching the treasure.

NoteThe following picture illustrates the island in the third example. Blue arrows show possible paths Vasya may use to go from $$$(1, 1)$$$ to $$$(n, m)$$$. Red illustrates one possible set of cells for the Witch to turn into impassable forest to make Vasya's trip from $$$(1, 1)$$$ to $$$(n, m)$$$ impossible.

package main

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

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

var n, m int
var a [][]int
var mp map[int]int

func dfs(i, j, k int) bool {
	if i >= n || j >= m {
		return false
	}
	if i == n-1 && j == m-1 {
		return true
	}
	if a[i][j] == -1 {
		return false
	}
	if a[i][j] != 0 {
		return true
	}

	ret := false
	if dfs(i+1, j, k+1) {
		ret = true
	}
	if dfs(i, j+1, k+1) {
		ret = true
	}
	if ret == true && !(i == 0 && j == 0) {
		a[i][j] = k
		mp[k]++
		return true
	}
	a[i][j] = -1
	return false
}

func main() {
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	a = make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Fscanf(reader, "%c", &c)
			if c == '.' {
				a[i][j] = 0
			} else {
				a[i][j] = -1
			}
		}
		fmt.Fscanln(reader)
	}

	mp = make(map[int]int)
	dfs(0, 0, 0)

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	if ans == INF || mp[n+m-3] == 0 {
		ans = 0
	}
	fmt.Println(ans)

	return
}

package main

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

const (
	maxn = 1000000
)

var n int
var m int
var s [maxn]string
var mark [maxn]bool
var pre_x [maxn]int
var pre_y [maxn]int
var blocked [maxn]bool

func valid(x int, y int) bool {
	return x >= 0 && x < n && y >= 0 && y < m && s[x][y] != '#' && !blocked[get_index(x, y)]
}

func get_index(x int, y int) int {
	return x*m + y
}

func dfs(x int, y int) {
	mark[get_index(x, y)] = true
	if valid(x+1, y) && !mark[get_index(x+1, y)] {
		pre_x[get_index(x+1, y)] = x
		pre_y[get_index(x+1, y)] = y

		dfs(x+1, y)
	}
	if valid(x, y+1) && !mark[get_index(x, y+1)] {
		pre_x[get_index(x, y+1)] = x
		pre_y[get_index(x, y+1)] = y
		dfs(x, y+1)
	}
}

func block_path(x int, y int) {
	if x == 0 && y == 0 {
		return
	}

	if !(x == n-1 && y == m-1) {
		blocked[get_index(x, y)] = true
	}

	x2 := pre_x[get_index(x, y)]
	y2 := pre_y[get_index(x, y)]

	block_path(x2, y2)

}

func main() {

	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	fmt.Fscan(in, &n, &m)

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

	dfs(0, 0)

	if !mark[get_index(n-1, m-1)] {
		fmt.Println(0)
	} else {
		response := 1
		block_path(n-1, m-1)

		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				mark[get_index(i, j)] = false
			}
		}

		dfs(0, 0)
		if mark[get_index(n-1, m-1)] {
			response += 1
		}

		fmt.Println(response)
	}
}

package main

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

func dfs(cell [][]byte, i, j int) bool {
	switch cell[i][j] {
	case '#':
		return false
	case '$':
		return true
	}
	cell[i][j] = '#'
	return j+1 < len(cell[i]) && dfs(cell, i, j+1) ||
		i+1 < len(cell) && dfs(cell, i+1, j)
}

// github.com/EndlessCheng/codeforces-go
func Sol1214D(reader io.Reader, writer io.Writer) {
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n, m int
	Fscan(in, &n, &m)
	cell := make([][]byte, n)
	for i := range cell {
		Fscan(in, &cell[i])
	}

	ans := 0
	cell[n-1][m-1] = '$'
	if dfs(cell, 0, 0) {
		ans++
	}
	cell[0][0] = '.'
	if dfs(cell, 0, 0) {
		ans++
	}
	Fprint(out, ans)
}

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

package main

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

func dfs(cell [][]byte, i, j int) bool {
	switch cell[i][j] {
	case '#':
		return false
	case '$':
		return true
	}
	cell[i][j] = '#'
	return j+1 < len(cell[i]) && dfs(cell, i, j+1) ||
		i+1 < len(cell) && dfs(cell, i+1, j)
}

// github.com/EndlessCheng/codeforces-go
func Sol1214D(reader io.Reader, writer io.Writer) {
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n, m int
	Fscan(in, &n, &m)
	cell := make([][]byte, n)
	for i := range cell {
		Fscan(in, &cell[i])
	}

	ans := 0
	cell[n-1][m-1] = '$'
	if dfs(cell, 0, 0) {
		ans++
		cell[0][0] = '.'
		if dfs(cell, 0, 0) {
			ans++
		}
	}
	Fprint(out, ans)
}

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

package main

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

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

var n, m int
var a [][]int
var mp map[int]int

func dfs(i, j, k int) bool {
	if i >= n || j >= m {
		return false
	}
	if i == n-1 && j == m-1 {
		return true
	}
	if a[i][j] == -1 {
		return false
	}
	if a[i][j] != 0 {
		return true
	}
	ret := false
	if dfs(i+1, j, k+1) {
		ret = true
	}
	if dfs(i, j+1, k+1) {
		ret = true
	}
	if ret == true && !(i == 0 && j == 0) {
		a[i][j] = k
		mp[k]++
		return true
	}
	a[i][j] = -1
	return false
}

func main() {
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	a = make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Fscanf(reader, "%c", &c)
			if c == '.' {
				a[i][j] = 0
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanln()
	}

	mp = make(map[int]int)
	dfs(0, 0, 0)
	// fmt.Println(a)

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	if ans == INF || mp[n+m-2] == 0 {
		ans = 0
	}
	fmt.Println(ans)

	return
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanln()
	}

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) && a[i][j] != INF {
				mp[a[i][j]]++
			}
		}
	}

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	if ans == INF || mp[n+m-3] == INF {
		ans = 0
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanln()
	}

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) && a[i][j] != INF {
				mp[a[i][j]]++
			}
		}
	}

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	if ans == INF || mp[n+m-3] != INF {
		ans = 0
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

var n, m int
var a [][]int
var mp map[int]int

func dfs(i, j, k int) bool {
	if i >= n || j >= m {
		return false
	}
	if i == n-1 && j == m-1 {
		return true
	}
	if a[i][j] == -1 {
		return false
	}
	ret := false
	if dfs(i+1, j, k+1) {
		ret = true
	}
	if dfs(i, j+1, k+1) {
		ret = true
	}
	if ret == true && !(i == 0 && j == 0) {
		mp[k]++
		return true
	}
	return false
}

func main() {
	fmt.Scanf("%d %d\n", &n, &m)
	a = make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = 0
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanln()
	}

	mp = make(map[int]int)
	dfs(0, 0, 0)
	// fmt.Println(mp)

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	if ans == INF {
		ans = 0
	}
	fmt.Println(ans)

	return
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanln()
	}

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) {
				mp[a[i][j]]++
			}
		}
	}

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			fmt.Println(c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanf("%c", &c)
	}

	fmt.Println(a)

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) {
				mp[a[i][j]]++
			}
		}
	}

	fmt.Println(a)
	fmt.Println(mp)

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanf("%c", &c)
	}

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) {
				mp[a[i][j]]++
			}
		}
	}

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanln()
	}

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) && a[i][j] != INF {
				mp[a[i][j]]++
			}
		}
	}

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	if ans == INF || mp[n+m-3] == 0 {
		ans = 0
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d%d", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanf("%c", &c)
	}

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) {
				mp[a[i][j]]++
			}
		}
	}

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	fmt.Println(ans)
}

package main

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

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

var n, m int
var a [][]int
var mp map[int]int

func dfs(i, j, k int) bool {
	if i >= n || j >= m {
		return false
	}
	if i == n-1 && j == m-1 {
		return true
	}
	if a[i][j] == -1 {
		return false
	}
	if a[i][j] != 0 {
		return true
	}

	ret := false
	if dfs(i+1, j, k+1) {
		ret = true
	}
	if dfs(i, j+1, k+1) {
		ret = true
	}
	if ret == true && !(i == 0 && j == 0) {
		a[i][j] = k
		mp[k]++
		return true
	}
	a[i][j] = -1
	return false
}

func main() {
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	a = make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Fscanf(reader, "%c", &c)
			if c == '.' {
				a[i][j] = 0
			} else {
				a[i][j] = -1
			}
		}
		fmt.Fscanf(reader, "%c", &c)
	}

	mp = make(map[int]int)
	dfs(0, 0, 0)

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	if ans == INF || mp[n+m-3] == 0 {
		ans = 0
	}
	fmt.Println(ans)

	return
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanf("%c", &c)
	}

	fmt.Println(a)

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) {
				mp[a[i][j]]++
			}
		}
	}

	fmt.Println(a)
	fmt.Println(mp)

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanln()
	}

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) && a[i][j] != INF {
				mp[a[i][j]]++
			}
		}
	}

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	if ans == INF {
		ans = 0
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanln()
	}

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 && a[i-1][j] != INF {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 && a[i][j-1] != INF {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) && a[i][j] != INF {
				mp[a[i][j]]++
			}
		}
	}

	if a[n-1][m-1] == INF {
		fmt.Println(0)
		return
	}

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	if ans == INF {
		ans = 0
	}
	fmt.Println(ans)
	return
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanln()
	}

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) && a[i][j] != INF {
				mp[a[i][j]]++
			}
		}
	}

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			fmt.Println(c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanln()
	}

	fmt.Println(a)

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) {
				mp[a[i][j]]++
			}
		}
	}

	fmt.Println(a)
	fmt.Println(mp)

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	fmt.Println(ans)
}

package main

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

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

var n, m int
var a [][]int
var mp map[int]int

func dfs(i, j, k int) bool {
	if i >= n || j >= m {
		return false
	}
	if i == n-1 && j == m-1 {
		return true
	}
	if a[i][j] == -1 {
		return false
	}
	if a[i][j] != 0 {
		return true
	}

	ret := false
	if dfs(i+1, j, k+1) {
		ret = true
	}
	if dfs(i, j+1, k+1) {
		ret = true
	}
	if ret == true && !(i == 0 && j == 0) {
		a[i][j] = k
		mp[k]++
		return true
	}
	a[i][j] = -1
	return false
}

func main() {
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	a = make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Fscanf(reader, "%c", &c)
			if c == '.' {
				a[i][j] = 0
			} else {
				a[i][j] = -1
			}
		}
		// fmt.Fscanf(reader, "%c", &c)
	}

	mp = make(map[int]int)
	dfs(0, 0, 0)

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	if ans == INF || mp[n+m-3] == 0 {
		ans = 0
	}
	fmt.Println(ans)

	return
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanf("%c", &c)
	}

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) {
				mp[a[i][j]]++
			}
		}
	}

	fmt.Println(a)
	fmt.Println(mp)

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const (
	// INF 无穷大
	INF = 0x3f3f3f2f
)

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		var c byte
		for j := 0; j < m; j++ {
			fmt.Scanf("%c", &c)
			if c == '.' {
				a[i][j] = INF
			} else {
				a[i][j] = -1
			}
		}
		fmt.Scanln()
	}

	a[0][0] = 0
	mp := make(map[int]int)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if a[i][j] == -1 {
				continue
			}
			if i > 0 && a[i-1][j] != -1 && a[i-1][j] != INF {
				a[i][j] = a[i-1][j] + 1
			} else if j > 0 && a[i][j-1] != -1 && a[i][j-1] != INF {
				if a[i][j] > a[i][j-1]+1 {
					a[i][j] = a[i][j-1] + 1
				}
			}
			if !(i == 0 && j == 0 || i == n-1 && j == m-1) && a[i][j] != INF {
				mp[a[i][j]]++
			}
		}
	}

	ans := INF
	for _, v := range mp {
		if ans > v {
			ans = v
		}
	}
	if ans == INF {
		ans = 0
	}
	fmt.Println(ans)
}

package main

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

func dfs(cell [][]byte, i, j int) bool {
	switch cell[i][j] {
	case '#':
		return false
	case '$':
		return true
	}
	cell[i][j] = '#'
	return j+1 < len(cell[i]) && dfs(cell, i, j+1) ||
		i+1 < len(cell) && dfs(cell, i+1, j)
}

func dfsR(cell [][]byte, i, j int) bool {
	switch cell[i][j] {
	case '#':
		return false
	case '$':
		return true
	}
	cell[i][j] = '#'
	return j > 0 && dfsR(cell, i, j-1) ||
		i > 0 && dfsR(cell, i-1, j)
}

// github.com/EndlessCheng/codeforces-go
func Sol1214D(reader io.Reader, writer io.Writer) {
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n, m int
	Fscan(in, &n, &m)
	containForest := false
	cell := make([][]byte, n)
	for i := range cell {
		Fscan(in, &cell[i])
		containForest = containForest && bytes.Contains(cell[i], []byte{'#'})
	}

	if n == 1 || m == 1 {
		if containForest {
			Fprint(out, 0)
		} else {
			Fprint(out, 1)
		}
		return
	}

	ans := 0
	cell[n-1][m-1] = '$'
	if dfs(cell, 0, 1) {
		ans++
	}
	cell[0][0] = '$'
	if dfsR(cell, n-1, m-2) {
		ans++
	}
	Fprint(out, ans)
}

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


One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated – it consists of n brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly:   It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains).  There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false. If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid.

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n, a ≠ b).

The output consists of one line, containing either yes or no depending on whether the nervous system is valid.

package main

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

type brain struct {
	v    int
	link []int
}

func remove_link(b brain, n int) brain {
	for i, j := range b.link {
		if j == n {
			b.link = append(b.link[:i], b.link[i+1:]...)
			return b
		}
	}
	return b
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	s := strings.Split(text, " ")

	n, _ := strconv.Atoi(s[0])
	m, _ := strconv.Atoi(s[1])
	v := make(map[int]brain)
	for i := 0; i < m; i++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimRight(text, "\r\n")
		s := strings.Split(text, " ")
		a, _ := strconv.Atoi(s[0])
		b, _ := strconv.Atoi(s[1])
		tmpb := v[a]
		tmpb.v = a
		tmpb.link = append(tmpb.link, b)
		v[a] = tmpb
		tmpb = v[b]
		tmpb.v = b
		tmpb.link = append(tmpb.link, a)
		v[b] = tmpb
	}

	pending := []int{1}
	visited := []int{1}
	valid := true
	for len(pending) > 0 && valid {
		c := pending[0]
		b := v[c]
		for len(b.link) > 0 && valid {
			n := b.link[0]
			b.link = b.link[1:]
			pending = append(pending, n)

			tmpb := v[n]
			tmpb = remove_link(tmpb, c)
			v[n] = tmpb
			for _, j := range visited {
				if j == n {
					valid = false
				}
			}
			visited = append(visited, n)
		}
		pending = pending[1:]
	}
	if len(visited) != n {
		valid = false
	}
	if valid {
		fmt.Println("yes")
	} else {
		fmt.Println("no")
	}
}

package main

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

type brain struct {
	v    int
	link []int
}

func remove_link(b brain, n int) brain {
	fmt.Println(b, n)
	for i, j := range b.link {
		if j == n {
			b.link = append(b.link[:i], b.link[i+1:]...)
			return b
		}
	}
	return b
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	s := strings.Split(text, " ")

	n, _ := strconv.Atoi(s[0])
	m, _ := strconv.Atoi(s[1])
	v := make(map[int]brain)
	for i := 0; i < m; i++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimRight(text, "\r\n")
		s := strings.Split(text, " ")
		a, _ := strconv.Atoi(s[0])
		b, _ := strconv.Atoi(s[1])
		tmpb := v[a]
		tmpb.v = a
		tmpb.link = append(tmpb.link, b)
		v[a] = tmpb
		tmpb = v[b]
		tmpb.v = b
		tmpb.link = append(tmpb.link, a)
		v[b] = tmpb
	}

	pending := []int{1}
	visited := []int{1}
	valid := true
	for len(pending) > 0 && valid {
		c := pending[0]
		b := v[c]
		for len(b.link) > 0 && valid {
			n := b.link[0]
			b.link = b.link[1:]
			pending = append(pending, n)

			tmpb := v[n]
			tmpb = remove_link(tmpb, c)
			v[n] = tmpb
			for _, j := range visited {
				if j == n {
					valid = false
				}
			}
			visited = append(visited, n)
		}
		pending = pending[1:]
	}
	if len(visited) != n {
		valid = false
	}
	if valid {
		fmt.Println("yes")
	} else {
		fmt.Println("no")
	}
}

package main

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

type brain struct {
	v    int
	link []int
}

func remove_link(b brain, n int) brain {
	for i, j := range b.link {
		if j == n {
			b.link = append(b.link[:i], b.link[i+1:]...)
		}
	}
	return b
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	s := strings.Split(text, " ")

	//n, _ := strconv.Atoi(s[0])
	m, _ := strconv.Atoi(s[1])
	v := make(map[int]brain)
	for i := 0; i < m; i++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimRight(text, "\r\n")
		s := strings.Split(text, " ")
		a, _ := strconv.Atoi(s[0])
		b, _ := strconv.Atoi(s[1])
		tmpb := v[a]
		tmpb.v = a
		tmpb.link = append(tmpb.link, b)
		v[a] = tmpb
		tmpb = v[b]
		tmpb.v = b
		tmpb.link = append(tmpb.link, a)
		v[b] = tmpb
	}

	pending := []int{1}
	visited := []int{1}
	valid := true
	for len(pending) > 0 && valid {
		c := pending[0]
		b := v[c]
		for len(b.link) > 0 && valid {
			n := b.link[0]
			b.link = b.link[1:]
			pending = append(pending, n)

			tmpb := v[n]
			tmpb = remove_link(tmpb, c)
			v[n] = tmpb
			for _, j := range visited {
				if j == n {
					valid = false
				}
			}
			visited = append(visited, n)
		}
		pending = pending[1:]
	}
	if valid {
		fmt.Println("yes")
	} else {
		fmt.Println("no")
	}
}