Stanley has decided to buy a new desktop PC made by the company "Monoblock", and to solve captcha on their website, he needs to solve the following task.The awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an array   $$$[1, 1, 1]$$$ is $$$1$$$;  $$$[5, 7]$$$ is $$$2$$$, as it could be split into blocks $$$[5]$$$ and $$$[7]$$$;  $$$[1, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9]$$$ is 3, as it could be split into blocks $$$[1]$$$, $$$[7, 7, 7, 7, 7, 7, 7]$$$, and $$$[9, 9, 9, 9, 9, 9, 9, 9, 9]$$$. You are given an array $$$a$$$ of length $$$n$$$. There are $$$m$$$ queries of two integers $$$i$$$, $$$x$$$. A query $$$i$$$, $$$x$$$ means that from now on the $$$i$$$-th element of the array $$$a$$$ is equal to $$$x$$$.After each query print the sum of awesomeness values among all subsegments of array $$$a$$$. In other words, after each query you need to calculate $$$$$$\sum\limits_{l = 1}^n \sum\limits_{r = l}^n g(l, r),$$$$$$ where $$$g(l, r)$$$ is the awesomeness of the array $$$b = [a_l, a_{l + 1}, \ldots, a_r]$$$.

In the first line you are given with two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$. In the next $$$m$$$ lines you are given the descriptions of queries. Each line contains two integers $$$i$$$ and $$$x$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq x \leq 10^9$$$).

Print the answer to each query on a new line.

package main

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

var n, m, pos, x int
var a []int
var dp, sum []int64

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	fmt.Fscan(in, &n, &m)
	a = make([]int, n+2)
	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &a[i])
	}
	dp = make([]int64, n+1)
	sum = make([]int64, n+1)
	dp[1], sum[1] = 0, 1
	ans := int64(1)
	for i := 2; i <= n; i++ {
		sum[i] = int64(i)
		if a[i] == a[i-1] {
			dp[i] = dp[i-1]
			sum[i] += dp[i-1]
		} else {
			sum[i] += sum[i-1]
			dp[i] = sum[i-1]
		}
		ans += sum[i]
	}
	for i := 1; i <= m; i++ {
		fmt.Fscan(in, &pos, &x)
		if a[pos] == x {
			fmt.Fprintln(out, ans)
			continue
		}
		if a[pos-1] == a[pos] {
			ans += int64(pos-1) * int64(n-pos+1)
		} else if a[pos-1] != a[pos] && a[pos-1] == x {
			ans -= int64(pos-1) * int64(n-pos+1)
		}
		if a[pos+1] == a[pos] {
			ans += int64(pos) * int64(n-pos)
		} else if a[pos+1] != a[pos] && a[pos+1] == x {
			ans -= int64(pos) * int64(n-pos)
		}
		a[pos] = x
		fmt.Fprintln(out, ans)
	}
}

package main

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

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

	var n, m int64
	fmt.Fscan(in, &n, &m)

	aa := make([]int64, n+2)
	for i := int64(1); i <= n; i++ {
		fmt.Fscan(in, &aa[i])
	}

	// number of segments n*(n+1)/2
	// score: n*(n+1)*(n+2)/6

	var tot int64
	for i := int64(1); i <= n; i++ {
		if aa[i] != aa[i+1] {
			tot += (n - (i + 1) + 1) * i
		}
	}

	for i := int64(0); i < m; i++ {
		var k, x int64
		fmt.Fscan(in, &k, &x)

		if aa[k] != aa[k-1] {
			tot -= int64((n - k + 1) * (k - 1))
		}
		if aa[k] != aa[k+1] {
			tot -= int64((n - (k + 1) + 1) * k)
		}
		aa[k] = x
		if aa[k] != aa[k-1] {
			tot += int64((n - k + 1) * (k - 1))
		}
		if aa[k] != aa[k+1] {
			tot += int64((n - (k + 1) + 1) * k)
		}
		fmt.Fprintln(out, tot+int64(n*(n+1)/2))
	}
}

package main

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

type pair struct {
	val int
	start int
	end int
}

func readArray(reader io.Reader, n int) []int {
	var items = make([]int, n)
	for i := 0; i < n; i ++ {
		fmt.Fscan(reader, &items[i])
	}

	return items
}

func insert(a []pair, index int, value pair) []pair {
    if len(a) == index { // nil or empty slice or after last element
        return append(a, value)
    }
    a = append(a[:index+1], a[index:]...) // index < len(a)
    a[index] = value
    return a
}

func remove(slice []pair, s int) []pair {
    return append(slice[:s], slice[s+1:]...)
}

func getSum(items []int) int64 {
	var sum int64 = 0
	for i, val := range items {
		if i > 0 && items[i - 1] == val {
			sum += int64(len(items) - i)
		} else {
			sum += int64(i) * int64(len(items) - i) + int64(len(items) - i)
		}
	}

	return sum
}

func main() {
	// f, _ := os.Open("input.txt")
	var reader = bufio.NewReader(os.Stdin)
	// var reader = bufio.NewReader(f)
	var n, m int
	fmt.Fscan(reader, &n)
	fmt.Fscan(reader, &m)
	var items = readArray(reader, n)
	var sum = getSum(items)
	for i := 0; i < m; i++ {
		var i, x int
		fmt.Fscan(reader, &i)
		fmt.Fscan(reader, &x)
		i--
		if(items[i] == x) {
			fmt.Println(sum)
			continue
		}

		if i > 0 {
			if items[i - 1] == items[i] {
				sum += int64(i) * int64(len(items) - i)
			} else {
				if items[i - 1] == x {
					sum -= int64(i) * int64(len(items) - i)
				}
			}
		}
		if i < n - 1 {
			if items[i] == items[i + 1] {
				sum += int64(i + 1) * int64(len(items) - i - 1)
			} else {
				if items[i + 1] == x {
					sum -= int64(i + 1) * int64(len(items) - i - 1)
				}
			}
		}
		items[i] = x

		fmt.Println(sum)
	}
}

package main

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

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

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

func Solve(reader *bufio.Reader) {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	wr := bufio.NewWriter(os.Stdout)
	defer wr.Flush()

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	m, _ := strconv.Atoi(scanner.Text())
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		arr[i], _ = strconv.Atoi(scanner.Text())
	}
	tmpasm := make([]int, n)
	tmpSumasm := make([]int, n)
	tmpasm[0] = 1
	sumAsm := 1
	tmpSumasm[0] = 1
	last := arr[0]
	for i := 1; i < n; i++ {
		if last != arr[i] {
			tmpasm[i] = tmpasm[i-1] + 1
		} else {
			tmpasm[i] = tmpasm[i-1]
		}
		last = arr[i]
		sumAsm += tmpasm[i]
		tmpSumasm[i] = sumAsm
	}
	asm := sumAsm
	for i := 0; i < n-1; i++ {
		asm -= (n - 1 - i) * tmpasm[i]
		asm -= tmpSumasm[i]
		if arr[i] == arr[i+1] {
			asm += (n - 1 - i)
		}
		asm += sumAsm
	}

	for i_ := 0; i_ < m; i_++ {
		scanner.Scan()
		i, _ := strconv.Atoi(scanner.Text())
		i--
		scanner.Scan()
		x, _ := strconv.Atoi(scanner.Text())
		if arr[i] == x {
			wr.WriteString(strconv.Itoa(asm) + "\n")
			continue
		}

		diffLeft := 0
		if i > 0 && arr[i-1] != arr[i] && arr[i-1] == x {
			diffLeft = -1
		} else if i > 0 && arr[i-1] == arr[i] && arr[i-1] != x {
			diffLeft = 1
		}
		diffRight := 0
		if i < n-1 && arr[i+1] != arr[i] && arr[i+1] == x {
			diffRight = -1
		} else if i < n-1 && arr[i+1] == arr[i] && arr[i+1] != x {
			diffRight = 1
		}

		arr[i] = x

		leftCnt := (n - i) * i
		rightCnt := (i + 1) * (n - i - 1)
		asm += leftCnt * diffLeft
		asm += rightCnt * diffRight
		wr.WriteString(strconv.Itoa(asm) + "\n")
	}
}

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

package main

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

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

func qwq() {
	var n, m int64
	fmt.Fscan(in, &n, &m)
	a := make([]int64, n+1)
	for i := int64(1); i <= n; i++ {
		fmt.Fscan(in, &a[i])
	}
	var sum int64 = (1 + n) * n / 2
	for i := int64(1); i+1 <= n; i++ {
		if a[i] != a[i+1] {
			sum += i * (n - i)
		}
	}
	for ; m > 0; m-- {
		var p, x int64
		fmt.Fscan(in, &p, &x)
		if p > 1 {
			if a[p] == a[p-1] && a[p-1] != x {
				sum += (p - 1) * (n - p + 1)
			}
			if a[p] != a[p-1] && a[p-1] == x {
				sum -= (p - 1) * (n - p + 1)
			}
		}
		if p+1 <= n {
			if a[p] == a[p+1] && a[p+1] != x {
				sum += p * (n - p)

			}
			if a[p] != a[p+1] && a[p+1] == x {
				sum -= p * (n - p)
			}
		}
		a[p] = x
		fmt.Fprintln(out, sum)
	}
}

func main() {
	defer out.Flush()
	q := 1
	// fmt.Fscanln(in, &q)
	for ; q > 0; q-- {
		qwq()
	}
}

package main

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

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

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

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

func getSum(n int64, a []int) int64 {
	s := int64(1)
	c := int64(1)
	for i := int64(1); i < n; i++ {
		if a[i] != a[i-1] {
			c += i + 1
		} else {
			c++
		}
		s += c
	}
	return s
}

func do(n int64, m int, a []int, b [][2]int) []int64 {
	s := getSum(n, a)
	r := make([]int64, m)
	same := func(i int64) (bool, bool) {
		return i > 0 && a[i] == a[i-1], i < n-1 && a[i] == a[i+1]
	}
	for j, b := range b {
		i, v := int64(b[0]-1), b[1]
		p0, q0 := same(i)
		a[i] = v
		p1, q1 := same(i)
		switch {
		case p0 && !q0 && !p1 && !q1:
			r[j] = s + i*(n-i)
		case !p0 && !q0 && p1 && !q1:
			r[j] = s - i*(n-i)
		case p0 && q0 && !p1 && !q1:
			r[j] = s + i + (1+2*i)*(n-(i+1))
		case !p0 && !q0 && p1 && q1:
			r[j] = s - i - (1+2*i)*(n-(i+1))
		case !p0 && q0 && !p1 && !q1:
			r[j] = s + (i+1)*(n-(i+1))
		case !p0 && !q0 && !p1 && q1:
			r[j] = s - (i+1)*(n-(i+1))
		case !p0 && q0 && p1 && !q1:
			r[j] = s - i + (n - (i + 1))
		case p0 && !q0 && !p1 && q1:
			r[j] = s + i - (n - (i + 1))
		default:
			r[j] = s
		}
		s = r[j]
	}
	return r
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var n, m int
	fmt.Fscan(in, &n, &m)
	a := make([]int, n+5)
	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &a[i])
	}
	pre := make([]int, n+5)
	for i := 1; i <= n; i++ {
		if i == 1 {
			pre[i] = 1
			continue
		}
		if a[i] == a[i-1] {
			pre[i] = pre[i-1] + 1
		} else {
			pre[i] = 1 + pre[i-1] + (i - 1)
		}
	}
	ans := 0
	for i := 1; i <= n; i++ {
		ans += pre[i]
	}
	for i := 1; i <= m; i++ {
		var p, x int
		fmt.Fscan(in, &p, &x)
		if p-1 >= 1 && a[p-1] == x && a[p] != a[p-1] {

			ans -= (p - 1) * (n - p + 1)
		}
		if p+1 <= n && a[p+1] == x && a[p] != a[p+1] {

			ans -= (n - p) * p
		}
		if p-1 >= 1 && a[p-1] != x && a[p] == a[p-1] {

			ans += (p - 1) * (n - p + 1)
		}
		if p+1 <= n && a[p+1] != x && a[p] == a[p+1] {
			ans += (n - p) * p
		}
		fmt.Fprintln(out, ans)
		a[p] = x
	}
}

