The statement of this problem shares a lot with problem A. The differences are that in this problem, the probability is introduced, and the constraint is different.A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $$$n$$$ rows and $$$m$$$ columns. The rows of the floor are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and columns of the floor are numbered from $$$1$$$ to $$$m$$$ from left to right. The cell on the intersection of the $$$r$$$-th row and the $$$c$$$-th column is denoted as $$$(r,c)$$$. The initial position of the robot is $$$(r_b, c_b)$$$.In one second, the robot moves by $$$dr$$$ rows and $$$dc$$$ columns, that is, after one second, the robot moves from the cell $$$(r, c)$$$ to $$$(r + dr, c + dc)$$$. Initially $$$dr = 1$$$, $$$dc = 1$$$. If there is a vertical wall (the left or the right walls) in the movement direction, $$$dc$$$ is reflected before the movement, so the new value of $$$dc$$$ is $$$-dc$$$. And if there is a horizontal wall (the upper or lower walls), $$$dr$$$ is reflected before the movement, so the new value of $$$dr$$$ is $$$-dr$$$.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at $$$(r_d, c_d)$$$. The job of the robot is to clean that dirty cell. After a lot of testings in problem A, the robot is now broken. It cleans the floor as described above, but at each second the cleaning operation is performed with probability $$$\frac p {100}$$$ only, and not performed with probability $$$1 - \frac p {100}$$$. The cleaning or not cleaning outcomes are independent each second.Given the floor size $$$n$$$ and $$$m$$$, the robot's initial position $$$(r_b, c_b)$$$ and the dirty cell's position $$$(r_d, c_d)$$$, find the expected time for the robot to do its job.It can be shown that the answer can be expressed as an irreducible fraction $$$\frac x y$$$, where $$$x$$$ and $$$y$$$ are integers and $$$y \not \equiv 0 \pmod{10^9 + 7} $$$. Output the integer equal to $$$x \cdot y^{-1} \bmod (10^9 + 7)$$$. In other words, output such an integer $$$a$$$ that $$$0 \le a < 10^9 + 7$$$ and $$$a \cdot y \equiv x \pmod {10^9 + 7}$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10$$$). Description of the test cases follows. A test case consists of only one line, containing $$$n$$$, $$$m$$$, $$$r_b$$$, $$$c_b$$$, $$$r_d$$$, $$$c_d$$$, and $$$p$$$ ($$$4 \le n \cdot m \le 10^5$$$, $$$n, m \ge 2$$$, $$$1 \le r_b, r_d \le n$$$, $$$1 \le c_b, c_d \le m$$$, $$$1 \le p \le 99$$$) — the sizes of the room, the initial position of the robot, the position of the dirt cell and the probability of cleaning in percentage.

For each test case, print a single integer — the expected time for the robot to clean the dirty cell, modulo $$$10^9 + 7$$$.

NoteIn the first test case, the robot has the opportunity to clean the dirty cell every second. Using the geometric distribution, we can find out that with the success rate of $$$25\%$$$, the expected number of tries to clear the dirty cell is $$$\frac 1 {0.25} = 4$$$. But because the first moment the robot has the opportunity to clean the cell is before the robot starts moving, the answer is $$$3$$$.  Illustration for the first example. The blue arc is the robot. The red star is the target dirt cell. The purple square is the initial position of the robot. Each second the robot has an opportunity to clean a row and a column, denoted by yellow stripes. In the second test case, the board size and the position are different, but the robot still has the opportunity to clean the dirty cell every second, and it has the same probability of cleaning. Therefore the answer is the same as in the first example.  Illustration for the second example. The third and the fourth case are almost the same. The only difference is that the position of the dirty cell and the robot are swapped. But the movements in both cases are identical, hence the same result.

package main