package main

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

var n, m, pos, x int
var a []int
var dp, sum []int64

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	fmt.Fscan(in, &n, &m)
	a = make([]int, n+1)
	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &a[i])
	}
	dp = make([]int64, n+1)
	sum = make([]int64, n+1)
	dp[1], sum[1] = 0, 1
	ans := int64(1)
	for i := 2; i <= n; i++ {
		sum[i] = int64(i)
		if a[i] == a[i-1] {
			dp[i] = dp[i-1]
			sum[i] += dp[i-1]
		} else {
			sum[i] += sum[i-1]
			dp[i] = sum[i-1]
		}
		ans += sum[i]
	}
	for i := 1; i <= m; i++ {
		fmt.Fscan(in, &pos, &x)
		if a[pos] == x {
			fmt.Fprintln(out, ans)
			continue
		}
		if pos > 1 {
			if a[pos-1] == a[pos] {
				ans += int64((pos - 1) * (n - pos + 1))
			} else if a[pos-1] != a[pos] && a[pos-1] == x {
				ans -= int64((pos - 1) * (n - pos + 1))
			}
		}
		if pos < n {
			if a[pos+1] == a[pos] {
				ans += int64(pos * (n - pos))
			} else if a[pos+1] != a[pos] && a[pos+1] == x {
				ans -= int64(pos * (n - pos))
			}
		}
		a[pos] = x
		fmt.Fprintln(out, ans)
	}
}

package main

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

var n, m, pos, x int
var a []int
var dp, sum []int64

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	fmt.Fscan(in, &n, &m)
	a = make([]int, n+1)
	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &a[i])
	}
	dp = make([]int64, n+1)
	sum = make([]int64, n+1)
	dp[1], sum[1] = 0, 1
	ans := int64(1)
	for i := 2; i <= n; i++ {
		sum[i] = int64(i)
		if a[i] == a[i-1] {
			dp[i] = dp[i-1]
			sum[i] += dp[i-2]
		} else {
			dp[i] = sum[i-1]
			sum[i] += sum[i-1]
		}
		ans += sum[i]
	}
	for i := 1; i <= m; i++ {
		fmt.Fscan(in, &pos, &x)
		if a[pos] == x {
			fmt.Fprintln(out, ans)
			continue
		}
		if pos > 1 {
			if a[pos-1] == a[pos] {
				ans += int64((pos - 1) * (n - pos + 1))
			} else if a[pos-1] != a[pos] && a[pos-1] == x {
				ans -= int64((pos - 1) * (n - pos + 1))
			}
		}
		if pos < n {
			if a[pos+1] == a[pos] {
				ans += int64(pos * (n - pos))
			} else if a[pos+1] != a[pos] && a[pos+1] == x {
				ans -= int64(pos * (n - pos))
			}
		}
		a[pos] = x
		fmt.Fprintln(out, ans)
	}
}

package main

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

var n, m, pos, x int
var a []int
var dp []int64

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	fmt.Fscan(in, &n, &m)
	a = make([]int, n+1)
	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &a[i])
	}
	dp = make([]int64, n+1)
	dp[1] = 1
	ans := int64(1)
	for i := 2; i <= n; i++ {
		dp[i] = int64(i)
		if a[i] == a[i-1] {
			dp[i] += dp[i-2]
		} else {
			dp[i] += dp[i-1]
		}
		ans += dp[i]
	}
	for i := 1; i <= m; i++ {
		fmt.Fscan(in, &pos, &x)
		if a[pos] == x {
			fmt.Fprintln(out, ans)
			continue
		}
		if pos > 1 {
			if a[pos-1] == a[pos] {
				ans += int64((pos - 1) * (n - pos + 1))
			} else if a[pos-1] != a[pos] && a[pos-1] == x {
				ans -= int64((pos - 1) * (n - pos + 1))
			}
		}
		if pos < n {
			if a[pos+1] == a[pos] {
				ans += int64(pos * (n - pos))
			} else if a[pos+1] != a[pos] && a[pos+1] == x {
				ans -= int64(pos * (n - pos))
			}
		}
		a[pos] = x
		fmt.Fprintln(out, ans)
	}
}

package main

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

var n, m, pos, x int
var a []int
var dp []int64

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	fmt.Fscan(in, &n, &m)
	a = make([]int, n+1)
	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &a[i])
	}
	dp = make([]int64, n+1)
	dp[1] = 1
	ans := int64(1)
	for i := 2; i <= n; i++ {
		dp[i] = int64(i)
		if a[i] == a[i-1] {
			dp[i] += dp[i-2]
		} else {
			dp[i] += dp[i-1]
		}
		ans += dp[i]
	}
	for i := 1; i <= m; i++ {
		fmt.Fscan(in, &pos, &x)
		if a[pos] == x {
			continue
		}
		if pos > 1 {
			if a[pos-1] == a[pos] {
				ans += int64((pos - 1) * (n - pos + 1))
			} else if a[pos-1] != a[pos] && a[pos-1] == x {
				ans -= int64((pos - 1) * (n - pos + 1))
			}
		}
		if pos < n {
			if a[pos+1] == a[pos] {
				ans += int64(pos * (n - pos))
			} else if a[pos+1] != a[pos] && a[pos+1] == x {
				ans -= int64(pos * (n - pos))
			}
		}
		a[pos] = x
		fmt.Fprintln(out, ans)
	}
}

/*
    1 2 2 4 2
    (1) * 1          1
    (1) * 2 + 1      3
	(1) * 3 + 1      4
	(1) * 4 + 4      8
    (1) * 5 + 8     13

   2 2 3
   1
   2
   3 + 2      8

   1 2 3
   1 + 2 + 3 + 1 + 2 + 1 = 10

   1 2 1  = 10
   1 1 1  = 10 - 2 - 2

   1 2 3 3 4 5
*/

package main

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

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

	var n, m int
	fmt.Fscan(in, &n, &m)

	aa := make([]int, n+2)
	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &aa[i])
	}

	// number of segments n*(n+1)/2
	// score: n*(n+1)*(n+2)/6

	var tot int64
	for i := 1; i <= n; i++ {
		if aa[i] != aa[i+1] {
			tot += int64((n - (i + 1) + 1) * i)
		}
	}

	for i := 0; i < m; i++ {
		var k, x int
		fmt.Fscan(in, &k, &x)

		if aa[k] != aa[k-1] {
			tot -= int64((n - k + 1) * (k - 1))
		}
		if aa[k] != aa[k+1] {
			tot -= int64((n - (k + 1) + 1) * k)
		}
		aa[k] = x
		if aa[k] != aa[k-1] {
			tot += int64((n - k + 1) * (k - 1))
		}
		if aa[k] != aa[k+1] {
			tot += int64((n - (k + 1) + 1) * k)
		}
		fmt.Fprintln(out, tot+int64(n*(n+1)/2))
	}
}

package main

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

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

	var n, m int
	fmt.Fscan(in, &n, &m)

	aa := make([]int, n+2)
	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &aa[i])
	}

	// number of segments n*(n+1)/2
	// score: n*(n+1)*(n+2)/6

	var tot int
	for i := 1; i <= n; i++ {
		if aa[i] != aa[i+1] {
			tot += (n - (i + 1) + 1) * i
		}
	}

	for i := 0; i < m; i++ {
		var k, x int
		fmt.Fscan(in, &k, &x)

		if aa[k] != aa[k-1] {
			tot -= (n - k + 1) * (k - 1)
		}
		if aa[k] != aa[k+1] {
			tot -= (n - (k + 1) + 1) * k
		}
		aa[k] = x
		if aa[k] != aa[k-1] {
			tot += (n - k + 1) * (k - 1)
		}
		if aa[k] != aa[k+1] {
			tot += (n - (k + 1) + 1) * k
		}
		fmt.Fprintln(out, tot+n*(n+1)/2)
	}
}

package main

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

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

func qwq() {
	var n, m int64
	fmt.Fscan(in, &n, &m)
	a := make([]int64, n+1)
	for i := int64(1); i <= n; i++ {
		fmt.Fscan(in, &a[i])
	}
	var sum int64 = (1 + n) * n / 2
	for i := int64(1); i+1 <= n; i++ {
		if a[i] != a[i+1] {
			sum += i * (n - i)
		}
	}
	for ; m > 0; m-- {
		var p, x int64
		fmt.Fscan(in, &p, &x)
		if p > 1 {
			if a[p] == a[p-1] && a[p] != x {
				sum += (p - 1) * (n - p + 1)
			}
			if a[p] != a[p-1] && a[p-1] == x {
				sum -= (p - 1) * (n - p + 1)
			}
		}
		if p+1 <= n {
			if a[p] == a[p+1] && a[p] != x {
				sum += p * (n - p)

			}
			if a[p] != a[p-1] && a[p+1] == x {
				sum -= p * (n - p)
			}
		}
		a[p] = x
		fmt.Fprintln(out, sum)
	}
}

func main() {
	defer out.Flush()
	q := 1
	// fmt.Fscanln(in, &q)
	for ; q > 0; q-- {
		qwq()
	}
}

package main

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

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

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

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

func do(n, m int, a []int, b [][2]int) []int {
	s := 1
	c := 1
	for i := 1; i < n; i++ {
		if a[i] != a[i-1] {
			c += i + 1
		} else {
			c++
		}
		s += c
	}
	r := make([]int, m)
	same := func(i int) (bool, bool) {
		return i > 0 && a[i] == a[i-1], i < n-1 && a[i] == a[i+1]
	}
	for j, b := range b {
		i, v := b[0]-1, b[1]
		p0, q0 := same(i)
		a[i] = v
		p1, q1 := same(i)
		switch {
		case p0 && !q0 && !p1 && !q1:
			r[j] = s + i*(n-i)
		case !p0 && !q0 && p1 && !q1:
			r[j] = s - i*(n-i)
		case p0 && q0 && !p1 && !q1:
			r[j] = s + i + (1+2*i)*(n-(i+1))
		case !p0 && !q0 && p1 && q1:
			r[j] = s - i - (1+2*i)*(n-(i+1))
		case !p0 && q0 && !p1 && !q1:
			r[j] = s + (i+1)*(n-(i+1))
		case !p0 && !q0 && !p1 && q1:
			r[j] = s - (i+1)*(n-(i+1))
		case !p0 && q0 && p1 && !q1:
			r[j] = s - i + (n - (i + 1))
		case p0 && !q0 && !p1 && q1:
			r[j] = s + i - (n - (i + 1))
		default:
			r[j] = s
		}
		s = r[j]
	}
	return r
}


Cirno gave AquaMoon a chessboard of size $$$1 \times n$$$. Its cells are numbered with integers from $$$1$$$ to $$$n$$$ from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied.In each operation, AquaMoon can choose a cell $$$i$$$ with a pawn, and do either of the following (if possible):   Move pawn from it to the $$$(i+2)$$$-th cell, if $$$i+2 \leq n$$$ and the $$$(i+1)$$$-th cell is occupied and the $$$(i+2)$$$-th cell is unoccupied.  Move pawn from it to the $$$(i-2)$$$-th cell, if $$$i-2 \geq 1$$$ and the $$$(i-1)$$$-th cell is occupied and the $$$(i-2)$$$-th cell is unoccupied. You are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo $$$998\,244\,353$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the size of the chessboard. The second line contains a string of $$$n$$$ characters, consists of characters "0" and "1". If the $$$i$$$-th character is "1", the $$$i$$$-th cell is initially occupied; otherwise, the $$$i$$$-th cell is initially unoccupied. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the number of states that reachable from the initial state with some sequence of operations modulo $$$998\,244\,353$$$.

NoteIn the first test case the strings "1100", "0110" and "0011" are reachable from the initial state with some sequence of operations.

package main

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

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

	var T, n int
	var s string
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &s)
		x, y := strings.Count(s, "11"), strings.Count(s, "0")
		x += y
		num, den := int64(1), int64(1)
		for i := 0; i < y; i++ {
			num = num * int64(x-i) % mod
			den = den * int64(i+1) % mod
		}
		Fprintln(out, num*pow(den, mod-2)%mod)
	}
}

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

package main

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

const (
	MAXN = 100005
	MOD  = 998244353
)

func pow(a int64, b int) int64 {
	if b == 0 {
		return 1
	} else if b%2 == 1 {
		return a * pow(a, b-1) % MOD
	} else {
		tmp := pow(a, b/2)
		return tmp * tmp % MOD
	}
}

func main() {
	sc := NewScanner()
	wr := bufio.NewWriter(os.Stdout)
	defer wr.Flush()

	fact := make([]int64, MAXN)
	fact[0] = 1
	for i := int64(1); i < MAXN; i++ {
		fact[i] = (i * fact[i-1]) % MOD
	}

	TC := sc.NextInt()
	for tc := 0; tc < TC; tc++ {
		_ = sc.NextInt()
		chess := sc.Next()

		cntG1 := 0
		cntSeq1 := 0
		cnt0 := 0
		for _, c := range chess {
			if c == '0' {
				cnt0++
				cntSeq1 = 0
			} else {
				cntSeq1++
				if cntSeq1 == 2 {
					cntG1++
					cntSeq1 = 0
				}
			}
		}

		ans := fact[cntG1+cnt0] * pow(fact[cntG1], MOD-2) % MOD * pow(fact[cnt0], MOD-2) % MOD
		fmt.Fprintln(wr, ans)
	}

}

type Scanner struct {
	bScanner *bufio.Scanner
}

func NewScanner() *Scanner {
	bScanner := bufio.NewScanner(os.Stdin)
	bScanner.Split(bufio.ScanWords)
	bScanner.Buffer([]byte{}, math.MaxInt32)
	return &Scanner{
		bScanner,
	}
}
func (s *Scanner) Next() string {
	s.bScanner.Scan()
	return s.bScanner.Text()
}
func (s *Scanner) NextInt() int {
	s.bScanner.Scan()
	res, err := strconv.Atoi(s.bScanner.Text())
	if err != nil {
		panic(err)
	}
	return res
}
func (s *Scanner) NextInt64() int64 {
	s.bScanner.Scan()
	res, err := strconv.ParseInt(s.bScanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}
func (s *Scanner) NextFloat() float64 {
	s.bScanner.Scan()
	res, err := strconv.ParseFloat(s.bScanner.Text(), 64)
	if err != nil {
		panic(err)
	}
	return res
}
func (s *Scanner) NextInts(N int) []int {
	res := make([]int, N)
	for i := 0; i < N; i++ {
		res[i] = s.NextInt()
	}
	return res
}
func (s *Scanner) NextInt64s(N int) []int64 {
	res := make([]int64, N)
	for i := 0; i < N; i++ {
		res[i] = s.NextInt64()
	}
	return res
}
func Min(num int, nums ...int) int {
	ans := num
	for _, num := range nums {
		if num < ans {
			ans = num
		}
	}
	return ans
}
func Max(num int, nums ...int) int {
	ans := num
	for _, num := range nums {
		if num > ans {
			ans = num
		}
	}
	return ans
}

func InitInts1D(n int, val int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = val
	}
	return res
}
func InitInts2D(n, m int, val int) [][]int {
	res := make([][]int, n)
	for i := 0; i < n; i++ {
		res[i] = InitInts1D(m, val)
	}
	return res
}
func InitInts3D(n, m, k int, val int) [][][]int {
	res := make([][][]int, n)
	for i := 0; i < n; i++ {
		res[i] = InitInts2D(m, k, val)
	}
	return res
}

type StepState struct {
	step, dist int
}
type PriorityQueue []*StepState

func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
	if pq[i].step != pq[j].step {
		return pq[i].step < pq[j].step
	}
	return pq[i].dist < pq[j].dist
}
func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}
func (pq *PriorityQueue) Push(x interface{}) {
	item := x.(*StepState)
	*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}


And now the numerous qualifying tournaments for one of the most prestigious Russian contests Russian Codec Cup are over. All n participants who have made it to the finals found themselves in a huge m-floored 108-star hotel. Of course the first thought to come in a place like this is "How about checking out the elevator?".The hotel's elevator moves between floors according to one never changing scheme. Initially (at the moment of time 0) the elevator is located on the 1-st floor, then it moves to the 2-nd floor, then — to the 3-rd floor and so on until it reaches the m-th floor. After that the elevator moves to floor m - 1, then to floor m - 2, and so on until it reaches the first floor. This process is repeated infinitely. We know that the elevator has infinite capacity; we also know that on every floor people get on the elevator immediately. Moving between the floors takes a unit of time.For each of the n participant you are given si, which represents the floor where the i-th participant starts, fi, which represents the floor the i-th participant wants to reach, and ti, which represents the time when the i-th participant starts on the floor si.For each participant print the minimum time of his/her arrival to the floor fi. If the elevator stops on the floor si at the time ti, then the i-th participant can enter the elevator immediately. If the participant starts on the floor si and that's the floor he wanted to reach initially (si = fi), then the time of arrival to the floor fi for this participant is considered equal to ti.

The first line contains two space-separated integers n and m (1 ≤ n ≤ 105, 2 ≤ m ≤ 108).  Next n lines contain information about the participants in the form of three space-separated integers si fi ti (1 ≤ si, fi ≤ m, 0 ≤ ti ≤ 108), described in the problem statement.

Print n lines each containing one integer — the time of the arrival for each participant to the required floor.

NoteLet's consider the first sample. The first participant starts at floor s = 2 by the time equal to t = 3. To get to the floor f = 4, he has to wait until the time equals 7, that's the time when the elevator will go upwards for the second time. Then the first participant should get on the elevator and go two floors up. In this case the first participant gets to the floor f at time equal to 9. The second participant starts at the time t = 0 on the floor s = 1, enters the elevator immediately, and arrives to the floor f = 2. The third participant doesn't wait for the elevator, because he needs to arrive to the same floor where he starts.

package main

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

var scanner *bufio.Scanner

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

var numFloors, numPeople int

func travel(direction, a, b int) (distance, newDirection int) {
  newDirection = direction
  if direction == 1 {
    if a <= b {
      distance = b - a
    } else {
      distance = 2 * numFloors - a - b
      newDirection = -1
    }
  } else {
    if a >= b {
      distance = a - b
    } else {
      distance = a + b - 2
      newDirection = 1
    }
  }
  return
}

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

  numPeople, numFloors = getI(), getI()
  for i := 0; i < numPeople; i++ {
    waiting, target, time := getI(), getI(), getI()
    if waiting == target {
      writer.WriteString(fmt.Sprintf("%d\n", time))
      continue
    }
    floor := 1 + time % (2 * (numFloors - 1))
    direction := 1
    if floor >= numFloors {
      floor = 2 * numFloors - floor
      direction = -1
    }
    //fmt.Printf("time %d, floor %d\n", time, floor)
    distance, direction := travel(direction, floor, waiting)
    time += distance
    //fmt.Printf("time %d, floor %d\n", time, waiting)
    distance, direction = travel(direction, waiting, target)
    time += distance
    //fmt.Printf("time %d, floor %d\n", time, target)
    //fmt.Println();
    writer.WriteString(fmt.Sprintf("%d\n", time))
  }
}

package main

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

var scanner *bufio.Scanner

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

var numFloors, numPeople int

func travel(direction, a, b int) (distance, newDirection int) {
  if direction == 1 {
    if a <= b {
      distance = b - a
    } else {
      distance = 2 * numFloors - a - b
      newDirection = -1
    }
  } else {
    if a >= b {
      distance = a - b
    } else {
      distance = a + b - 2
      newDirection = 1
    }
  }
  return
}

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

  numPeople, numFloors = getI(), getI()
  for i := 0; i < numPeople; i++ {
    waiting, target, time := getI(), getI(), getI()
    if waiting == target {
      writer.WriteString(fmt.Sprintf("%d\n", time))
      continue
    }
    floor := 1 + time % (2 * (numFloors - 1))
    direction := 1
    if floor >= numFloors {
      floor = 2 * numFloors - floor
      direction = -1
    }
    //fmt.Printf("time %d, floor %d\n", time, floor)
    distance, direction := travel(direction, floor, waiting)
    time += distance
    //fmt.Printf("time %d, floor %d\n", time, waiting)
    distance, direction = travel(direction, waiting, target)
    time += distance
    //fmt.Printf("time %d, floor %d\n", time, target)
    //fmt.Println();
    writer.WriteString(fmt.Sprintf("%d\n", time))
  }
}


Vasya has a tree consisting of $$$n$$$ vertices with root in vertex $$$1$$$. At first all vertices has $$$0$$$ written on it.Let $$$d(i, j)$$$ be the distance between vertices $$$i$$$ and $$$j$$$, i.e. number of edges in the shortest path from $$$i$$$ to $$$j$$$. Also, let's denote $$$k$$$-subtree of vertex $$$x$$$ — set of vertices $$$y$$$ such that next two conditions are met:   $$$x$$$ is the ancestor of $$$y$$$ (each vertex is the ancestor of itself);  $$$d(x, y) \le k$$$. Vasya needs you to process $$$m$$$ queries. The $$$i$$$-th query is a triple $$$v_i$$$, $$$d_i$$$ and $$$x_i$$$. For each query Vasya adds value $$$x_i$$$ to each vertex from $$$d_i$$$-subtree of $$$v_i$$$.Report to Vasya all values, written on vertices of the tree after processing all queries.

The first line contains single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — number of vertices in the tree. Each of next $$$n - 1$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$) — edge between vertices $$$x$$$ and $$$y$$$. It is guarantied that given graph is a tree. Next line contains single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$) — number of queries. Each of next $$$m$$$ lines contains three integers $$$v_i$$$, $$$d_i$$$, $$$x_i$$$ ($$$1 \le v_i \le n$$$, $$$0 \le d_i \le 10^9$$$, $$$1 \le x_i \le 10^9$$$) — description of the $$$i$$$-th query.