import (
	"bufio"
	. "fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	const mod int64 = 1e9 + 7
	pow := func(x, n int64) int64 {
		x %= mod
		res := int64(1)
		for ; n > 0; n >>= 1 {
			if n&1 > 0 {
				res = res * x % mod
			}
			x = x * x % mod
		}
		return res
	}
	inv := func(a int64) int64 { return pow(a, mod-2) }
	div := func(a, b int64) int64 { return a % mod * inv(b%mod) % mod }

	solve := func(Case int) {
		var n, m, x, y, tx, ty int
		var P int64
		Fscan(in, &n, &m, &x, &y, &tx, &ty, &P)
		T := 2 * (n - 1) * (m - 1) / gcd(n-1, m-1)

		p := div(P, 100)
		np := div(100-P, 100)

		dx, dy := 1, 1
		//x0, y0 := x, y

		if x+dx < 1 || x+dx > n {
			dx = -dx
		}
		if y+dy < 1 || y+dy > m {
			dy = -dy
		}
		//dx0, dy0 := dx, dy

		part1 := int64(0)
		part2 := int64(0)
		powNp := int64(1)
		k := int64(0)
		t := int64(0)
		for {
			if x == tx || y == ty {
				part1 = (part1 + t*powNp) % mod
				part2 = (part2 + powNp) % mod
				powNp = powNp * np % mod
				k++
			}
			t++
			x += dx
			y += dy
			if x+dx < 1 || x+dx > n {
				dx = -dx
			}
			if y+dy < 1 || y+dy > m {
				dy = -dy
			}
			if int(t)==T  {
				break
			}
			//Println(t, x,y,dx,dy,"#", x0,y0,dx0,dy0)
		}
		//Println()
		part2 = part2 * t % mod

		sq := div(1, 1+mod-powNp)
		part1 = part1 * sq % mod

		sq2 := div(powNp, (1+mod-powNp)*(1+mod-powNp)%mod)
		part2 = part2 * sq2 % mod

		ans := (part1 + part2) % mod
		ans = ans * p % mod
		Fprintln(out, ans)
	}

	T := 1
	Fscan(in, &T)
	for Case := 1; Case <= T; Case++ {
		solve(Case)
	}

	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("有未读入的数据：\n" + _s)
	}

}

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

func gcd(a, b int) int {
	for a != 0 {
		a, b = b%a, a
	}
	return b
}

package main

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

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

	tc := readNum(reader)
	var buf bytes.Buffer

	for tc > 0 {
		tc--
		in := readNNums(reader, 7)
		res := solve(in[0], in[1], in[2], in[3], in[4], in[5], in[6])
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}

	fmt.Print(buf.String())
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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

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

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

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

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

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

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

	return i
}

const MOD = 1000000007

func pow(a, b int) int {
	A := int64(a)
	R := int64(1)
	for b > 0 {
		if b&1 == 1 {
			R = (R * A) % MOD
		}
		A = (A * A) % MOD
		b >>= 1
	}
	return int(R)
}

func inverse(x int) int {
	return pow(x, MOD-2)
}

func add(a, b int) int {
	a += b
	if a >= MOD {
		a -= MOD
	}
	return a
}

func sub(a, b int) int {
	return add(a, MOD-b)
}

func mul(a, b int) int {
	A := int64(a) * int64(b)
	A %= MOD
	return int(A)
}

func solve(n int, m int, rb int, cb int, rd int, cd int, p int) int {
	p = sub(1, mul(p, inverse(100)))

	dr, dc := -1, -1
	var u int
	v := 1
	for i := 0; i < 4*(n-1)*(m-1); i++ {
		if !(rb+dr >= 1 && rb+dr <= n) {
			dr *= -1
		}
		if !(cb+dc >= 1 && cb+dc <= m) {
			dc *= -1
		}
		rb += dr
		cb += dc
		u++
		if rb == rd || cb == cd {
			u = mul(u, p)
			v = mul(v, p)
		}
	}
	ans := mul(u, inverse(sub(1, v)))
	return ans
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	const mod int64 = 1e9 + 7
	pow := func(x, n int64) int64 {
		x %= mod
		res := int64(1)
		for ; n > 0; n >>= 1 {
			if n&1 > 0 {
				res = res * x % mod
			}
			x = x * x % mod
		}
		return res
	}
	inv := func(a int64) int64 { return pow(a, mod-2) }
	div := func(a, b int64) int64 { return a % mod * inv(b) % mod }

	solve := func(Case int) {
		var n, m, x, y, tx, ty int
		var P int64
		Fscan(in, &n, &m, &x, &y, &tx, &ty, &P)
		p := div(P, 100)
		np := div(100-P, 100)

		dx, dy := 1, 1
		x0, y0 := x, y

		part1 := int64(0)
		part2 := int64(0)
		powNp := int64(1)
		k := int64(0)
		t := int64(0)
		for ; ; t++ {
			if x == tx || y == ty {
				part1 = (part1 + t*powNp) % mod
				part2 = (part2 + powNp) % mod
				powNp = powNp * np % mod
				k++
			}

			if x+dx < 1 || x+dx > n {
				dx = -dx
			}
			if y+dy < 1 || y+dy > m {
				dy = -dy
			}
			x += dx
			y += dy
			if x == x0 && y == y0 {
				t++
				break
			}
		}
		part2 = part2 * t % mod

		sq := div(1, 1+mod-powNp)
		part1 = part1 * sq % mod

		sq2 := div(powNp, (1+mod-powNp)*(1+mod-powNp)%mod)
		part2 = part2 * sq2 % mod

		ans := (part1 + part2) % mod
		ans = ans * p % mod
		Fprintln(out, ans)
	}

	T := 1
	Fscan(in, &T)
	for Case := 1; Case <= T; Case++ {
		solve(Case)
	}

	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("有未读入的数据：\n" + _s)
	}

}

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