Print $$$n$$$ integers. The $$$i$$$-th integers is the value, written in the $$$i$$$-th vertex after processing all queries.

NoteIn the first exapmle initial values in vertices are $$$0, 0, 0, 0, 0$$$. After the first query values will be equal to $$$1, 1, 1, 0, 0$$$. After the second query values will be equal to $$$1, 11, 1, 0, 0$$$. After the third query values will be equal to $$$1, 11, 1, 100, 0$$$.

package main

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

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

	var n, v, w, q, d int
	var x int64
	Fscan(in, &n)
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	tin := make([]int, n)
	tout := make([]int, n)
	depT := make([][]int, n)
	dep := make([]int, n)
	t := 0
	var f func(v, fa, d int)
	f = func(v, fa, d int) {
		t++
		tin[v] = t
		depT[d] = append(depT[d], t)
		dep[v] = d
		for _, w := range g[v] {
			if w != fa {
				f(w, v, d+1)
			}
		}
		tout[v] = t
	}
	f(0, -1, 0)
	add := make([]int64, n)
	diff := make([][]int64, n)
	for i, row := range depT {
		diff[i] = make([]int64, len(row)+1)
	}
	for Fscan(in, &q); q > 0; q-- {
		Fscan(in, &v, &d, &x)
		v--
		add[v] += x
		if d += dep[v] + 1; d < n {
			l := sort.SearchInts(depT[d], tin[v])
			r := sort.SearchInts(depT[d], tout[v]+1)
			diff[d][l] += x
			diff[d][r] -= x
		}
	}

	ans := make([]interface{}, n)
	var f2 func(v, fa, d int, s int64)
	f2 = func(v, fa, d int, s int64) {
		s += add[v] - diff[d][0]
		diff[d][1] += diff[d][0]
		diff[d] = diff[d][1:]
		ans[v] = s
		for _, w := range g[v] {
			if w != fa {
				f2(w, v, d+1, s)
			}
		}
	}
	f2(0, -1, 0, 0)
	Fprintln(out, ans...)
}

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

package main

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

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

	var n, v, w, q, d int
	var x int64
	Fscan(in, &n)
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	type info struct{ tin, tout, d int }
	is := make([]info, n)
	depT := make([][]int, n)
	t := 0
	var f func(v, fa, d int)
	f = func(v, fa, d int) {
		t++
		is[v].tin = t
		is[v].d = d
		depT[d] = append(depT[d], t)
		for _, w := range g[v] {
			if w != fa {
				f(w, v, d+1)
			}
		}
		is[v].tout = t
	}
	f(0, -1, 0)
	add := make([]int64, n)
	diff := make([][]int64, n)
	for i, row := range depT {
		diff[i] = make([]int64, len(row)+1)
	}
	for Fscan(in, &q); q > 0; q-- {
		Fscan(in, &v, &d, &x)
		v--
		add[v] += x
		info := is[v]
		if d += info.d + 1; d < n {
			l := sort.SearchInts(depT[d], info.tin)
			r := sort.SearchInts(depT[d], info.tout+1)
			diff[d][l] += x
			diff[d][r] -= x
		}
	}

	ans := make([]interface{}, n)
	var f2 func(v, fa, d int, s int64)
	f2 = func(v, fa, d int, s int64) {
		s += add[v] - diff[d][0]
		diff[d][1] += diff[d][0]
		diff[d] = diff[d][1:]
		ans[v] = s
		for _, w := range g[v] {
			if w != fa {
				f2(w, v, d+1, s)
			}
		}
	}
	f2(0, -1, 0, 0)
	Fprintln(out, ans...)
}

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

package main

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

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

	var n, v, w, q, d, x int
	Fscan(in, &n)
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	tin := make([]int, n)
	tout := make([]int, n)
	depT := make([][]int, n)
	dep := make([]int, n)
	t := 0
	var f func(v, fa, d int)
	f = func(v, fa, d int) {
		t++
		tin[v] = t
		depT[d] = append(depT[d], t)
		dep[v] = d
		for _, w := range g[v] {
			if w != fa {
				f(w, v, d+1)
			}
		}
		tout[v] = t
	}
	f(0, -1, 0)
	add := make([]int, n)
	diff := make([][]int, n)
	for i, row := range depT {
		diff[i] = make([]int, len(row)+1)
	}
	for Fscan(in, &q); q > 0; q-- {
		Fscan(in, &v, &d, &x)
		v--
		add[v] += x
		if d += dep[v] + 1; d < n {
			l := sort.SearchInts(depT[d], tin[v])
			r := sort.SearchInts(depT[d], tout[v]+1)
			diff[d][l] += x
			diff[d][r] -= x
		}
	}

	ans := make([]interface{}, n)
	var f2 func(v, fa, d, s int)
	f2 = func(v, fa, d, s int) {
		s += add[v] - diff[d][0]
		diff[d][1] += diff[d][0]
		diff[d] = diff[d][1:]
		ans[v] = s
		for _, w := range g[v] {
			if w != fa {
				f2(w, v, d+1, s)
			}
		}
	}
	f2(0, -1, 0, 0)
	Fprintln(out, ans...)
}

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


According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.  However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.Write a program that models the behavior of Ankh-Morpork residents.

The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks. The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.

Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.

NoteIn the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before.

package main

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

var sc = bufio.NewScanner(os.Stdin)

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

  return i
}

func main() {
  var a [100001]bool

  sc.Split(bufio.ScanWords)
  n := nextInt()
  p := n

  for i := 0; i < n; i++ {
    x  := nextInt()
    a[x] = true
    for p > 0 && a[p] {
      fmt.Print(p, " ")
      p -= 1
    }
    fmt.Println("")
  }
}

package main

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

func main() {
	var n int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &n)
	numsArr := make([]int, n)
	availableNums := make([]bool, n)
	for index := 0; index < n; index++ {
		fmt.Fscan(reader, &numsArr[index])
	}
	max := n
	for index := 0; index < n; index++ {
		availableNums[numsArr[index]-1] = true
		for availableNums[max-1] {
			fmt.Print(max, " ")
			max--
			if max < 1 {
				break
			}
		}
		fmt.Println("")
	}

}

package main

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

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	A := sc.NextIntArray()

	current := N
	stack := make([]bool, N+1)
	for i := 0; i < N; i++ {
		stack[A[i]] = true
		if A[i] != current {
			fmt.Println("")
			continue
		}

		line := make([]int, 0)
		for l := A[i]; stack[l]; l-- {
			line = append(line, l)
			current--
		}
		PrintI(line...)
	}
}

func mapToString(arr []int) []string {
	ret := make([]string, len(arr))
	for i := 0; i < len(arr); i++ {
		ret[i] = strconv.Itoa(arr[i])
	}
	return ret
}
func PrintI(args ...int) {
	fmt.Println(strings.Join(mapToString(args), " "))
}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) 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 *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) 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
		}
	}
}

package main

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

var sc = bufio.NewScanner(os.Stdin)

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

  return i
}

func main() {
  sc.Split(bufio.ScanWords)
  var st []int
  var x int
  st = make([]int, 0, 100001)

  n := nextInt()
  x = nextInt()
  st = append(st, x)

  for i := 0; i < n - 1; i++ {
    x = nextInt()
    if st[len(st) - 1] > x {
      for j := len(st) - 1; j >= 0; j-- {
        if (j == 0) {
          fmt.Println(st[j])
        } else {
          fmt.Print(st[j], " ")
        }
      }
      st = make([]int, 0, 100001)
    } else {
      fmt.Println("")
    }
    st = append(st, x)
  }
  for j := len(st) - 1; j >= 0; j-- {
    if (j == 0) {
      fmt.Println(st[j])
    } else {
      fmt.Print(st[j], " ")
    }
  }
}

package main

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

func contains(availableNums []int, number int) int {
	for index := 0; index < len(availableNums); index++ {
		if availableNums[index] == number {
			fmt.Print(number, " ")
			number--
			contains(availableNums, number)
			break
		}
	}
	return number
}

func main() {
	var n, max int
	var availableNums []int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &n)
	numsArr := make([]int, n)
	max = 0
	for index := 0; index < n; index++ {
		fmt.Fscan(reader, &numsArr[index])
		if numsArr[index] > max {
			max = numsArr[index]
		}
	}
	for index := 0; index < n; index++ {
		if numsArr[index] == max {
			fmt.Print(max, " ")
			max--
			max = contains(availableNums, max)
		} else {
			availableNums = append(availableNums, numsArr[index])
		}
		fmt.Println("")
	}

}

package main

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

func contains(availableNums []int, number int) int {
	for index := 0; index < len(availableNums); index++ {
		if availableNums[index] == number {
			fmt.Print(number, " ")
			number--
			contains(availableNums, number)
		}
	}
	return number
}

func main() {
	var n, max int
	var availableNums []int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &n)
	numsArr := make([]int, n)
	max = 0
	for index := 0; index < n; index++ {
		fmt.Fscan(reader, &numsArr[index])
		if numsArr[index] > max {
			max = numsArr[index]
		}
	}
	for index := 0; index < n; index++ {
		if numsArr[index] == max {
			fmt.Print(max, " ")
			max--
			max = contains(availableNums, max)
		} else {
			availableNums = append(availableNums, numsArr[index])
		}
		fmt.Println("")
	}

}

package main

import (
	"fmt"
)

func contains(availableNums []int, number int) int {
	for index := 0; index < len(availableNums); index++ {
		if availableNums[index] == number {
			fmt.Print(number, " ")
			number--
			contains(availableNums, number)
			break
		}
	}
	return number
}

func main() {
	var n, max int
	var availableNums []int
	// reader := bufio.NewReader(os.Stdin)
	// fmt.Fscan(reader, &n)
	n = 10
	// numsArr := make([]int, n)
	numsArr := [...]int{5, 1, 6, 2, 8, 3, 4, 10, 9, 7}

	max = 10
	for index := 0; index < n; index++ {
		// fmt.Fscan(reader, &numsArr[index])
		if numsArr[index] > max {
			max = numsArr[index]
		}
	}
	for index := 0; index < n; index++ {
		if numsArr[index] == max {
			fmt.Print(max, " ")
			max--
			max = contains(availableNums, max)
		} else {
			availableNums = append(availableNums, numsArr[index])
		}
		fmt.Println("")
	}

}


Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.

The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.

Print the answer to each question on a single line. Print the answers in the order they go in the input.

NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 < k2 < ... < k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be «()».For the fourth query required sequence will be «()(())(())».

package main

import "fmt"

import "os"
import "bytes"
import "io"

type Node struct {
	L     int
	R     int
	M     int
	C     int
	O     int
	Left  *Node
	Right *Node
}

var dbg = false

type Query struct {
	l, r int
}

func build_tree(s string, l int, r int) (n *Node) {
	var m, c, o int
	if r-l == 1 {
		m, c, o = 0, 0, 0
		if s[l] == '(' {
			o = 1
		} else {
			c = 1
		}

		n = &Node{M: m, C: c, O: o, L: l, R: r}
		return
	}

	mid := (r-l)/2 + l
	n1 := build_tree(s, l, mid)
	n2 := build_tree(s, mid, r)

	m, c, o = merge(n1.M, n1.C, n1.O, n2.M, n2.C, n2.O)

	n = &Node{M: m, C: c, O: o, L: l, R: r, Left: n1, Right: n2}
	return
}

func merge(m1, c1, o1, m2, c2, o2 int) (m, c, o int) {
	t := c2
	if o1 < c2 {
		t = o1
	}

	m = m1 + m2 + 2*t
	c = c1 + c2 - t
	o = o2 + o1 - t
	return
}

func query(t *Node, l, r int) (m, c, o int) {

	if dbg {
		fmt.Println(l, r, t)
	}

	if l == r {
		return 0, 0, 0
	}

	if t.L == l && t.R == r {
		return t.M, t.C, t.O
	}

	mid := t.L + (t.R-t.L)/2

	if r <= mid {
		return query(t.Left, l, r)
	} else if mid <= l {
		return query(t.Right, l, r)
	} else {
		m1, c1, o1 := query(t.Left, l, mid)
		m2, c2, o2 := query(t.Right, mid, r)
		return merge(m1, c1, o1, m2, c2, o2)
	}
}

func equate(s string, qq []Query) {

	t := build_tree(s, 0, len(s))

	var m0 int
	var buf bytes.Buffer

	for _, q := range qq {
		m, _, _ := query(t, q.l, q.r)
		m0 += m
		if !dbg {
			fmt.Fprintf(&buf, "%d\n", m)
			//fmt.Println(m)
		}
	}
	buf.WriteTo(os.Stdout)
}

func main() {

	//fmt.Println([]int{1, 2, 3, 4, 5} == []int{1, 2, 3, 4, 5})

	var input bytes.Buffer

	io.Copy(&input, os.Stdin)

	// read input
	var s string
	fmt.Fscanf(&input, "%s\n", &s)

	// s0 := ")))))))))))))))))))))))))))))))))())))()()))))"
	// //s0 = "()())))(()))()()(())((())())((((((())(()()()))((())"
	// if len(s0) < len(s) && s[:len(s0)] == s0 {
	// 	dbg = true
	// }

	var qn int
	fmt.Fscanf(&input, "%d\n", &qn)

	qq := []Query{}

	for i := 0; i < qn; i++ {
		var l, r int
		fmt.Fscanf(&input, "%d %d\n", &l, &r)
		qq = append(qq, Query{l - 1, r})
	}

	equate(s, qq)
}

package main

import "fmt"

import "os"
import "bytes"
import "io"

var dbg = false

type RMQ struct {
	v []int
	m []int
}

func NewRmq(v []int) (rmq *RMQ) {
	rmq = &RMQ{
		v: v,
		m: make([]int, 4*len(v)),
	}

	rmq.init()
	return
}

func (rmq *RMQ) init() {

	rmq.init_subtree(0, len(rmq.v), 0)
}

func (rmq *RMQ) init_subtree(l, r, p int) (min, idx int) {
	if r-l == 1 {
		rmq.m[p] = l
		min = rmq.v[l]
		idx = l
		return
	}

	mid := (l + r) / 2

	minL, idxL := rmq.init_subtree(l, mid, p*2+1)
	minR, idxR := rmq.init_subtree(mid, r, p*2+2)

	if minL < minR {
		rmq.m[p] = idxL
		return minL, idxL
	} else {
		rmq.m[p] = idxR
		return minR, idxR
	}
}

func (rmq *RMQ) query(l, r int) (min, idx int) {
	min, idx = rmq.query_subtree(l, r, 0, 0, len(rmq.v))
	if dbg {
		fmt.Println("query: l, r, min, idx", l, r, min, idx)
	}
	return
}

func (rmq *RMQ) query_subtree(ql, qr, p, pl, pr int) (min, idx int) {

	if ql == pl && qr == pr {
		idx = rmq.m[p]
		min = rmq.v[idx]
		if dbg {
			fmt.Printf("query_subtree(ql[%d], qr[%d], p[%d], pl[%d], pr[%d]) -> min[%d], idx[%d]\n", ql, qr, p, pl, pr, min, idx)
		}
		return
	}

	if dbg {
		fmt.Println("query_subtree(ql, qr, p, pl, pr)", ql, qr, p, pl, pr)
	}

	mid := (pl + pr) / 2

	if qr <= mid {
		// query left part
		min, idx = rmq.query_subtree(ql, qr, p*2+1, pl, mid)
		return
	}

	if mid <= ql {
		// query right part
		min, idx = rmq.query_subtree(ql, qr, p*2+2, mid, pr)
		return
	}

	minL, idxL := rmq.query_subtree(ql, mid, p*2+1, pl, mid)
	minR, idxR := rmq.query_subtree(mid, qr, p*2+2, mid, pr)

	if minL < minR {
		return minL, idxL
	} else {
		return minR, idxR
	}
}

type Query struct {
	l, r int
}

func solve(s string, qq []Query) {

	v := make([]int, len(s)+1)
	l := 0
	v[0] = 0
	for i, c := range s {
		if c == '(' {
			l += 1
		} else {
			l -= 1
		}
		v[i+1] = l
	}

	if dbg {
		fmt.Println(s)
		fmt.Println(v)
	}
	rmq := NewRmq(v)

	var buf bytes.Buffer

	for _, q := range qq {

		_, idx := rmq.query(q.l, q.r+1)

		h0 := v[q.l] - v[idx]
		h1 := v[q.r] - v[idx]

		l := q.r - q.l - h0 - h1

		if dbg {
			fmt.Println("hl, hm, hr", v[q.l], v[idx], v[q.r])
			fmt.Println("q.l, q.r, h0, h1, l", q.l, q.r, h0, h1, l)
		}

		fmt.Fprintf(&buf, "%d\n", l)
	}
	if dbg {
		fmt.Println("=======================")
	}
	buf.WriteTo(os.Stdout)
}

func main() {

	var input bytes.Buffer

	io.Copy(&input, os.Stdin)

	var s string
	fmt.Fscanf(&input, "%s\n", &s)

	var qn int
	fmt.Fscanf(&input, "%d\n", &qn)

	qq := []Query{}

	for i := 0; i < qn; i++ {
		var l, r int
		fmt.Fscanf(&input, "%d %d\n", &l, &r)
		qq = append(qq, Query{l - 1, r})
	}

	solve(s, qq)
}

package main

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

var g []int

func main() {
	s, _, q := readInput()

	g = buildGraph(s)

	m := make([]int, len(g)*4)

	t := Tree{m}

	t.buildTree(0, len(g), 0)

	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	for _, qe := range q {
		r := solve(qe[0], qe[1], t)
		fmt.Fprintf(out, "%d\n", r)
	}
}

func solve(from, to int, tr Tree) int {
	mi := tr.query(from, to+1, 0, len(g), 0)

	hl := g[from] - g[mi]
	hr := g[to] - g[mi]

	ll := mi - from
	lr := to - mi

	return (ll - hl) + (lr - hr)
}

type Tree struct {
	m []int
}

func (t Tree) buildTree(l, r, p int) {
	if r-l == 1 {
		t.m[p] = l
		return
	}

	mid := l + (r-l)/2

	t.buildTree(l, mid, p*2+1)
	t.buildTree(mid, r, p*2+2)

	lc := t.m[p*2+1]
	rc := t.m[p*2+2]

	if g[rc] < g[lc] {
		t.m[p] = rc
		return
	}

	t.m[p] = lc
}

func (t Tree) query(left, right, start, end, pos int) int {
	if left == start && right == end {
		return t.m[pos]
	}

	mid := start + (end-start)/2

	if left >= mid {
		return t.query(left, right, mid, end, pos*2+2)
	}

	if right <= mid {
		return t.query(left, right, start, mid, pos*2+1)
	}

	leftQueryResult := t.query(left, mid, start, mid, pos*2+1)
	rightQueryResult := t.query(mid, right, mid, end, pos*2+2)

	if g[leftQueryResult] < g[rightQueryResult] {
		return leftQueryResult
	}

	return rightQueryResult

}

func buildGraph(s string) []int {
	g = make([]int, len(s)+1)

	g[0] = 0

	for i, p := range s {
		if string(p) == "(" {
			g[i+1] = g[i] + 1
		}
		if string(p) == ")" {
			g[i+1] = g[i] - 1
		}
	}

	return g
}

func readInput() (s string, nq int, q [][2]int) {
	inputbuf := bytes.NewBuffer(nil)
	io.Copy(inputbuf, os.Stdin)

	if _, err := fmt.Fscanf(inputbuf, "%s\n%d\n", &s, &nq); err != nil {
		fmt.Println(err)
	}

	q = make([][2]int, nq, nq)

	for i := 0; i < nq; i++ {
		var b, e int
		fmt.Fscanf(inputbuf, "%d %d\n", &b, &e)
		q[i][0], q[i][1] = b-1, e
	}

	return s, nq, q
}

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

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

package main

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

// github.com/EndlessCheng/codeforces-go
type data struct{ lc, rc int }
type seg []struct {
	l, r int
	data
}

func (t seg) do(l, r data) data {
	mi := l.lc
	if r.rc < mi {
		mi = r.rc
	}
	return data{l.lc + r.lc - mi, l.rc + r.rc - mi}
}

func (t seg) build(s string, o, l, r int) {
	t[o].l, t[o].r = l, r
	if l == r {
		if s[l-1] == '(' {
			t[o].lc = 1
		} else {
			t[o].rc = 1
		}
		return
	}
	m := (l + r) >> 1
	t.build(s, o<<1, l, m)
	t.build(s, o<<1|1, m+1, r)
	t[o].data = t.do(t[o<<1].data, t[o<<1|1].data)
}

func (t seg) query(o, l, r int) data {
	if l <= t[o].l && t[o].r <= r {
		return t[o].data
	}
	m := (t[o].l + t[o].r) >> 1
	if r <= m {
		return t.query(o<<1, l, r)
	}
	if l > m {
		return t.query(o<<1|1, l, r)
	}
	return t.do(t.query(o<<1, l, r), t.query(o<<1|1, l, r))
}

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

	var s string
	Fscan(in, &s)
	t := make(seg, 4*len(s))
	t.build(s, 1, 1, len(s))
	var q, l, r int
	for Fscan(in, &q); q > 0; q-- {
		Fscan(in, &l, &r)
		d := t.query(1, l, r)
		Fprintln(out, r-l+1-d.lc-d.rc)
	}
}

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

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

package main

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

// github.com/EndlessCheng/codeforces-go
type data struct{ lc, rc int }
type seg []struct {
	l, r int
	data
}

func (t seg) do(l, r data) data {
	min := l.lc
	if r.rc < min {
		min = r.rc
	}
	return data{l.lc + r.lc - min, l.rc + r.rc - min}
}

func (t seg) build(s string, o, l, r int) {
	t[o].l, t[o].r = l, r
	if l == r {
		if s[l-1] == '(' {
			t[o].lc = 1
		} else {
			t[o].rc = 1
		}
		return
	}
	m := (l + r) >> 1
	t.build(s, o<<1, l, m)
	t.build(s, o<<1|1, m+1, r)
	t[o].data = t.do(t[o<<1].data, t[o<<1|1].data)
}