There is an undirected tree of $$$n$$$ vertices, connected by $$$n-1$$$ bidirectional edges. There is also a snake stuck inside of this tree. Its head is at vertex $$$a$$$ and its tail is at vertex $$$b$$$. The snake's body occupies all vertices on the unique simple path between $$$a$$$ and $$$b$$$.The snake wants to know if it can reverse itself  — that is, to move its head to where its tail started, and its tail to where its head started. Unfortunately, the snake's movements are restricted to the tree's structure.In an operation, the snake can move its head to an adjacent vertex not currently occupied by the snake. When it does this, the tail moves one vertex closer to the head, so that the length of the snake remains unchanged. Similarly, the snake can also move its tail to an adjacent vertex not currently occupied by the snake. When it does this, the head moves one unit closer to the tail.  Let's denote a snake position by $$$(h,t)$$$, where $$$h$$$ is the index of the vertex with the snake's head, $$$t$$$ is the index of the vertex with the snake's tail. This snake can reverse itself with the movements $$$(4,7)\to (5,1)\to (4,2)\to (1, 3)\to (7,2)\to (8,1)\to (7,4)$$$. Determine if it is possible to reverse the snake with some sequence of operations.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 100$$$)  — the number of test cases. The next lines contain descriptions of test cases. The first line of each test case contains three integers $$$n,a,b$$$ ($$$2\le n\le 10^5,1\le a,b\le n,a\ne b$$$). Each of the next $$$n-1$$$ lines contains two integers $$$u_i,v_i$$$ ($$$1\le u_i,v_i\le n,u_i\ne v_i$$$), indicating an edge between vertices $$$u_i$$$ and $$$v_i$$$. It is guaranteed that the given edges form a tree. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, output "YES" if it is possible for the snake to reverse itself, or "NO" otherwise.

NoteThe first test case is pictured above.In the second test case, the tree is a path. We can show that the snake cannot reverse itself.In the third test case, we can show that the snake cannot reverse itself.In the fourth test case, an example solution is:$$$(15,12)\to (16,11)\to (15,13)\to (10,14)\to (8,13)\to (4,11)\to (1,10)$$$$$$\to (2,8)\to (3,4)\to (2,5)\to (1,6)\to (4,7)\to (8,6)\to (10,5)$$$$$$\to (11,4)\to (13,8)\to (14,10)\to (13,15)\to (11,16)\to (12,15)$$$.