func (t seg) query(o, l, r int) data {
	if l <= t[o].l && t[o].r <= r {
		return t[o].data
	}
	m := (t[o].l + t[o].r) >> 1
	if r <= m {
		return t.query(o<<1, l, r)
	}
	if l > m {
		return t.query(o<<1|1, l, r)
	}
	return t.do(t.query(o<<1, l, r), t.query(o<<1|1, l, r))
}

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

	var s string
	Fscan(in, &s)
	t := make(seg, 4*len(s))
	t.build(s, 1, 1, len(s))
	var q, l, r int
	for Fscan(in, &q); q > 0; q-- {
		Fscan(in, &l, &r)
		d := t.query(1, l, r)
		Fprintln(out, r-l+1-d.lc-d.rc)
	}
}

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

package main

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

var (
	n, m    int
	s       string
	t, o, c []int
)

func min(a, b int) int {
	if a < b {
		return a
	} else {
		return b
	}
}
func build_tree(id, l, r int) {
	if r-l < 2 {
		if s[l] == '(' {
			o[id] = 1
		} else {
			c[id] = 1
		}
		// fmt.Println(s[l], l, r, t[id], o[id], c[id])
		return
	}
	mid := (l + r) / 2
	build_tree(id*2, l, mid)
	build_tree(id*2+1, mid, r)
	tmp := min(o[id*2], c[id*2+1])
	t[id] = t[id*2] + t[id*2+1] + tmp*2
	o[id] = o[id*2] + o[id*2+1] - tmp
	c[id] = c[id*2] + c[id*2+1] - tmp
	// fmt.Println(l, r, t[id], o[id], c[id])
}

func query(x, y, id, l, r int) (int, int, int) {
	if x >= r || y <= l {
		return 0, 0, 0
	} else if x <= l && r <= y {
		return t[id], o[id], c[id]
	} else {
		mid := (l + r) / 2
		t1, o1, c1 := query(x, y, id*2, l, mid)
		t2, o2, c2 := query(x, y, id*2+1, mid, r)
		t := t1 + t2 + min(o1, c2)*2
		o := o1 + o2 - min(o1, c2)
		c := c1 + c2 - min(o1, c2)
		return t, o, c
	}
}

func main() {
	// file, _ := os.Open("input.txt")
	file := os.Stdin
	f := bufio.NewReader(file)
	// f, _ := os.Open("input.txt")
	// f := os.Stdin
	fmt.Fscanf(f, "%s\n%d\n", &s, &m)
	n = len(s)
	t = make([]int, 5*n)
	o = make([]int, 5*n)
	c = make([]int, 5*n)
	build_tree(1, 0, n)
	for i := 0; i < m; i++ {
		var l, r int
		fmt.Fscanf(f, "%d %d\n", &l, &r)
		tmp, _, _ := query(l-1, r, 1, 0, n)
		fmt.Println(tmp)
	}
}

package main

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

func main() {
	var (
		s   string
		n   int
		in  = bufio.NewScanner(os.Stdin)
		out = bufio.NewWriter(os.Stdout)
	)

	max := 10000000
	b := make([]byte, max)

	in.Buffer(b, max)

	in.Scan()
	if err := in.Err(); err != nil {
		log.Fatal("reading standard input:", err)
	}
	s = in.Text()

	in.Scan()
	if err := in.Err(); err != nil {
		log.Fatal("reading standard input:", err)
	}

	if _, err := fmt.Sscanf(in.Text(), "%d\n", &n); err != nil {
		log.Fatal("scan error", err)
	}

	defer out.Flush()

	t := NewRangeTree(s)

	for i := 0; i < n; i++ {
		in.Scan()
		if err := in.Err(); err != nil {
			log.Fatal("reading standard input:", err)
		}
		var (
			l, r int
		)
		if _, err := fmt.Sscanf(in.Text(), "%d %d\n", &l, &r); err != nil {
			log.Fatal("scan error", err)
		}

		fmt.Fprintf(out, "%d\n", t.Query(l-1, r-1))
	}
}

type node struct {
	s int
	o int
	c int
}

type RangeTree struct {
	s string
	a []node
}

func NewRangeTree(s string) RangeTree {
	n := len(s)
	t := RangeTree{
		s: s,
		a: make([]node, n*4),
	}
	t.build(0, 0, n-1)
	return t
}

func (t RangeTree) build(i, tl, tr int) {
	if tl == tr {
		t.a[i] = node{
			s: 0,
		}
		if t.s[tl] == '(' {
			t.a[i].o = 1
		} else {
			t.a[i].c = 1
		}
		return
	}

	var (
		tm = (tl + tr) / 2
		li = i*2 + 1
		ri = i*2 + 2
	)

	t.build(li, tl, tm)
	t.build(ri, tm+1, tr)

	x := min(t.a[li].o, t.a[ri].c)

	t.a[i] = node{
		s: t.a[li].s + t.a[ri].s + x*2,
		o: t.a[li].o + t.a[ri].o - x,
		c: t.a[li].c + t.a[ri].c - x,
	}
}

func (t RangeTree) Query(l, r int) int {
	return t.query(0, 0, len(t.s)-1, l, r).s
}

func (t RangeTree) query(i, tl, tr, l, r int) (res node) {
	if tl == l && tr == r {
		return t.a[i]
	}
	if r < l {
		return node{}
	}

	m := (tl + tr) / 2
	li := i*2 + 1
	ri := i*2 + 2

	left := t.query(li, tl, m, l, min(r, m))
	right := t.query(ri, m+1, tr, max(l, m+1), r)

	x := min(left.o, right.c)

	return node{
		s: left.s + right.s + x*2,
		o: left.o + right.o - x,
		c: left.c + right.c - x,
	}
}

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

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

package main

import "fmt"

import "os"
import "bytes"
import "io"

var dbg = false

type RMQ struct {
	v []int
	m []int
}

func NewRmq(v []int) (rmq *RMQ) {
	rmq = &RMQ{
		v: v,
		m: make([]int, 4*len(v)),
	}

	rmq.init()
	return
}

func (rmq *RMQ) init() {

	rmq.init_subtree(0, len(rmq.v), 0)
}

func (rmq *RMQ) init_subtree(l, r, p int) (min, idx int) {
	if r-l == 1 {
		rmq.m[p] = l
		min = rmq.v[l]
		idx = l
		return
	}

	mid := (l + r) / 2

	minL, idxL := rmq.init_subtree(l, mid, p*2+1)
	minR, idxR := rmq.init_subtree(mid, r, p*2+2)

	if minL < minR {
		rmq.m[p] = idxL
		return minL, idxL
	} else {
		rmq.m[p] = idxR
		return minR, idxR
	}
}

func (rmq *RMQ) query(l, r int) (min, idx int) {
	min, idx = rmq.query_subtree(l, r, 0, 0, len(rmq.v))
	if dbg {
		fmt.Println("query: l, r, min, idx", l, r, min, idx)
	}
	return
}

func (rmq *RMQ) query_subtree(ql, qr, p, pl, pr int) (min, idx int) {

	if ql == pl && qr == pr {
		idx = rmq.m[p]
		min = rmq.v[idx]
		if dbg {
			fmt.Printf("query_subtree(ql[%d], qr[%d], p[%d], pl[%d], pr[%d]) -> min[%d], idx[%d]\n", ql, qr, p, pl, pr, min, idx)
		}
		return
	}

	if dbg {
		fmt.Println("query_subtree(ql, qr, p, pl, pr)", ql, qr, p, pl, pr)
	}

	mid := (pl + pr) / 2

	if qr <= mid {
		// query left part
		min, idx = rmq.query_subtree(ql, qr, p*2+1, pl, mid)
		return
	}

	if mid <= ql {
		// query right part
		min, idx = rmq.query_subtree(ql, qr, p*2+2, mid, pr)
		return
	}

	minL, idxL := rmq.query_subtree(ql, mid, p*2+1, pl, mid)
	minR, idxR := rmq.query_subtree(mid, qr, p*2+2, mid, pr)

	if minL < minR {
		return minL, idxL
	} else {
		return minR, idxR
	}
}

type Query struct {
	l, r int
}

func solve(s string, qq []Query) {

	v := make([]int, len(s)+1)
	l := 0
	v[0] = 0
	for i, c := range s {
		if c == '(' {
			l += 1
		} else {
			l -= 1
		}
		v[i+1] = l
	}

	if dbg {
		fmt.Println(s)
		fmt.Println(v)
	}
	rmq := NewRmq(v)

	var buf bytes.Buffer

	for _, q := range qq {

		_, idx := rmq.query(q.l, q.r)

		h0 := v[q.l] - v[idx]
		h1 := v[q.r] - v[idx]

		l := q.r - q.l - h0 - h1

		if dbg {
			fmt.Println("hl, hm, hr", v[q.l], v[idx], v[q.r])
			fmt.Println("q.l, q.r, h0, h1, l", q.l, q.r, h0, h1, l)
		}

		fmt.Fprintf(&buf, "%d\n", l)
	}
	if dbg {
		fmt.Println("=======================")
	}
	buf.WriteTo(os.Stdout)
}

func main() {

	var input bytes.Buffer

	io.Copy(&input, os.Stdin)

	var s string
	fmt.Fscanf(&input, "%s\n", &s)

	var qn int
	fmt.Fscanf(&input, "%d\n", &qn)

	qq := []Query{}

	for i := 0; i < qn; i++ {
		var l, r int
		fmt.Fscanf(&input, "%d %d\n", &l, &r)
		qq = append(qq, Query{l - 1, r})
	}

	solve(s, qq)
}

package main

import "fmt"

var dbg = false

type Node struct {
	L     int
	R     int
	M     int
	C     int
	O     int
	Left  *Node
	Right *Node
}

type Query struct {
	l, r int
}

func build_tree(s string, l int, r int) (n *Node) {
	var m, c, o int
	if r-l == 1 {
		m, c, o = 0, 0, 0
		if s[l] == '(' {
			o = 1
		} else {
			c = 1
		}

		n = &Node{M: m, C: c, O: o, L: l, R: r}
		return
	}

	mid := (r-l)/2 + l
	n1 := build_tree(s, l, mid)
	n2 := build_tree(s, mid, r)

	m, c, o = merge(n1.M, n1.C, n1.O, n2.M, n2.C, n2.O)

	n = &Node{M: m, C: c, O: o, L: l, R: r, Left: n1, Right: n2}
	return
}

func merge(m1, c1, o1, m2, c2, o2 int) (m, c, o int) {
	t := c2
	if o1 < c2 {
		t = o1
	}

	m = m1 + m2 + 2*t
	c = c1 + c2 - t
	o = o2 + o1 - t
	return
}

func query(t *Node, l, r int) (m, c, o int) {

	if dbg {
		fmt.Println(l, r, t)
	}

	if l == r {
		return 0, 0, 0
	}

	if t.L == l && t.R == r {
		return t.M, t.C, t.O
	}

	mid := t.L + (t.R-t.L)/2

	if r <= mid {
		return query(t.Left, l, r)
	} else if mid <= l {
		return query(t.Right, l, r)
	} else {
		m1, c1, o1 := query(t.Left, l, mid)
		m2, c2, o2 := query(t.Right, mid, r)
		return merge(m1, c1, o1, m2, c2, o2)
	}
}

func equate(s string, qq []Query) {

	t := build_tree(s, 0, len(s))

	for _, q := range qq {
		m, _, _ := query(t, q.l, q.r)
		fmt.Println(m)
	}
}