package main

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

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.nextInt(); t > 0; t-- {
		n, a, b := io.nextInt(), io.nextInt(), io.nextInt()
		g := make([][]int, n+1)
		for i := 0; i < n-1; i++ {
			u, v := io.nextInt(), io.nextInt()
			g[u] = append(g[u], v)
			g[v] = append(g[v], u)
		}

		arm := make([][]int, n+1)
		var dfsUp func(u, p int)
		dfsUp = func(u, p int) {
			arm[u] = []int{0}
			for _, v := range g[u] {
				if v != p {
					dfsUp(v, u)
					arm[u] = append(arm[u], arm[v][0]+1)
				}
			}
			sort.Sort(sort.Reverse(sort.IntSlice(arm[u])))
		}
		dfsUp(1, 1)

		var dfsDn func(u, p int)
		dfsDn = func(u, p int) {
			for _, v := range g[u] {
				if v != p {
					x := arm[u][0]
					if x == arm[v][0]+1 {
						x = arm[u][1]
					}
					arm[v] = append(arm[v], x+1)
					sort.Sort(sort.Reverse(sort.IntSlice(arm[v])))
					dfsDn(v, u)
				}
			}
		}
		dfsDn(1, 1)

		var dfsSnek func(u, p int) int
		dfsSnek = func(u, p int) int {
			if u == b {
				return 0
			}
			for _, v := range g[u] {
				if v != p {
					d := dfsSnek(v, u)
					if d >= 0 {
						return d + 1
					}
				}
			}
			return -1
		}
		snekLen := dfsSnek(a, a)

		root := -1
		for u := 1; u <= n; u++ {
			if len(arm[u]) >= 3 && arm[u][2] >= snekLen {
				root = u
			}
		}

		ok := false
		if root != -1 {
			arm = make([][]int, n+1)
			dfsUp(root, root)

			par := make([]int, n+1)
			in, out, time := make([]int, n+1), make([]int, n+1), 0
			var dfsEuler func(u, p int)
			dfsEuler = func(u, p int) {
				time++
				in[u] = time
				par[u] = p
				for _, v := range g[u] {
					if v != p {
						dfsEuler(v, u)
					}
				}
				time++
				out[u] = time
			}
			dfsEuler(root, root)

			isAbove := func(u, v int) bool {
				return in[u] <= in[v] && in[v] <= out[u]
			}

			type snekPos struct {
				a, b int
			}
			vis := map[snekPos]bool{}

			for !vis[snekPos{a, b}] {
				if isAbove(a, b) || isAbove(b, a) {
					ok = true
					break
				}
				vis[snekPos{a, b}] = true
				for len(g[a]) > 1 {
					for _, v := range g[a] {
						x := arm[a][0]
						if x == arm[v][0]+1 {
							a, b = v, par[b]
							break
						}
					}
				}
				a, b = b, a
			}
		}

		if ok {
			io.println("YES")
		} else {
			io.println("NO")
		}
	}
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for !('0' <= f.p[0] && f.p[0] <= '9') {
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	return n
}

func (f *fastIO) nextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.nextInt()
	}
	return a
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *fastIO) printInts(a ...int) {
	if len(a) > 0 {
		f.print(a[0])
		for _, x := range a[1:] {
			f.print(" ", x)
		}
	}
}

func (f *fastIO) printlnInts(a ...int) {
	f.printInts(a...)
	f.println()
}

package main

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

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.nextInt(); t > 0; t-- {
		n, a, b := io.nextInt(), io.nextInt(), io.nextInt()
		g := make([][]int, n+1)
		for i := 0; i < n-1; i++ {
			u, v := io.nextInt(), io.nextInt()
			g[u] = append(g[u], v)
			g[v] = append(g[v], u)
		}

		arm := make([][]int, n+1)
		var dfsUp func(u, p int)
		dfsUp = func(u, p int) {
			arm[u] = []int{0}
			for _, v := range g[u] {
				if v != p {
					dfsUp(v, u)
					arm[u] = append(arm[u], arm[v][0]+1)
				}
			}
			sort.Sort(sort.Reverse(sort.IntSlice(arm[u])))
		}
		dfsUp(1, 1)

		var dfsDn func(u, p int)
		dfsDn = func(u, p int) {
			for _, v := range g[u] {
				if v != p {
					x := arm[u][0]
					if x == arm[v][0]+1 {
						x = arm[u][1]
					}
					arm[v] = append(arm[v], x+1)
					sort.Sort(sort.Reverse(sort.IntSlice(arm[v])))
					dfsDn(v, u)
				}
			}
		}
		dfsDn(1, 1)

		var dfsSnek func(u, p int) int
		dfsSnek = func(u, p int) int {
			if u == b {
				return 0
			}
			for _, v := range g[u] {
				if v != p {
					d := dfsSnek(v, u)
					if d >= 0 {
						return d + 1
					}
				}
			}
			return -1
		}
		snekLen := dfsSnek(a, a)

		root := -1
		for u := 1; u <= n; u++ {
			if len(arm[u]) >= 3 && arm[u][2] >= snekLen {
				root = u
			}
		}

		ok := false
		if root != -1 {
			arm = make([][]int, n+1)
			dfsUp(root, root)

			par := make([]int, n+1)
			in, out, time := make([]int, n+1), make([]int, n+1), 0
			var dfsEuler func(u, p int)
			dfsEuler = func(u, p int) {
				time++
				in[u] = time
				par[u] = p
				for _, v := range g[u] {
					if v != p {
						dfsEuler(v, u)
					}
				}
				time++
				out[u] = time
			}
			dfsEuler(root, root)

			isAbove := func(u, v int) bool {
				return in[u] <= in[v] && in[v] <= out[u]
			}

			type snekPos struct {
				a, b int
			}
			vis := map[snekPos]bool{}

			for !vis[snekPos{a, b}] && !vis[snekPos{b, a}] {
				if isAbove(a, b) || isAbove(b, a) {
					ok = true
					break
				}
				vis[snekPos{a, b}] = true
				for len(g[a]) > 1 {
					for _, v := range g[a] {
						x := arm[a][0]
						if x == arm[v][0]+1 {
							a, b = v, par[b]
							break
						}
					}
				}
				a, b = b, a
			}
		}

		if ok {
			io.println("YES")
		} else {
			io.println("NO")
		}
	}
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for !('0' <= f.p[0] && f.p[0] <= '9') {
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	return n
}