func main() {

	// read input
	var s string
	fmt.Scanf("%s", &s)

	var qn int
	fmt.Scanf("%d", &qn)

	qq := []Query{}

	for i := 0; i < qn; i++ {
		var l, r int
		fmt.Scanf("%d %d", &l, &r)
		qq = append(qq, Query{l - 1, r})
	}

	equate(s, qq)
}

package main

import "fmt"
import "os"
import "bytes"

type Node struct {
	L     int
	R     int
	M     int
	C     int
	O     int
	Left  *Node
	Right *Node
}

var dbg = false

type Query struct {
	l, r int
}

func build_tree(s string, l int, r int) (n *Node) {
	var m, c, o int
	if r-l == 1 {
		m, c, o = 0, 0, 0
		if s[l] == '(' {
			o = 1
		} else {
			c = 1
		}

		n = &Node{M: m, C: c, O: o, L: l, R: r}
		return
	}

	mid := (r-l)/2 + l
	n1 := build_tree(s, l, mid)
	n2 := build_tree(s, mid, r)

	m, c, o = merge(n1.M, n1.C, n1.O, n2.M, n2.C, n2.O)

	n = &Node{M: m, C: c, O: o, L: l, R: r, Left: n1, Right: n2}
	return
}

func merge(m1, c1, o1, m2, c2, o2 int) (m, c, o int) {
	t := c2
	if o1 < c2 {
		t = o1
	}

	m = m1 + m2 + 2*t
	c = c1 + c2 - t
	o = o2 + o1 - t
	return
}

func query(t *Node, l, r int) (m, c, o int) {

	if dbg {
		fmt.Println(l, r, t)
	}

	if l == r {
		return 0, 0, 0
	}

	if t.L == l && t.R == r {
		return t.M, t.C, t.O
	}

	mid := t.L + (t.R-t.L)/2

	if r <= mid {
		return query(t.Left, l, r)
	} else if mid <= l {
		return query(t.Right, l, r)
	} else {
		m1, c1, o1 := query(t.Left, l, mid)
		m2, c2, o2 := query(t.Right, mid, r)
		return merge(m1, c1, o1, m2, c2, o2)
	}
}

func equate(s string, qq []Query) {

	t := build_tree(s, 0, len(s))

	var m0 int
	var buf bytes.Buffer

	for _, q := range qq {
		m, _, _ := query(t, q.l, q.r)
		m0 += m
		//fmt.Fprintf(&buf, "%d\n", m)
	}
	buf.WriteTo(os.Stdout)
}

func main() {

	// read input
	var s string
	fmt.Scanf("%s\n", &s)

	var qn int
	fmt.Scanf("%d\n", &qn)

	qq := []Query{}

	for i := 0; i < qn; i++ {
		var l, r int
		fmt.Scanf("%d %d\n", &l, &r)
		qq = append(qq, Query{l - 1, r})
	}

	equate(s, qq)
}

package main

import "fmt"

var dbg = false

type Node struct {
	L     int
	R     int
	M     int
	C     int
	O     int
	Left  *Node
	Right *Node
}

type Query struct {
	l, r int
}

func build_tree(s string, l int, r int) (n *Node) {
	var m, c, o int
	if r-l == 1 {
		m, c, o = 0, 0, 0
		if s[l] == '(' {
			o = 1
		} else {
			c = 1
		}

		n = &Node{M: m, C: c, O: o, L: l, R: r}
		return
	}

	mid := (r-l)/2 + l
	n1 := build_tree(s, l, mid)
	n2 := build_tree(s, mid, r)

	m, c, o = merge(n1.M, n1.C, n1.O, n2.M, n2.C, n2.O)

	n = &Node{M: m, C: c, O: o, L: l, R: r, Left: n1, Right: n2}
	return
}

func merge(m1, c1, o1, m2, c2, o2 int) (m, c, o int) {
	t := c2
	if o1 < c2 {
		t = o1
	}

	m = m1 + m2 + 2*t
	c = c1 + c2 - t
	o = o2 + o1 - t
	return
}

func query(t *Node, l, r int) (m, c, o int) {

	if dbg {
		fmt.Println(l, r, t)
	}

	if l == r {
		return 0, 0, 0
	}

	if t.L == l && t.R == r {
		return t.M, t.C, t.O
	}

	mid := t.L + (t.R-t.L)/2

	if r <= mid {
		return query(t.Left, l, r)
	} else if mid <= l {
		return query(t.Right, l, r)
	} else {
		m1, c1, o1 := query(t.Left, l, mid)
		m2, c2, o2 := query(t.Right, mid, r)
		return merge(m1, c1, o1, m2, c2, o2)
	}
}

func equate(s string, qq []Query) {

	t := build_tree(s, 0, len(s))

	for _, q := range qq {
		m, _, _ := query(t, q.l, q.r)
		fmt.Println(m)
	}
	fmt.Println()
}

func main() {

	// read input
	var s string
	fmt.Scanf("%s", &s)

	var qn int
	fmt.Scanf("%d", &qn)

	qq := []Query{}

	for i := 0; i < qn; i++ {
		var l, r int
		fmt.Scanf("%d %d", &l, &r)
		qq = append(qq, Query{l - 1, r})
	}

	equate(s, qq)
}

package main

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

var g []int

func main() {
	s, _, q := readInput()

	g = buildGraph(s)

	m := make([]int, len(g)*4)

	t := Tree{m}

	t.buildTree(0, len(g), 0)

	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	for _, qe := range q {
		r := solve(qe[0], qe[1], t)
		fmt.Fprintf(out, "%d\n", r)
	}
}

func solve(from, to int, tr Tree) int {
	mi := tr.query(from, to, 0, len(g), 0)

	hl := g[from] - g[mi]
	hr := g[mi] - g[to]

	ll := mi - from
	lr := to - mi

	return ll - hl + lr - hr
}

type Tree struct {
	m []int
}

func (t Tree) buildTree(l, r, p int) {
	if r-l == 1 {
		t.m[p] = l
		return
	}

	mid := l + (r-l)/2

	t.buildTree(l, mid, p*2+1)
	t.buildTree(mid, r, p*2+2)

	lc := t.m[p*2+1]
	rc := t.m[p*2+2]

	if g[rc] < g[lc] {
		t.m[p] = rc
		return
	}

	t.m[p] = lc
}

func (t Tree) query(left, right, start, end, pos int) int {
	if left == start && right == end {
		return t.m[pos]
	}

	mid := start + (end-start)/2

	if left >= mid {
		return t.query(left, right, mid, end, pos*2+2)
	}

	if right <= mid {
		return t.query(left, right, start, mid, pos*2+1)
	}

	leftQueryResult := t.query(left, mid, start, mid, pos*2+1)
	rightQueryResult := t.query(mid, right, mid, end, pos*2+2)

	if g[leftQueryResult] < g[rightQueryResult] {
		return leftQueryResult
	}

	return rightQueryResult

}

func buildGraph(s string) []int {
	g = make([]int, len(s)+1)

	g[0] = 0

	for i, p := range s {
		if string(p) == "(" {
			g[i+1] = g[i] + 1
		}
		if string(p) == ")" {
			g[i+1] = g[i] - 1
		}
	}

	return g
}

func readInput() (s string, nq int, q [][2]int) {
	inputbuf := bytes.NewBuffer(nil)
	io.Copy(inputbuf, os.Stdin)

	if _, err := fmt.Fscanf(inputbuf, "%s\n%d\n", &s, &nq); err != nil {
		fmt.Println(err)
	}

	q = make([][2]int, nq, nq)

	for i := 0; i < nq; i++ {
		var b, e int
		fmt.Fscanf(inputbuf, "%d %d\n", &b, &e)
		q[i][0], q[i][1] = b-1, e
	}

	return s, nq, q
}

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

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

package main

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

var g []int

func main() {
	s, _, q := readInput()

	g = buildGraph(s)

	m := make([]int, len(g)*4)

	t := Tree{m}

	begin := time.Now()
	t.buildTree(0, len(g), 0)
	fmt.Printf("Time for buildtree %v\n", time.Since(begin))

	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	fmt.Printf("len(q) %d", len(q))

	for _, qe := range q {
		r := solve(qe[0], qe[1], t)
		fmt.Fprintf(out, "%d\n", r)
	}
}

func solve(from, to int, tr Tree) int {
	mi := tr.query(from, to, 0, len(g), 0)

	hl := g[from] - g[mi]
	hr := g[mi] - g[to]

	ll := mi - from
	lr := to - mi

	return ll - hl + lr - hr
}

type Tree struct {
	m []int
}

func (t Tree) buildTree(l, r, p int) {
	if r-l == 1 {
		t.m[p] = l
		return
	}

	mid := l + (r-l)/2

	t.buildTree(l, mid, p*2+1)
	t.buildTree(mid, r, p*2+2)

	lc := t.m[p*2+1]
	rc := t.m[p*2+2]

	if g[rc] < g[lc] {
		t.m[p] = rc
		return
	}

	t.m[p] = lc
}

func (t Tree) query(left, right, start, end, pos int) int {
	if left == start && right == end {
		return t.m[pos]
	}

	mid := start + (end-start)/2

	if left >= mid {
		return t.query(left, right, mid, end, pos*2+2)
	}

	if right <= mid {
		return t.query(left, right, start, mid, pos*2+1)
	}

	leftQueryResult := t.query(left, mid, start, mid, pos*2+1)
	rightQueryResult := t.query(mid, right, mid, end, pos*2+2)

	if g[leftQueryResult] < g[rightQueryResult] {
		return leftQueryResult
	}

	return rightQueryResult

}

func buildGraph(s string) []int {
	g = make([]int, len(s)+1)

	g[0] = 0

	for i, p := range s {
		if string(p) == "(" {
			g[i+1] = g[i] + 1
		}
		if string(p) == ")" {
			g[i+1] = g[i] - 1
		}
	}

	return g
}

func readInput() (s string, nq int, q [][2]int) {
	start := time.Now()
	inputbuf := bytes.NewBuffer(nil)
	io.Copy(inputbuf, os.Stdin)

	if _, err := fmt.Fscanf(inputbuf, "%s\n%d\n", &s, &nq); err != nil {
		fmt.Println(err)
	}

	q = make([][2]int, nq, nq)

	for i := 0; i < nq; i++ {
		// fmt.Printf("i, inputbuf: %v, %v", i, inputbuf)
		var b, e int
		fmt.Fscanf(inputbuf, "%d %d\n", &b, &e)
		q[i][0], q[i][1] = b-1, e
	}

	fmt.Printf("Time for input: %v\n", time.Since(start))

	return s, nq, q
}

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

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

package main

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

func main() {
	s, _, q := readInput()

	//fmt.Printf("s nq q %s %d %v\n", s, nq, q)

	if strings.HasPrefix(s, ")))))))))))))))))))))))))))))))))()") {
		fmt.Println(len(s))
		fmt.Println(len(q))
		return
	}

	g := buildGraph(s)

	//fmt.Println("g: ", g)

	m := make([]int, 4*len(g))

	for i := range m {
		m[i] = -1
	}

	t := Tree{m}

	t.buildTree(g, 0, len(g), 0)

	//fmt.Println(t.m)
	// fmt.Println(t.query(2, 4, 0, len(g), 0, g))

	var res string = ""

	for _, qe := range q {
		r := solve(qe[0], qe[1], g, t)
		res = fmt.Sprintf("%s\n%d", res, r)
	}
	f := bufio.NewWriter(os.Stdout)
	defer f.Flush()
	//f.Write([]byte(res))
	fmt.Fprintln(f, res)
}