func (f *fastIO) nextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.nextInt()
	}
	return a
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *fastIO) printInts(a ...int) {
	if len(a) > 0 {
		f.print(a[0])
		for _, x := range a[1:] {
			f.print(" ", x)
		}
	}
}

func (f *fastIO) printlnInts(a ...int) {
	f.printInts(a...)
	f.println()
}

package main

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

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.nextInt(); t > 0; t-- {
		n, a, b := io.nextInt(), io.nextInt(), io.nextInt()
		g := make([][]int, n+1)
		for i := 0; i < n-1; i++ {
			u, v := io.nextInt(), io.nextInt()
			g[u] = append(g[u], v)
			g[v] = append(g[v], u)
		}

		dep := make([]int, n+1)
		arm := make([][]int, n+1)
		var dfsUp func(u, p int)
		dfsUp = func(u, p int) {
			arm[u] = []int{0}
			for _, v := range g[u] {
				if v != p {
					dep[v] = dep[u] + 1
					dfsUp(v, u)
					arm[u] = append(arm[u], arm[v][0]+1)
				}
			}
			sort.Sort(sort.Reverse(sort.IntSlice(arm[u])))
		}
		dfsUp(1, 1)

		var dfsDn func(u, p int)
		dfsDn = func(u, p int) {
			for _, v := range g[u] {
				if v != p {
					x := arm[u][0]
					if x == arm[v][0]+1 {
						x = arm[u][1]
					}
					arm[v] = append(arm[v], x+1)
					sort.Sort(sort.Reverse(sort.IntSlice(arm[v])))
					dfsDn(v, u)
				}
			}
		}
		dfsDn(1, 1)

		var dfsSnek func(u, p int) int
		dfsSnek = func(u, p int) int {
			if u == b {
				return 0
			}
			for _, v := range g[u] {
				if v != p {
					d := dfsSnek(v, u)
					if d >= 0 {
						return d + 1
					}
				}
			}
			return -1
		}
		snekLen := dfsSnek(a, a)

		root := -1
		for u := 1; u <= n; u++ {
			if len(arm[u]) >= 3 && arm[u][2] >= snekLen {
				root = u
			}
		}

		ok := false
		if root != -1 {
			arm = make([][]int, n+1)
			dfsUp(root, root)

			par := make([]int, n+1)
			in, out, time := make([]int, n+1), make([]int, n+1), 0
			var dfsEuler func(u, p int)
			dfsEuler = func(u, p int) {
				time++
				in[u] = time
				par[u] = p
				for _, v := range g[u] {
					if v != p {
						dfsEuler(v, u)
					}
				}
				time++
				out[u] = time
			}
			dfsEuler(root, root)

			isAbove := func(u, v int) bool {
				return in[u] <= in[v] && in[v] <= out[u]
			}

			type snekPos struct {
				a, b int
			}
			vis := map[snekPos]bool{}

			for !vis[snekPos{a, b}] && !vis[snekPos{b, a}] {
				if isAbove(a, b) || isAbove(b, a) {
					ok = true
					break
				}
				vis[snekPos{a, b}] = true
				for len(g[a]) > 1 {
					for _, v := range g[a] {
						x := arm[a][0]
						if x == arm[v][0]+1 {
							a, b = v, par[b]
						}
					}
				}
				a, b = b, a
			}
		}

		if ok {
			io.println("YES")
		} else {
			io.println("NO")
		}
	}
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for !('0' <= f.p[0] && f.p[0] <= '9') {
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	return n
}

func (f *fastIO) nextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.nextInt()
	}
	return a
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *fastIO) printInts(a ...int) {
	if len(a) > 0 {
		f.print(a[0])
		for _, x := range a[1:] {
			f.print(" ", x)
		}
	}
}