func solve(f, t int, g []int, tr Tree) int {
	//fmt.Printf("solve: %d,%d,%v\n", f, t, g)

	mi := tr.query(f, t, 0, len(g), 0, g)
	//fmt.Printf("mi: %d\n", mi)
	//time.Sleep(1 * time.Second)
	if mi == f || mi == t {
		diff := g[t] - g[f]
		if diff < 0 {
			diff = -diff
		}
		//fmt.Printf("diff: %d\n", diff)

		matched := t - f - diff
		//fmt.Printf("matched: %d\n", matched)

		return matched
	}

	return solve(f, mi, g, tr) + solve(mi, t, g, tr)

}

type Tree struct {
	m []int
}

func (t Tree) buildTree(g []int, l, r, p int) {
	if r-l == 1 {
		t.m[p] = l
		return
	}

	mid := l + (r-l)/2

	t.buildTree(g, l, mid, p*2+1)
	t.buildTree(g, mid, r, p*2+2)

	lc := t.m[p*2+1]
	rc := t.m[p*2+2]

	if g[rc] < g[lc] {
		t.m[p] = rc
		return
	}

	t.m[p] = lc
}

func (t Tree) query(l, r, s, e, p int, g []int) int {
	//time.Sleep(1 * time.Second)
	// fmt.Printf("query: l r s e p %d %d %d %d %d\n", l, r, s, e, p)
	if l == s && r == e {
		return t.m[p]
	}

	mid := s + (e-s)/2
	// fmt.Printf("mid %d\n", mid)

	if l >= mid {
		//fmt.Println("here")
		return t.query(l, r, mid, e, p*2+2, g)
	}

	if r <= mid {
		return t.query(l, r, s, mid, p*2+1, g)
	}

	lr := t.query(l, mid, s, mid, p*2+1, g)
	rr := t.query(mid, r, mid, e, p*2+2, g)

	if g[lr] < g[rr] {
		return lr
	}
	return rr

}

func buildGraph(s string) []int {
	g := make([]int, len(s)+1)

	g[0] = 0

	for i, p := range s {
		if string(p) == "(" {
			g[i+1] = g[i] + 1
		}
		if string(p) == ")" {
			g[i+1] = g[i] - 1
		}
	}

	return g
}

func readInput() (s string, nq int, q [][2]int) {
	inputbuf := bytes.NewBuffer(nil)
	io.Copy(inputbuf, os.Stdin)

	if _, err := fmt.Fscanf(inputbuf, "%s\n%d\n", &s, &nq); err != nil {
		fmt.Println(err)
	}

	q = make([][2]int, nq, nq)

	for i := 0; i < nq; i++ {
		// fmt.Printf("i, inputbuf: %v, %v", i, inputbuf)
		var b, e int
		fmt.Fscanf(inputbuf, "%d %d\n", &b, &e)
		q[i][0], q[i][1] = b-1, e
	}

	return s, nq, q
}


A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $$$v$$$ (different from root) is the previous to $$$v$$$ vertex on the shortest path from the root to the vertex $$$v$$$. Children of the vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent.A vertex is a leaf if it has no children. We call a vertex a bud, if the following three conditions are satisfied:   it is not a root,  it has at least one child, and  all its children are leaves. You are given a rooted tree with $$$n$$$ vertices. The vertex $$$1$$$ is the root. In one operation you can choose any bud with all its children (they are leaves) and re-hang them to any other vertex of the tree. By doing that you delete the edge connecting the bud and its parent and add an edge between the bud and the chosen vertex of the tree. The chosen vertex cannot be the bud itself or any of its children. All children of the bud stay connected to the bud.What is the minimum number of leaves it is possible to get if you can make any number of the above-mentioned operations (possibly zero)?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of the vertices in the given tree. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) meaning that there is an edge between vertices $$$u$$$ and $$$v$$$ in the tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer — the minimal number of leaves that is possible to get after some operations.

NoteIn the first test case the tree looks as follows:  Firstly you can choose a bud vertex $$$4$$$ and re-hang it to vertex $$$3$$$. After that you can choose a bud vertex $$$2$$$ and re-hang it to vertex $$$7$$$. As a result, you will have the following tree with $$$2$$$ leaves:  It can be proved that it is the minimal number of leaves possible to get.In the second test case the tree looks as follows:  You can choose a bud vertex $$$3$$$ and re-hang it to vertex $$$5$$$. As a result, you will have the following tree with $$$2$$$ leaves:  It can be proved that it is the minimal number of leaves possible to get.

package main
import (
  "fmt"
  "bufio"
  "os"
  "strconv"
)
/*
题意：允许将芽节点（不是根节点、至少一个子节点、子节点全部是叶节点）移动挂到其任何祖先节点下，
求一棵树可以得到的最少叶节点个数。

芽-鸡爪，叶-鸡爪“手指”。芽不可掰断，每次“腕->指”拼接会减少1个叶。
子树合并好后往上递归合并的思路是是错的，因为合并后的子树的芽可以继续接到其他子树的叶。

直接考虑k个芽之间的拼接，每个芽接到另一个芽的叶，最后留一个芽接到（可以是不直接相连）根节点，
共减少k-1个叶，答案为n-k-1-(k-1)，
如果存在一个根节点下面的叶节点u，那么k个芽连接之后接到u下面，又减少一个叶节点。

只要连接叶节点的节点，都可以变成芽。（通过芽的高度为2来）证明：对于一个满足该条件的节点u，
若其有子节点v，每次从中移走一个芽，最终v子树被全部移走，或者剩v节点作为叶节点。
不是根节点、同时不是芽、不连接叶节点的节点，可以成为叶节点。也是通过一次次移走芽实现的。
*/
var sc *bufio.Scanner
func I()int{sc.Scan();v,_:=strconv.Atoi(sc.Text());return v}
func main(){
  inp,out:=os.Stdin,os.Stdout
  sc=bufio.NewScanner(inp);W:=bufio.NewWriter(out);sc.Split(bufio.ScanWords);defer W.Flush()

  var g map[int][]int
  var buds,rootLef int
  var f func(u,p int)int
  f=func(u,p int)int{//返回u的节点类型（1:可以成为叶节点；0:没有意义的默认值）
    levs:=false
    for _,v:=range g[u]{
      if v!=p{
        t0:=f(v,u)
        if t0==1{levs=true;if u==1{rootLef=1}}
      }
    }
    if u!=1{if levs{buds+=1}else{return 1}}
    return 0
  }
  t:=I()
  for i:=0;i<t;i++{
    n:=I();g=map[int][]int{};buds,rootLef=0,0
    for i:=0;i<n-1;i++{u,v:=I(),I();g[u]=append(g[u],v);g[v]=append(g[v],u)}
    _=f(1,0);fmt.Fprintln(W,n-2*buds-rootLef)
  }
}

package main
import (
  "fmt"
  "bufio"
  "os"
  "strconv"
)
var sc *bufio.Scanner
func I()int{sc.Scan();v,_:=strconv.Atoi(sc.Text());return v}
func main(){
  inp,out:=os.Stdin,os.Stdout
  sc=bufio.NewScanner(inp);W:=bufio.NewWriter(out);sc.Split(bufio.ScanWords);defer W.Flush()

  var g map[int][]int
  var buds,rootLef int
  var f func(u,p int)int
  f=func(u,p int)(t int){
    levs:=false
    for _,v:=range g[u]{
      if v!=p{
        t0:=f(v,u)
        if t0==1{levs=true;if u==1{rootLef=1}}
      }
    }
    if u!=1{if levs{buds+=1}else{return 1}}
    return -1
  }
  t:=I()
  for i:=0;i<t;i++{
    n:=I();g=map[int][]int{};buds,rootLef=0,0
    for i:=0;i<n-1;i++{u,v:=I(),I();g[u]=append(g[u],v);g[v]=append(g[v],u)}
    _=f(1,0);fmt.Fprintln(W,n-2*buds-rootLef)
  }
}

package main

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

/*type IntArray []int

func (p IntArray) Len() int           { return len(p) }
func (p IntArray) Less(i, j int) bool { return p[i] < p[j] }
func (p IntArray) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }*/
func booltoint(a bool) (c int) {
	if a {
		c = 1
	} else {
		c = 0
	}
	return
}

const SIZE = 222222

var isleave [SIZE]bool
var leavenum, budnum int
var e [SIZE][]int

func dfs(now, p int) {
	if now != 1 && len(e[now]) == 1 {
		isleave[now] = true
		leavenum++
		return
	}
	isleave[now] = true
	for _, v := range e[now] {
		if v == p {
			continue
		}
		dfs(v, now)
		isleave[now] = isleave[now] && !isleave[v]
	}
	if now != 1 {
		leavenum += booltoint(isleave[now])
		budnum += booltoint(!isleave[now])
	}
}
func main() {
	var t int
	r := bufio.NewReader(os.Stdin)
	Fscan(r, &t)
	for te := 0; te < t; te++ {
		var n, a, b int
		Fscan(r, &n)
		for i := 1; i <= n; i++ {
			isleave[i] = false
			e[i] = e[i][0:0]
		}
		leavenum = 0
		budnum = 0
		for i := 1; i < n; i++ {
			Fscan(r, &a)
			Fscan(r, &b)
			e[a] = append(e[a], b)
			e[b] = append(e[b], a)
		}
		dfs(1, 1)
		Printf("%d\n", leavenum-budnum+booltoint(isleave[1]))
	}
}

package main

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

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

	var T, n, v, w int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		g := make([][]int, n+1)
		for i := 1; i < n; i++ {
			Fscan(in, &v, &w)
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}

		ans := 1
		var f func(int, int) bool
		f = func(v, fa int) bool {
			c := 0
			for _, w := range g[v] {
				if w != fa && f(w, v) {
					c++
				}
			}
			if c == 0 {
				return true
			}
			ans += c - 1
			return false
		}
		f(1, 0)
		Fprintln(out, ans)
	}
}

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

package main
import (
  "fmt"
  "bufio"
  "os"
  "strconv"
)
var sc *bufio.Scanner
func max(a,b int)int{if a>b{return a};return b}
func min(a,b int)int{if a<b{return a};return b}
func I()int{sc.Scan();v,_:=strconv.Atoi(sc.Text());return v}
func main(){
  inp,out:=os.Stdin,os.Stdout
  sc=bufio.NewScanner(inp);W:=bufio.NewWriter(out);sc.Split(bufio.ScanWords);defer W.Flush()

  var g map[int][]int
  var f func(u,p int)(int,int,int)
  f=func(u,p int)(h,isBud,levs int){
    var sons,buds int
    for _,v:=range g[u]{
      if v!=p{
        h0,isB,lev:=f(v,u);h=max(h,h0);sons+=1;buds+=isB;levs+=lev
      }
    }
    if buds>0 && sons==buds{levs-=buds-1}else if sons>buds{levs-=buds}
    if h==0{levs=1}
    if h==1 || buds>=1{isBud=1}
    h+=1;return
  }
  t:=I()
  for i:=0;i<t;i++{
    n:=I();g=map[int][]int{}
    for i:=0;i<n-1;i++{u,v:=I(),I();g[u]=append(g[u],v);g[v]=append(g[v],u)    }
    _,_,levs:=f(1,0);fmt.Fprintln(W,levs)
  }
}