func (f *fastIO) printlnInts(a ...int) {
	f.printInts(a...)
	f.println()
}


Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.You are given a string s consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.A substring of a string is a nonempty sequence of consecutive characters.For example if string s is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.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 only line contains string s (1 ≤ |s| ≤ 3·105). The string s contains only digits from 0 to 9.

Print integer a — the number of substrings of the string s that are divisible by 4. Note that the answer can be huge, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

package main

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

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

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)
	reader := bufio.NewReader(os.Stdin)

	s, _ := reader.ReadString('\n')
	s = strings.TrimSpace(s)
	var ret int64

	if s[0] == '0' || s[0] == '4' || s[0] == '8' {
		ret++
	}

	for i := 1; i < len(s); i++ {
		// println(s[i-1 : i+1])
		m, _ := strconv.Atoi(s[i-1 : i+1])
		if m%4 == 0 {
			ret += int64(i)
		}

		if (s[i]-'0')%4 == 0 {
			ret++
		}
	}

	println(ret)
}

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 (
	"fmt"
	"bufio"
	"os"
	"strings"
	// "strconv"
	// "sort"
	// "math"
)

//N _
const (
	N = 1e6 + 5
)

func inputter(inputReader *bufio.Reader,strs chan *string){
	for {
		input , _ := inputReader.ReadString('\n')
		input = strings.TrimSpace(input)
		if len(input) > 0 {
			inputs := strings.Split(input, " ")
			for i := range inputs{
				strs <- &inputs[i]
			}
		}
	}
}

func main(){
	rs := bufio.NewReader(os.Stdin)
	ws := bufio.NewWriter(os.Stdout)

	strs := make(chan *string, 100)

	go inputter(rs, strs)

	str := <-strs
	i := len(*str)-1
	last := (*str)[i]

	tot := int64(0)

	if (last - '0') % 4 == 0 {
		tot++
	}

	ctr := int64(0)

	for i := len(*str)-2; i >= 0; i-- {
		ths := (*str)[i] - '0'
		x := ths * 10 + last
		if x % 4 == 0{
			ctr++
		}
		tot += ctr
		last = ths
		if last % 4 == 0 {
			tot++
		}
	}

	ws.WriteString(fmt.Sprint(tot))

	ws.Flush()
}

package main

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

func main() {
	fsc := NewFastScanner()
	S := fsc.Next()
	N := len(S)
	var result int64
	result = 0
	for i := 0; i < N; i++ {
		var res int
		res, _ = strconv.Atoi(S[i : i+1])
		if res%4 == 0 {
			result++
		}
		if i+1 < N {
			res, _ = strconv.Atoi(S[i : i+2])
			if res%4 == 0 {
				result += int64(i + 1)
			}
		}
	}
	fmt.Println(result)
}

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

//Max,Min
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
}

//Gcd
func IntGcd(a, b int) int {
	if a < b {
		b, a = a, b
	}
	if b == 0 {
		return a
	}
	return IntGcd(b, a%b)
}
func Int64Gcd(a, b int64) int64 {
	if a < b {
		b, a = a, b
	}
	if b == 0 {
		return a
	}
	return Int64Gcd(b, a%b)
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, _ := in.ReadBytes('\n')
	r := uint64(0)
	if n[0]%4 == 0 {
		r++
	}
	for i := 1; i < len(n) && n[i] != '\r'; i++ {
		if n[i]%4 == 0 {
			r++
		}
		s := (n[i-1]-'0')*10 + (n[i] - '0')
		if s%4 == 0 {
			r += uint64(i)
		}
	}
	out.WriteString(strconv.FormatUint(r, 10) + "\n")
}

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()
	s := reader.NextString()
	res := int64(0)
	for i := range s {
		if (s[i] - '0') % 4 == 0 {
			res++
		}
		if i > 0 {
			if (((s[i-1] - '0') * 10) + (s[i] - '0')) % 4 == 0 {
				res += int64(i)
			}
		}
	}
	writer.Printf("%d\n", res)
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, _ := in.ReadBytes('\n')
	r := uint64(0)
	if n[0]%4 == 0 {
		r++
	}
	for i := 1; i < len(n); i++ {
		if n[i]%4 == 0 {
			r++
		}
		s := (n[i-1]-'0')*10 + (n[i] - '0')
		if s%4 == 0 {
			r += uint64(i)
		}
	}
	out.WriteString(strconv.FormatUint(r, 10) + "\n")
}