The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum  is maximal possible. Help George to cope with the task.

The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109).

Print an integer in a single line — the maximum possible value of sum.

package main

import (
	"fmt"
)

func main() {
	var n, m, k int
	fmt.Scan(&n, &m, &k)
	firstM := int64(0)
	p := make([]int, n)
	for i := range p {
		fmt.Scan(&p[i])
		if i < m {
			firstM += int64(p[i])
		}
	}
	before := make([]int64, n+1)
	after := make([]int64, n+1)
	for i := 0; i < k; i++ {
		sum := firstM
		best := int64(0)
		for i := m; i <= n; i++ {
			if best < before[i-m] {
				best = before[i-m]
			}
			after[i] = best + sum
			if i+1 <= n {
				sum += int64(p[i] - p[i-m])
			}
		}
		before, after = after, before
	}
	ans := int64(0)
	for _, b := range before {
		if ans < b {
			ans = b
		}
	}
	fmt.Println(ans)
}

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

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

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

const (
	MOD = 1e9 + 7
)

type (

)

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

	return b
}

func main() {
	var (
		n, m, k int
	)

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

	fmt.Fscan(input, &n, &m, &k)

	p := make([]int64, n)
	sum := make([]int64, n + 1)
	dp := make([][]int64, n)
	for i := 0; i < n; i++ {
		dp[i] = make([]int64, k)
		fmt.Fscan(input, &p[i])

		sum[i + 1] = sum[i] + p[i]
	}

	// Solve
	curs := make([]int64, n)
	for i := m - 1; i < n; i++ {
		curs[i] = sum[i + 1] - sum[i - m + 1]

		if i > 0 {
			dp[i][0] = max(sum[i + 1] - sum[i - m + 1], dp[i - 1][0])
		}  else {
			dp[i][0] = sum[i + 1] - sum[i - m + 1]
		}
	}

	for i := m; i < n; i++ {
		for j := 1; j < k; j++ {
			dp[i][j] = max(dp[i - 1][j], curs[i] + dp[i - m][j - 1])
		}
	}

	fmt.Println(dp[n - 1][k - 1])
}

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol467C(reader io.Reader, writer io.Writer) {
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n, sz, k int
	Fscan(in, &n, &sz, &k)
	p := make([]int64, n)
	for i := range p {
		Fscan(in, &p[i])
	}

	sum := make([]int64, n-sz+1)
	for _, v := range p[:sz] {
		sum[0] += v
	}
	for i, v := range p[sz:] {
		sum[i+1] = sum[i] + v - p[i]
	}

	dp := make([]int64, n+1)
	for i := 1; i <= k; i++ {
		for end := n; end >= sz; end-- {
			dp[end] = max(dp[end], dp[end-sz]+sum[end-sz])
		}
		maxVal := int64(0)
		for i, dpi := range dp {
			maxVal = max(maxVal, dpi)
			dp[i] = maxVal
		}
	}
	Fprint(out, dp[n])
}

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

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

var n, m, K int

func max(nums ...int64) int64 {
	var m int64
	for i, v := range nums{
		if i == 0 || v > m {
			m = v
		}
	}
	return m
}

func main() {
	scanf("%d %d %d\n", &n, &m, &K)

	p := make([]int64, n)
	for i := range p {
		scanf("%d", &p[i])
	}
	sum := make(map[int]int64)
	for i, v := range p {
		sum[i] = sum[i-1] + v
	}

	prev, curr := make([]int64, n), make([]int64, n)

	// prev init k = 1
	prev[m-1] = sum[m-1]
	for i := m; i < n; i++ {
		prev[i] = max(prev[i-1], sum[i] - sum[i-m])
	}

	for k := 2; k <= K; k++{
		curr[m*k-1] = sum[m*k-1]
		for i:= m*k; i<n; i++{
			curr[i] = max(curr[i-1], prev[i-m] + sum[i] - sum[i-m])
		}
		prev, curr = curr, prev
	}

	fmt.Println(prev[n-1])

}

package main

import (
    "fmt"
)

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

func main() {
    var n, m, k int
    fmt.Scanf("%d %d %d\n", &n, &m, &k)
    sum := make([]uint64, n+1)
    dp := make([][]uint64, 2)
    dp[0] = make([]uint64, n+1)
    dp[1] = make([]uint64, n+1)

    for i := 1; i <= n; i++ {
        fmt.Scan(&sum[i])
        sum[i] += sum[i-1]
    }

    q := 1
    for i := 1; i <= k; i++ {
        q = 1 - q
        for j := i * m; j <= n; j++ {
            dp[q][j] = max(dp[q][j-1], dp[1-q][j-m]+sum[j]-sum[j-m])
        }
    }
    fmt.Println(dp[q][n])
}

package main

import (
	"fmt"
)

func main() {
	var n, m, k int
	fmt.Scan(&n, &m, &k)
	firstM := 0
	p := make([]int, n)
	for i := range p {
		fmt.Scan(&p[i])
		if i < m {
			firstM += p[i]
		}
	}
	before := make([]int, n+1)
	after := make([]int, n+1)
	for i := 0; i < k; i++ {
		sum := firstM
		best := 0
		for i := m; i <= n; i++ {
			if best < before[i-m] {
				best = before[i-m]
			}
			after[i] = best + sum
			if i+1 <= n {
				sum += p[i] - p[i-m]
			}
		}
		before, after = after, before
	}
	ans := 0
	for _, b := range before {
		if ans < b {
			ans = b
		}
	}
	fmt.Println(ans)
}

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

var n, m, K int

func max(nums ...int) int {
	var m int
	for i, v := range nums{
		if i == 0 || v > m {
			m = v
		}
	}
	return m
}

func main() {
	scanf("%d %d %d\n", &n, &m, &K)

	p := make([]int, n)
	for i := range p {
		scanf("%d", &p[i])
	}
	sum := make(map[int]int)
	for i, v := range p {
		sum[i] = sum[i-1] + v
	}

	prev, curr := make([]int, n), make([]int, n)

	// prev init k = 1
	prev[m-1] = sum[m-1]
	for i := m; i < n; i++ {
		prev[i] = max(prev[i-1], sum[i] - sum[i-m])
	}

	for k := 2; k <= K; k++{
		curr[m*k-1] = sum[m*k-1]
		for i:= m*k; i<n; i++{
			curr[i] = max(curr[i-1], prev[i-m] + sum[i] - sum[i-m])
		}
		prev, curr = curr, prev
	}

	fmt.Println(prev[n-1])

}

package main

import (
	"container/list"
	"fmt"
)

type el struct {
	index int
	value uint64
}

func main() {
	var n, m, k int
	var x uint64
	fmt.Scanf("%d %d %d\n", &n, &m, &k)
	sum := make([]uint64, n)
	var e *list.Element
	l := list.New()
	fmt.Scanf("%d", &sum[0])

	for i := 1; i < n; i++ {
		fmt.Scanf("%d", &x)
		sum[i] = sum[i-1] + x
	}

	l.PushBack(el{0, sum[m-1]})

	for i := 1; i < n-(m-1); i++ {
		s := sum[i+m-1] - sum[i-1]
		if l.Len() < k {
			for e = l.Front(); (e != nil) && e.Value.(el).value < s; e = e.Next() {
			}

			if e != nil {
				l.InsertBefore(el{i, s}, e)
			} else {
				l.PushBack(el{i, s})
			}
		} else {
			for e = l.Front(); (e != nil) && e.Value.(el).value < s; e = e.Next() {
			}

			if e != nil {
				if e.Value.(el).value < s {
					l.InsertBefore(el{i, s}, e)
					l.Remove(l.Front())
				}
			} else {
				l.PushBack(el{i, s})
				l.Remove(l.Front())
			}
		}
	}

	x = 0
	if m > 1 {
		for e := l.Front(); e != nil; e = e.Next() {
			x += e.Value.(el).value
		}
	} else {
		for e := l.Front(); e != nil; e = e.Next() {
			x += e.Value.(el).value
		}
	}
	fmt.Println(x)
}

package main

import (
	"container/list"
	"fmt"
)

type el struct {
	index int
	value uint64
}

func main() {
	var n, m, k int
	var x, s uint64
	fmt.Scanf("%d %d %d\n", &n, &m, &k)
	sum := make([]uint64, n)
	var e *list.Element
	l := list.New()
	fmt.Scanf("%d", &sum[0])

	for i := 1; i < n; i++ {
		fmt.Scanf("%d", &x)
		sum[i] = sum[i-1] + x
	}

	l.PushBack(el{0, sum[m-1]})

	for i := 1; i < n-(m-1); i++ {
		s = sum[i+m-1] - sum[i-1]
		if l.Len() < k {
			for e = l.Front(); (e != nil) && e.Value.(el).value < s; e = e.Next() {
			}

			if e != nil {
				l.InsertBefore(el{i, s}, e)
			} else {
				l.PushBack(el{i, s})
			}
		} else {
			for e = l.Front(); (e != nil) && e.Value.(el).value < s; e = e.Next() {
			}

			if e != nil {
				if (l.Front()).Value.(el).value < s {
					l.InsertBefore(el{i, s}, e)
					l.Remove(l.Front())
				}
			} else {
				l.PushBack(el{i, s})
				l.Remove(l.Front())
			}
		}
	}

	x = 0
	for e := l.Front(); e != nil; e = e.Next() {
		x += e.Value.(el).value
	}
	fmt.Println(x)
}

package main

import (
	"container/list"
	"fmt"
)

func main() {
	var n, m, k int
	var x, s, max uint64
	fmt.Scanf("%d %d %d\n", &n, &m, &k)
	sum := make([]uint64, n)
	var e *list.Element
	fmt.Scanf("%d", &sum[0])

	for i := 1; i < n; i++ {
		fmt.Scanf("%d", &x)
		sum[i] = sum[i-1] + x
	}

	max = 0
	for offset := 0; offset <= m-1; offset++ {
		l := list.New()
		if offset == 0 {
			x = sum[offset]
		} else {
			x = sum[offset] - sum[offset-1]
		}
		l.PushBack(x)

		for i := offset + m; i < n-(m-1); i += m {
			s = sum[i+m-1] - sum[i-1]
			if l.Len() < k {
				for e = l.Front(); (e != nil) && e.Value.(uint64) < s; e = e.Next() {
				}

				if e != nil {
					l.InsertBefore(s, e)
				} else {
					l.PushBack(s)
				}
				x += s
			} else {
				for e = l.Front(); (e != nil) && e.Value.(uint64) < s; e = e.Next() {
				}

				if e != nil {
					if (l.Front()).Value.(uint64) < s {
						l.InsertBefore(s, e)
						l.Remove(l.Front())
						x += s - l.Front().Value.(uint64)
					}
				} else {
					l.PushBack(s)
					x += s - l.Front().Value.(uint64)
					l.Remove(l.Front())
				}
			}
		}
		if x > max {
			max = x
		}
	}

	fmt.Println(max)
}

package main

import (
	"container/list"
	"fmt"
)

func main() {
	var n, m, k int
	var x, s, max uint64
	fmt.Scanf("%d %d %d\n", &n, &m, &k)
	sum := make([]uint64, n)
	var e *list.Element
	fmt.Scanf("%d", &sum[0])

	for i := 1; i < n; i++ {
		fmt.Scanf("%d", &x)
		sum[i] = sum[i-1] + x
	}

	max = 0
	for offset := 0; offset <= m-1; offset++ {
		//fmt.Println()
		if m-1+offset >= n {
			break
		}
		l := list.New()
		if offset == 0 {
			x = sum[m-1+offset]
		} else {
			x = sum[m-1+offset] - sum[offset-1]
		}
		l.PushBack(x)
		//		fmt.Printf("%d ", x)

		for i := offset + m; i < n-(m-1); i += m {
			s = sum[i+m-1] - sum[i-1]
			if l.Len() < k {
				for e = l.Front(); (e != nil) && e.Value.(uint64) < s; e = e.Next() {
				}

				if e != nil {
					l.InsertBefore(s, e)
				} else {
					l.PushBack(s)
				}
				x += s
			} else {
				for e = l.Front(); (e != nil) && e.Value.(uint64) < s; e = e.Next() {
				}

				if e != nil {
					if (l.Front()).Value.(uint64) < s {
						l.InsertBefore(s, e)
						l.Remove(l.Front())
						x += s - l.Front().Value.(uint64)
					}
				} else {
					l.PushBack(s)
					x += s - l.Front().Value.(uint64)
					l.Remove(l.Front())
				}
			}
		}
		if x > max {
			max = x
		}
	}

	fmt.Println(max)
}

package main

import (
	"container/list"
	"fmt"
)

type el struct {
	index int
	value int
}

func main() {
	var n, m, k int
	fmt.Scanf("%d %d %d\n", &n, &m, &k)
	a := make([]int, n)
	l := list.New()
	var e *list.Element

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

	for i := 0; i < n-(m-1); i++ {
		s := a[i] + a[i+m-1]
		if l.Len() < k {
			for e = l.Front(); (e != nil) && e.Value.(el).value < s; e = e.Next() {
			}

			if e != nil {
				l.InsertBefore(el{i, s}, e)
			} else {
				l.PushBack(el{i, s})
			}
		} else {
			for e = l.Front(); (e != nil) && e.Value.(el).value < s; e = e.Next() {
			}

			if e != nil {
				if e.Value.(el).value < s {
					l.InsertBefore(el{i, s}, e)
					l.Remove(l.Front())
				}
			} else {
				l.PushBack(el{i, s})
				l.Remove(l.Front())
			}
		}
	}

	sum := 0
	if m > 1 {
		for e := l.Front(); e != nil; e = e.Next() {
			sum += a[e.Value.(el).index] + a[e.Value.(el).index+m-1]
		}
	} else {
		for e := l.Front(); e != nil; e = e.Next() {
			sum += a[e.Value.(el).index]
		}
	}
	fmt.Println(sum)
}


New Year is just around the corner, which means that in School 179, preparations for the concert are in full swing.There are $$$n$$$ classes in the school, numbered from $$$1$$$ to $$$n$$$, the $$$i$$$-th class has prepared a scene of length $$$a_i$$$ minutes.As the main one responsible for holding the concert, Idnar knows that if a concert has $$$k$$$ scenes of lengths $$$b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_k$$$ minutes, then the audience will get bored if there exist two integers $$$l$$$ and $$$r$$$ such that $$$1 \le l \le r \le k$$$ and $$$\gcd(b_l, b_{l + 1}, \ldots, b_{r - 1}, b_r) = r - l + 1$$$, where $$$\gcd(b_l, b_{l + 1}, \ldots, b_{r - 1}, b_r)$$$ is equal to the greatest common divisor (GCD) of the numbers $$$b_l$$$, $$$b_{l + 1}$$$, $$$\ldots$$$, $$$b_{r - 1}$$$, $$$b_r$$$.To avoid boring the audience, Idnar can ask any number of times (possibly zero) for the $$$t$$$-th class ($$$1 \le t \le k$$$) to make a new scene $$$d$$$ minutes in length, where $$$d$$$ can be any positive integer. Thus, after this operation, $$$b_t$$$ is equal to $$$d$$$. Note that $$$t$$$ and $$$d$$$ can be different for each operation.For a sequence of scene lengths $$$b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_{k}$$$, let $$$f(b)$$$ be the minimum number of classes Idnar has to ask to change their scene if he wants to avoid boring the audience.Idnar hasn't decided which scenes will be allowed for the concert, so he wants to know the value of $$$f$$$ for each non-empty prefix of $$$a$$$. In other words, Idnar wants to know the values of $$$f(a_1)$$$, $$$f(a_1$$$,$$$a_2)$$$, $$$\ldots$$$, $$$f(a_1$$$,$$$a_2$$$,$$$\ldots$$$,$$$a_n)$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of classes in the school. The second line contains $$$n$$$ positive integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the lengths of the class scenes.

NoteIn the first test we can change $$$1$$$ to $$$2$$$, so the answer is $$$1$$$.In the second test:   $$$[1]$$$ can be changed into $$$[2]$$$,  $$$[1, 4]$$$ can be changed into $$$[3, 4]$$$,  $$$[1, 4, 2]$$$ can be changed into $$$[2, 3, 2]$$$.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1632D(_r io.Reader, _w io.Writer) {
	out := bufio.NewWriter(_w)
	defer out.Flush()
	buf := make([]byte, 1<<12)
	_i := len(buf)
	rc := func() byte {
		if _i >= len(buf) {
			_r.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}

	type result struct{ v, l, r int }
	set := []result{}
	n := r()
	ans := 0
o:
	for i := 0; i < n; i++ {
		v := r()
		if v == 1 {
			set = set[:0]
			ans++
			Fprint(out, ans, " ")
			continue
		}
		for j, p := range set {
			g := gcd(p.v, v)
			if l := i + 1 - g; p.l <= l && l <= p.r {
				set = set[:0]
				ans++
				Fprint(out, ans, " ")
				continue o
			}
			set[j].v = g
		}
		set = append(set, result{v, i, i})
		k := 0
		for _, q := range set[1:] {
			if set[k].v != q.v {
				k++
				set[k] = q
			} else {
				set[k].r = q.r
			}
		}
		set = set[:k+1]
		Fprint(out, ans, " ")
	}
}

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

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

package main

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

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

	type result struct{ v, l, r int }
	set := []result{}
	var n, v, ans int
	Fscan(in, &n)
o:
	for i := 0; i < n; i++ {
		Fscan(in, &v)
		if v == 1 {
			set = set[:0]
			ans++
			Fprint(out, ans, " ")
			continue
		}
		for j, p := range set {
			g := gcd(p.v, v)
			if l := i + 1 - g; p.l <= l && l <= p.r {
				set = set[:0]
				ans++
				Fprint(out, ans, " ")
				continue o
			}
			set[j].v = g
		}
		set = append(set, result{v, i, i})
		k := 0
		for _, q := range set[1:] {
			if set[k].v != q.v {
				k++
				set[k] = q
			} else {
				set[k].r = q.r
			}
		}
		set = set[:k+1]
		Fprint(out, ans, " ")
	}
}

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

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

package main

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

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

	type result struct{ v, l, r int }
	set := []result{}
	var n, v, ans int
	Fscan(in, &n)
o:
	for i := 0; i < n; i++ {
		Fscan(in, &v)
		if v == 1 {
			set = nil
			ans++
			Fprint(out, ans, " ")
			continue
		}
		for j, p := range set {
			g := gcd(p.v, v)
			if l := i + 1 - g; p.l <= l && l < p.r {
				set = nil
				ans++
				Fprint(out, ans, " ")
				continue o
			}
			set[j].v = g
		}
		set = append(set, result{v, i, i + 1})
		k := 0
		for _, q := range set[1:] {
			if set[k].v != q.v {
				k++
				set[k] = q
			} else {
				set[k].r = q.r
			}
		}
		set = set[:k+1]
		Fprint(out, ans, " ")
	}
}

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

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

package main

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

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

func flush()                            { out.Flush() }
func scan(a ...interface{})             { fmt.Fscan(in, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(out, f, a...) }
func assert(f bool) {
	if !f {
		panic("gg")
	}
}

// ----------------------------- TEMPLATE END ----------------------------------

func gcd(x, y int) int {
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

var bit []int

func updateBit(i, v int) {
	for i++; i < len(bit); i += (i & -i) {
		bit[i] = gcd(bit[i], v)
	}
}

func queryBit(i int) int {
	r := 0
	for i++; i > 0; i -= (i & -i) {
		r = gcd(r, bit[i])
	}
	return r
}

var n int
var dp []int

func gcdFrom(i int) int {
	return queryBit(n - i + 1)
}

func main() {
	defer flush()
	scan(&n)

	bit = make([]int, n+10)
	dp = make([]int, n+1)
	var a []int = make([]int, n+1)
	for i := 1; i <= n; i++ {
		scan(&a[i])
		updateBit(n-i+1, a[i])

		lo := 1
		hi := i
		mi := i
		var segGcd, segLen int
		for lo < hi {
			mi = (lo + hi) / 2
			segGcd = gcdFrom(mi)
			segLen = i - mi + 1
			if segGcd < segLen {
				lo = mi + 1
			} else {
				hi = mi
			}
		}
		segGcd = gcdFrom(lo)
		segLen = i - lo + 1
		// for j := 1; j <= i; j++ {
		// 	printf("gcd[%d..%d]=%d\n", j, i, gcdFrom(j))
		// }
		// printf("lo = %d\n", lo)
		if segGcd == segLen {
			// printf("at %d found length of %d. gcd=%d\n", i, segLen, segGcd)
			dp[i] = dp[i-segLen] + 1
		} else {
			dp[i] = dp[i-1]
		}
	}
	for i := 1; i <= n; i++ {
		if i > 1 {
			printf(" ")
		}
		printf("%d", dp[i])
	}
	printf("\n")
}


On a strip of land of length $$$n$$$ there are $$$k$$$ air conditioners: the $$$i$$$-th air conditioner is placed in cell $$$a_i$$$ ($$$1 \le a_i \le n$$$). Two or more air conditioners cannot be placed in the same cell (i.e. all $$$a_i$$$ are distinct).Each air conditioner is characterized by one parameter: temperature. The $$$i$$$-th air conditioner is set to the temperature $$$t_i$$$.    Example of strip of length $$$n=6$$$, where $$$k=2$$$, $$$a=[2,5]$$$ and $$$t=[14,16]$$$. For each cell $$$i$$$ ($$$1 \le i \le n$$$) find it's temperature, that can be calculated by the formula $$$$$$\min_{1 \le j \le k}(t_j + |a_j - i|),$$$$$$where $$$|a_j - i|$$$ denotes absolute value of the difference $$$a_j - i$$$.In other words, the temperature in cell $$$i$$$ is equal to the minimum among the temperatures of air conditioners, increased by the distance from it to the cell $$$i$$$.Let's look at an example. Consider that $$$n=6, k=2$$$, the first air conditioner is placed in cell $$$a_1=2$$$ and is set to the temperature $$$t_1=14$$$ and the second air conditioner is placed in cell $$$a_2=5$$$ and is set to the temperature $$$t_2=16$$$. In that case temperatures in cells are:  temperature in cell $$$1$$$ is: $$$\min(14 + |2 - 1|, 16 + |5 - 1|)=\min(14 + 1, 16 + 4)=\min(15, 20)=15$$$;  temperature in cell $$$2$$$ is: $$$\min(14 + |2 - 2|, 16 + |5 - 2|)=\min(14 + 0, 16 + 3)=\min(14, 19)=14$$$;  temperature in cell $$$3$$$ is: $$$\min(14 + |2 - 3|, 16 + |5 - 3|)=\min(14 + 1, 16 + 2)=\min(15, 18)=15$$$;  temperature in cell $$$4$$$ is: $$$\min(14 + |2 - 4|, 16 + |5 - 4|)=\min(14 + 2, 16 + 1)=\min(16, 17)=16$$$;  temperature in cell $$$5$$$ is: $$$\min(14 + |2 - 5|, 16 + |5 - 5|)=\min(14 + 3, 16 + 0)=\min(17, 16)=16$$$;  temperature in cell $$$6$$$ is: $$$\min(14 + |2 - 6|, 16 + |5 - 6|)=\min(14 + 4, 16 + 1)=\min(18, 17)=17$$$. For each cell from $$$1$$$ to $$$n$$$ find the temperature in it.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the input. Then test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first line contains two integers $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) and $$$k$$$ ($$$1 \le k \le n$$$) — the length of the strip of land and the number of air conditioners respectively. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — positions of air conditioners on the strip of land. The third line contains $$$k$$$ integers $$$t_1, t_2, \ldots, t_k$$$ ($$$1 \le t_i \le 10^9$$$) — temperatures of air conditioners. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case output $$$n$$$ integers separated by space: temperatures of air in cells.

package main

import (
	"bufio"
	"fmt"
	"os"
)
func min(x,y int)int{
	if x<y{
		return x
	}
	return y
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for c:=1;c<=t;c++{
		var n int
		var k int
		fmt.Fscan(in,&n,&k)
		p := make([]int,n+5)
		l := make([]int,n+5)
		v := make([]int,n+5)
		f := make([]int,n+5)
		b := make([]int,n+5)
		for i:=1;i<=k;i++{
			fmt.Fscan(in,&p[i])
		}
		for i:=1;i<=k;i++{
			fmt.Fscan(in,&v[i])
		}
		for i:=1;i<=k;i++{
			l[p[i]]=v[i]
		}
		for i:=1;i<=n;i++{
			if l[i]!=0&&f[i-1]==0{
				f[i]=l[i]
				continue
			}
			if l[i]!=0&&f[i-1]!=0{
				f[i] = min(f[i-1]+1,l[i])
				continue
			}
			if f[i-1]!=0{
				f[i] = f[i-1]+1
			}
		}
		for i:=n;i>=1;i--{
			if l[i]!=0 && b[i+1]==0{
				b[i] = l[i]
				continue
			}
			if l[i]!=0&&b[i+1]!=0{
				b[i] = min(b[i+1]+1,l[i])
				continue
			}
			if b[i+1]!=0{
				b[i]=b[i+1]+1
			}
		}
		for i:=1;i<=n;i++{
			var ans int
			if f[i]==0{
				ans = b[i]
			}
			if b[i]==0{
				ans = f[i]
			}
			if f[i]!=0&&b[i]!=0{
				ans = min(f[i],b[i])
			}
			fmt.Fprintf(out,"%d ", ans)
		}
		fmt.Fprintf(out,"\n")
	}
}

package main

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

const MAX_INT int = 2_000_000_000

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var test int
	fmt.Fscan(in, &test)
	for ; test > 0; test-- {
		var n, k int
		fmt.Fscan(in, &n, &k)

		a := make([]int, k)
		t := make([]int, k)
		ar := make([]int, n)
		for i := range a {
			fmt.Fscan(in, &a[i])
		}
		for i := range t {
			fmt.Fscan(in, &t[i])
		}
		for i := range a {
			ar[a[i]-1] = t[i]
		}
		for i := range ar {
			if ar[i] == 0 {
				ar[i] = MAX_INT
			}
		}

		L := make([]int, n)
		R := make([]int, n)
		p := MAX_INT - 1
		for i := 0; i < n; i++ {
			p = Min(p+1, ar[i])
			L[i] = p
		}
		p = MAX_INT - 1
		for i := n - 1; i >= 0; i-- {
			p = Min(p+1, ar[i])
			R[i] = p
		}

		for i := range L {
			if i != 0 {
				fmt.Fprint(out, " ")
			}
			fmt.Fprint(out, Min(L[i], R[i]))
		}
		fmt.Fprintln(out)
	}
}

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

package main

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

var in *bufio.Reader

type airCondi struct {
	idx, t int
}

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

func solve() {
	var n, k int
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &k)

	airs := make([]airCondi, k)
	for i := 0; i < k; i++ {
		fmt.Fscan(in, &airs[i].idx)
		airs[i].idx--
	}
	for i := 0; i < k; i++ {
		fmt.Fscan(in, &airs[i].t)
	}

	sort.Slice(airs, func(i, j int) bool {
		return airs[i].idx < airs[j].idx
	})

	stack := []airCondi{airs[0]}
	for i := 1; i < k; i++ {
		last := stack[len(stack)-1]
		if airs[i].t-airs[i].idx >= last.t-last.idx {
			continue
		}
		for len(stack) > 0 {
			last := stack[len(stack)-1]
			if last.t+last.idx >= airs[i].t+airs[i].idx {
				stack = stack[:len(stack)-1]
			} else {
				break
			}
		}
		stack = append(stack, airs[i])
	}

	i := 0
	for si := 0; si < len(stack); si++ {
		air := stack[si]
		for ; i <= air.idx; i++ {
			curT := air.t + air.idx - i
			if si > 0 {
				last := stack[si-1]
				curT = min(curT, last.t+i-last.idx)
			}
			fmt.Printf("%d ", curT)
		}
	}
	air := stack[len(stack)-1]
	for ; i < n; i++ {
		curT := air.t + i - air.idx
		fmt.Printf("%d ", curT)
	}
	fmt.Println()
}

func main() {
	in = bufio.NewReader(os.Stdin)

	var q int
	fmt.Fscan(in, &q)

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

package main

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

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

func init() {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 4096), 1e9)
}

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

func sint64() int64 {
	s := sstring()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func sint64s(n int64) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	return a
}

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

func main() {
	defer writer.Flush()
	for t := sint64(); t > 0; t-- {
		n := sint64()
		k := sint64()
		a := sint64s(k)
		t := sint64s(k)
		res := sol(n, k, a, t)
		for _, r := range res {
			printf("%d ", r)
		}
		printf("\n")
	}
}

func sol(n, k int64, a, t []int64) []int64 {
	ret := make([]int64, n)
	p := prep(k, a, t)
	// if k != int64(len(p)) {
	// 	printf("check: %v %v %v\n", n, k, p)
	// }
	nxt := int64(0)
	for i := range ret {
		idx1 := int64(i) + 1
		if nxt == int64(len(p)) {
			ret[i] = p[nxt-1][1] + (idx1 - p[nxt-1][0])
			continue
		}
		if idx1 == p[nxt][0] {
			ret[i] = p[nxt][1]
			nxt++
			continue
		}
		if nxt == 0 {
			ret[i] = p[nxt][1] + (p[nxt][0] - idx1)
			continue
		}
		tmpPrev := p[nxt-1][1] + (idx1 - p[nxt-1][0])
		tmpNxt := p[nxt][1] + (p[nxt][0] - idx1)
		ret[i] = min(tmpPrev, tmpNxt)
	}
	return ret
}

func prep(k int64, a, t []int64) [][2]int64 {
	tmp := make([][2]int64, k) // idx, temp
	for i := range tmp {
		tmp[i] = [2]int64{a[i], t[i]}
	}
	sort.Slice(tmp, func(il, ir int) bool {
		return tmp[il][0] < tmp[ir][0]
	})
	ret := [][2]int64{}
	for i := range tmp {
		for len(ret) > 0 {
			last := ret[len(ret)-1]
			if last[1]-tmp[i][1] > tmp[i][0]-last[0] {
				ret = ret[:len(ret)-1]
			} else {
				break
			}
		}
		if len(ret) > 0 {
			last := ret[len(ret)-1]
			if tmp[i][1]-last[1] > tmp[i][0]-last[0] {
				continue
			}
		}
		ret = append(ret, tmp[i])
	}
	return ret
}

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

package main

import (
	"bufio"
	. "fmt"
	"io"
	"io/ioutil"
	"os"
	"sort"
	"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()
	type pair struct{ p, t, y, z int }

	solve := func(Case int) {
		var n, k int
		Fscan(in, &n, &k)
		a := make([]pair, k)
		for i := range a {
			Fscan(in, &a[i].p)
		}
		for i := range a {
			Fscan(in, &a[i].t)
			a[i].y = a[i].t + a[i].p - 1
			a[i].z = a[i].t + n - a[i].p
		}

		ans := make([]int, n+1)
		for _i := range ans {
			ans[_i] = 2e9
		}
		sort.Slice(a, func(i, j int) bool { return a[i].y < a[j].y })
		cur := 1
		for _, p := range a {
			for cur <= p.p {
				ans[cur] = min(ans[cur], p.t + p.p - cur)
				cur++
			}
		}
		sort.Slice(a, func(i, j int) bool { return a[i].z < a[j].z })
		cur = n
		for _, p := range a {
			for cur >= p.p {
				ans[cur] = min(ans[cur], p.t +cur- p.p )
				cur--
			}
		}

		for _, v := range ans[1:] {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}

	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 min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

package main

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

const MAX_INT int = 1_000_000_100

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var test int
	fmt.Fscan(in, &test)
	for ; test > 0; test-- {
		var n, k int
		fmt.Fscan(in, &n, &k)

		a := make([]int, k)
		t := make([]int, k)
		ar := make([]int, n)
		for i := range a {
			fmt.Fscan(in, &a[i])
		}
		for i := range t {
			fmt.Fscan(in, &t[i])
		}
		for i := range a {
			ar[a[i]-1] = t[i]
		}
		for i := range ar {
			if ar[i] == 0 {
				ar[i] = MAX_INT
			}
		}

		L := make([]int, n)
		R := make([]int, n)
		p := MAX_INT - 1
		for i := 0; i < n; i++ {
			p = Min(p+1, ar[i])
			L[i] = p
		}
		p = MAX_INT - 1
		for i := n - 1; i >= 0; i-- {
			p = Min(p+1, ar[i])
			R[i] = p
		}

		for i := range L {
			if i != 0 {
				fmt.Fprint(out, " ")
			}
			fmt.Fprint(out, Min(L[i], R[i]))
		}
		fmt.Fprintln(out)
	}
}

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


You are given two positive integers $$$a$$$ and $$$b$$$.In one move, you can change $$$a$$$ in the following way:  Choose any positive odd integer $$$x$$$ ($$$x > 0$$$) and replace $$$a$$$ with $$$a+x$$$;  choose any positive even integer $$$y$$$ ($$$y > 0$$$) and replace $$$a$$$ with $$$a-y$$$. You can perform as many such operations as you want. You can choose the same numbers $$$x$$$ and $$$y$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is given as two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case, print the answer — the minimum number of moves required to obtain $$$b$$$ from $$$a$$$ if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.

NoteIn the first test case, you can just add $$$1$$$.In the second test case, you don't need to do anything.In the third test case, you can add $$$1$$$ two times.In the fourth test case, you can subtract $$$4$$$ and add $$$1$$$.In the fifth test case, you can just subtract $$$6$$$.

 package main

 import (
         "fmt"
 )

 func main() {

         t := 0
         fmt.Scanf("%d\n", &t)
         for i := 0; i < t; i++ {
             var a,b int
             fmt.Scanf("%d %d\n", &a,&b)
             if a == b{
                 fmt.Println(0)

             }else if a < b{
                 if (b-a)%2 == 0{
                     fmt.Println(2)
                 }else{
                     fmt.Println(1)
                 }
             }else{
                 if (a-b)%2 == 0{
                     fmt.Println(1)
                 }else{
                     fmt.Println(2)
                 }
             }

        }
 }

package main

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

func main() {
	var t, a, b int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(in, &a, &b)
		if a < b {
			if b%2 == a%2 {
				fmt.Println(2)
			} else {
				fmt.Println(1)
			}
		} else if a > b {
			if b%2 == a%2 {
				fmt.Println(1)
			} else {
				fmt.Println(2)
			}
		} else {
			fmt.Println(0)
		}
	}
}

// A. Add Odd or Subtract Even
/*
You are given two positive integers 𝑎 and 𝑏.

In one move, you can change 𝑎 in the following way:

    Choose any positive odd integer 𝑥 (𝑥>0) and replace 𝑎 with 𝑎+𝑥;
    choose any positive even integer 𝑦 (𝑦>0) and replace 𝑎 with 𝑎−𝑦.

You can perform as many such operations as you want. You can choose the same numbers 𝑥 and 𝑦 in different moves.

Your task is to find the minimum number of moves required to obtain 𝑏 from 𝑎. It is guaranteed that you can always obtain 𝑏 from 𝑎.

You have to answer 𝑡 independent test cases.

Input
The first line of the input contains one integer 𝑡 (1≤𝑡≤104) — the number of test cases.

Then 𝑡 test cases follow. Each test case is given as two space-separated integers 𝑎 and 𝑏 (1≤𝑎,𝑏≤109).

Output
For each test case, print the answer — the minimum number of moves required to obtain 𝑏 from 𝑎 if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain 𝑏 from 𝑎.

Example
Input
5
2 3
10 10
2 4
7 4
9 3

Output
1
0
2
2
1

Note
In the first test case, you can just add 1.

In the second test case, you don't need to do anything.

In the third test case, you can add 1 two times.

In the fourth test case, you can subtract 4 and add 1.

In the fifth test case, you can just subtract 6.
*/
package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	input1, _ := reader.ReadString('\n')
	n, _ := strconv.Atoi(strings.TrimSpace(input1))

	for ; n > 0; n-- {
		input2, _ := reader.ReadString('\n')
		arr := strings.Split(strings.TrimSpace(input2), " ")
		a, _ := strconv.Atoi(arr[0])
		b, _ := strconv.Atoi(arr[1])

		if a == b {
			fmt.Println(0)
		} else if a > b {
			if (a-b)%2 == 0 {
				fmt.Println(1)
			} else {
				fmt.Println(2)
			}
		} else if a < b {
			if (b-a)%2 == 1 {
				fmt.Println(1)
			} else {
				fmt.Println(2)
			}
		}
	}
}

package main

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

func toInt(buf []byte) (n int) {
	for _, v := range buf {
		n = n * 10 + int(v - '0')
	}
	return
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	scanner.Scan()
	t := toInt(scanner.Bytes())

	for t > 0 {
		scanner.Scan()
		a := toInt(scanner.Bytes())
		scanner.Scan()
		b := toInt(scanner.Bytes())
		if a == b {
			fmt.Println(0)
			t--
			continue
		}
		if b > a {
			d := b - a
			if d % 2 != 0 || d == 1 {
				fmt.Println(1)
			}else {
				fmt.Println(2)
			}
		}else {
			d := b - a
			if d % 2 == 0 {
				fmt.Println(1)
			}else {
				fmt.Println(2)
			}
		}

		t--
	}

}

package main

import (
	"bufio"
	"os"
)

func toInt(buf []byte) (n int) {
	for _, v := range buf {
		n = n * 10 + int(v - '0')
	}
	return
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	scanner.Scan()
	t := toInt(scanner.Bytes())

	for t > 0 {
		scanner.Scan()
		a := toInt(scanner.Bytes())
		scanner.Scan()
		b := toInt(scanner.Bytes())
		if a == b {
			out.WriteString("0\n")
			t--
			continue
		}
		if b > a {
			d := b - a
			if d % 2 != 0 {
				out.WriteString("1\n")
			}else {
				out.WriteString("2\n")
			}
		}else {
			d := b - a
			if d % 2 == 0 {
				out.WriteString("1\n")
			}else {
				out.WriteString("2\n")
			}
		}

		t--
	}

}

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	for ; t > 0; t-- {
		var a, b int
		fmt.Scan(&a, &b)
		if a == b {
			fmt.Println(0)
		} else if (b > a && (b-a)%2 == 1) || (b < a && (a-b)%2 == 0) {
			fmt.Println(1)
		} else {
			fmt.Println(2)
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scan(&t)
	for ; t > 0; t-- {
		var a, b int
		fmt.Scan(&a, &b)
		if a == b {
			fmt.Println(0)
		} else if a > b {
			if a%2 != b%2 {
				fmt.Println(2)
			} else {
				fmt.Println(1)
			}
		} else {
			if a%2 != b%2 {
				fmt.Println(1)
			} else {
				fmt.Println(2)
			}
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var tests int
	fmt.Scanf("%d\n", &tests)

	as := make([]int, tests)
	bs := make([]int, tests)

	for i := 0; i < tests; i++ {
		var a, b int
		fmt.Scanf("%d %d\n", &a, &b)
		as[i] = a
		bs[i] = b
	}

	for i := range as {
		fmt.Println(steps(as[i], bs[i]))
	}
}

func steps(a, b int) int {
	if a < b {
		// increase a by odd number.
		delta := b - a
		if isEven(delta) {
			delta--
		}
		// calculate again.
		return steps(a+delta, b) + 1
	}

	if a > b {
		// decrease a by even number.
		delta := a - b
		if isOdd(delta) {
			delta++
		}
		// calculate again.
		return steps(a-delta, b) + 1
	}

	return 0
}

func isOdd(num int) bool {
	return num%2 != 0
}

func isEven(num int) bool {
	return num%2 == 0
}

package main

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

type Scan struct {
	f *os.File
	in *bufio.Reader
	out *bufio.Writer
}

func setup() *Scan {
	r := &Scan{ f: nil }

	inputFile := os.Getenv("INPUT_FILE")
	if inputFile != "" {
		var err error
		if r.f, err = os.Open(inputFile); err == nil {
			os.Stdin = r.f
		}
	}
	r.in = bufio.NewReader(os.Stdin)
	r.out = bufio.NewWriter(os.Stdout)

	return r
}

func (r *Scan) close() {
	if r.f != nil {
		r.f.Close()
	}
}

func (r *Scan) readString() string {
	var x string
	fmt.Fscan(r.in, &x)
	return x
}

func (r *Scan) readInt() int {
	x, err := strconv.Atoi(r.readString())
	if err != nil {
		panic(err)
	}
	return x
}

func (r *Scan) strings(refs ... *string) {
	for _, ref := range refs {
		*ref = r.readString()
	}
}

func (r *Scan) ints(refs ... *int) {
	for _, ref := range refs {
		*ref = r.readInt()
	}
}

func (r *Scan) print(s string) {
	fmt.Printf("%s", s)
}

func main() {
	scan := setup()

	var t, a, b int

	scan.ints(&t)
	for tc := 0; tc < t; tc++ {
		scan.ints(&a, &b)
		diff := b-a
		mves := 0
		if diff > 0 {
			if (diff%2) == 1 {
				mves = 1
			} else {
				mves = 2
			}
		} else if diff < 0 {
			if (-diff)%2 == 1 {
				mves = 2
			} else {
				mves = 1
			}
		}
		fmt.Printf("%d\n", mves)
	}

	scan.close()
}

package main

import (
	"fmt"
	"os"
)

var f *os.File = nil

func setup() {
	inputFile := os.Getenv("INPUT_FILE")
	if inputFile != "" {
		var err error
		if f, err = os.Open(inputFile); err == nil {
			os.Stdin = f
		}
	}
}

func cleanUp() {
	if f != nil {
		f.Close()
	}
}

func main() {
	setup()

	var t, a, b int

	fmt.Scanf("%d\n", &t)
	for tc := 0; tc < t; tc++ {
		fmt.Scanf("%d %d\n", &a, &b)
		diff := b-a
		mves := 0
		if diff > 0 {
			if (diff%2) == 1 {
				mves = 1
			} else {
				mves = 2
			}
		} else if diff < 0 {
			if (-diff)%2 == 1 {
				mves = 2
			} else {
				mves = 1
			}
		}
		fmt.Printf("%d\n", mves)
	}

	cleanUp()
}

package main

import "fmt"

type arr struct {
	x int64
	y int64
}

func main() {
	n:=int64(0)
	fmt.Scanln(&n)
	ad:=make([]arr,n)
	for i:=int64(0);i<n ; i++ {
		fmt.Scanln(&ad[i].x,&ad[i].y)
	}
	for i:=int64(0);i<n ; i++  {
		if ad[i].x<ad[i].y {
			if (ad[i].y-ad[i].x)%2!=0 {
				fmt.Println(1)
			}else {
				fmt.Println(2)
			}
		}else if ad[i].x>ad[i].y {
			if (ad[i].y-ad[i].x)%2!=0 {
				fmt.Println(2)
			}else {
				fmt.Println(1)
			}
		}else {
			fmt.Println(0)
		}
	}
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buffer := make([]byte, 3*1024*1024)
	scanner.Buffer(buffer, 10*1024*1024)
	scanner.Split(bufio.ScanWords)

	input := func() uint64 {
		scanner.Scan()
		i, _ := strconv.ParseUint(scanner.Text(), 10, 64)
		return i
	}

	for t := input(); t > 0; t-- {
		a, b := input(), input()

		if a == b {
			fmt.Println(0)
		} else if b < a {
			if (a-b)%2 == 0 {
				fmt.Println(1)
			} else {
				fmt.Println(2)
			}
		} else if b > a {
			if (b-a)%2 == 1 {
				fmt.Println(1)
			} else {
				fmt.Println(2)
			}
		}
	}
}

package main

import "fmt"

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

	for i := 0; i < t; i++ {
		var a, b int
		fmt.Scan(&a, &b)

		if a == b {
			fmt.Println(0)
		} else if a > b {
			if (a - b) % 2 == 0 {
				// subtract even, one move
				fmt.Println(1)
			} else {
				// odd difference, subtract even and add one
				fmt.Println(2)
			}
		} else if b > a {
			if (a - b) % 2 == 0 {
				// add odd twice
				fmt.Println(2)
			} else {
				// add odd once
				fmt.Println(1)
			}
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for i := 1; i <= t; i++ {
		var a, b int
		fmt.Scanf("%d %d\n", &a, &b)
		if a == b {
			fmt.Printf("%d\n", 0)
		} else if a > b {
			if (a-b)%2 == 0 {
				fmt.Printf("%d\n", 1)
			} else {
				fmt.Printf("%d\n", 2)
			}
		} else {
			if (b-a)%2 == 0 {
				fmt.Printf("%d\n", 2)
			} else {
				fmt.Printf("%d\n", 1)
			}
		}
	}
}

/**
 * Copyright shopee
 * @Author : Yuxiang.Lei
 * @MailBox: Yuxiang.Lei@shopee.com
 * @Date : 2020-02-24
 * @Version: v2.4
 **/

package main

import "fmt"

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	for i := 0; i < cases; i++ {
		var a,b int
		fmt.Scanf("%d %d\n", &a, &b)
		if a==b {
			fmt.Println(0)
		} else if a > b {
			if (a-b) % 2 == 0 {
				fmt.Println(1)
			} else {
				fmt.Println(2)
			}
		} else {
			if (b-a) % 2 == 0 {
				fmt.Println(2)
			} else {
				fmt.Println(1)
			}
		}
	}
}

/**
 * Copyright shopee
 * @Author : Yuxiang.Lei
 * @MailBox: Yuxiang.Lei@shopee.com
 * @Date : 2020-02-24
 * @Version: v2.4
 **/

package main

import "fmt"

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	for i := 0; i < cases; i++ {
		var a,b int64
		fmt.Scanf("%d %d\n", &a, &b)
		if a==b {
			fmt.Println(0)
		} else if a > b {
			if (a-b) % 2 == 0 {
				fmt.Println(1)
			} else {
				fmt.Println(2)
			}
		} else {
			if (b-a) % 2 == 0 {
				fmt.Println(2)
			} else {
				fmt.Println(1)
			}
		}
	}
}

package main

import "fmt"

func solve(a int64, b int64) int64 {
	if a == b {
		return 0
	}
	if a < b {
		if (b-a)%2 == 0 {
			return 2
		}
		return 1
	} else {
		if (a-b)%2 == 0 {
			return 1
		}
		return 2
	}
}

func main() {
	var T int
	fmt.Scanf("%v\n", &T)

	for cas := 1; cas <= T; cas++ {
		var a, b int64
		fmt.Scanf("%v %v\n", &a, &b)
		fmt.Println(solve(a, b))
	}
}

package main

import (
	"fmt"
)

func main() {
	n := 0
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		a, b := 0, 0
		fmt.Scan(&a, &b)
		if a < b {
			if (b - a) % 2 == 0 {
				fmt.Println(2)
			} else {
				fmt.Println(1)
			}
		} else if b < a {
			if (a - b) % 2 == 0 {
				fmt.Println(1)
			} else {
				fmt.Println(2)
			}
		} else {
			fmt.Println(0)
		}
	}
}

package main
import."fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	var T, a, b int
	for Scan(&T); T > 0; T-- {
		Scan(&a, &b)
		c := 0
		if a != b {
			c = 1
			if a < b != ((b-a)&1 > 0) {
				c = 2
			}
		}
		Println(c)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var n uint16
	var a,b uint32
	fmt.Fscanf(in, "%d\n", &n)
	for k := 0; uint16(k) < n; k++{
		fmt.Fscanf(in, "%d %d\n", &a, &b)
		if a > b{
			// hasna
			d := a - b
			if d % 2 == 0{
				fmt.Println(1)
			}else{
				fmt.Println(2)
			}

		}else if b > a {
			// nemne
			d := b - a
			if d % 2 != 0{
				fmt.Println(1)
			}else{
				fmt.Println(2)
			}
		}else if a == b{
			fmt.Println(0)
		}
	}

}

package main

import(
	"fmt"
)

func main(){
	var t int
	fmt.Scan(&t)
	for i:=0;i<t;i++{
		var a,b int32
		fmt.Scan(&a,&b)
		if a==b{
			fmt.Println(0)
		}else if a>b{
			var res int32=a-b
			if res%2==0{
				fmt.Println(1)
			}else{
				fmt.Println(2)
			}
		}else{
			var res int32=b-a
			if res%2!=0{
				fmt.Println(1)
			}else {
				fmt.Println(2)
			}
		}
	}
}

package main

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

func main() {
	for t := ScanInt(); t > 0; t-- {
		a, b := ScanInt(), ScanInt()
		count := 0
		//for a != b {
		//	count++
		if a == b {
			count = 0
		} else if a < b {
			count = nextOdd(b - a)
			//fmt.Println("evenNum:", num)
			//a = a + num
		} else {
			count = prevEven(a - b)
			//fmt.Println("prevEven:", num)
			//a = a - num
		}
		//}

		//P(count)
		P(count)
	}

	close(O)
	oWg.Wait()
}

func prevEven(x int) int {
	if x%2 == 0 {
		return 1
	}
	return 2
}
func nextOdd(x int) int {
	if x%2 == 1 {
		return 1
	}
	return 2
}

/*********************** I/O ***********************/

var O chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var P func(a ...interface{}) (n int, err error)

func init() {
	P = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)

	O = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

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

func ScanWord() string { in.Scan(); return in.Text() }
func ScanInt() int     { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInt64() int64 { i, _ := strconv.ParseInt(ScanWord(), 10, 64); return i }
func ScanStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt()
	}
	return arr
}
func ScanInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt64()
	}
	return arr
}

/*********************** Utils ***********************/

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func SArr64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func MnMx(args ...int64) (int64, int64) {
	minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64)
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int64) int64 { mn, _ := MnMx(args...); return mn }
func Mx(args ...int64) int64 { _, mx := MnMx(args...); return mx }
func LCM(a, b int64) int64   { return a / GCD(a, b) * b }
func GCD(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scanf("%d \n", &t)
	for i := 0; i < t; i++ {
	    var a,b int
		fmt.Scanf("%d %d \n", &a, &b)

		var ans = -1
		if a == b {
			ans = 0
		} else if a < b {
			if (b-a)%2 == 0 {
				ans = 2
			} else {
				ans = 1
			}
		} else {
			if (a-b)%2 == 0 {
				ans = 1
			} else {
				ans = 2
			}
		}
		fmt.Println(ans)
	}
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for ; t > 0; t-- {
		var a, b int
		fmt.Scanf("%d %d\n", &a, &b)
		var diff = b - a
		if diff == 0 {
			fmt.Println(0)
		} else if diff > 0 {
			if diff%2 == 0 {
				fmt.Println(2)
			} else {
				fmt.Println(1)
			}
		} else {
			if diff%2 == 0{
				fmt.Println(1)
			} else{
				fmt.Println(2)
			}
		}
	}
}

package main

import "fmt"

func main() {
	var t, a, b int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		fmt.Scan(&a, &b)
		if a == b {
			fmt.Println(0)
		} else if b-a > 0 && (b-a)%2 == 1 {
			fmt.Println(1)
		} else if b-a < 0 && (b-a)%2 == 0 {
			fmt.Println(1)
		} else {
			fmt.Println(2)
		}
	}
}

package main

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

func init() {
	log.SetFlags(0)
}

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

	if reader.Scan() {
		if err := reader.Err(); err != nil {
			log.Fatalln(err)
		}
	}

	n, err := strconv.Atoi(reader.Text())
	if err != nil {
		log.Fatalln(err)
	}

	var results []string
	for i := 0; i < n; i++ {
		if reader.Scan() {
			if reader.Err() != nil {
				log.Fatalln(err)
			}
			results = append(results, calc(strings.TrimSpace(reader.Text())))
		}
	}

	for i, v := range results {
		if i > 0 {
			fmt.Print("\n")
		}
		fmt.Print(v)
	}
}

func calc(s string) string {
	ss := strings.Fields(s)
	if n := len(ss); n != 2 {
		log.Fatalf("expected 2, got %d", n)
	}

	a, err := strconv.Atoi(ss[0])
	if err != nil {
		log.Fatalln(err)
	}
	b, err := strconv.Atoi(ss[1])
	if err != nil {
		log.Fatalln(err)
	}

	// -------------------------------------------------------------------------

	if a == b {
		return fmt.Sprint(0)
	}

	if ((b - a) > 0) && ((b-a)%2 == 1) {
		return fmt.Sprint(1)
	}

	if ((a - b) > 0) && ((b-a)%2 == 0) {
		return fmt.Sprint(1)
	}

	return fmt.Sprint(2)
}

package main

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

func main () {
	in := bufio.NewReader(os.Stdin);
	out := bufio.NewWriter(os.Stdout);
	var t int;
	fmt.Fscan(in, &t);
	for i := 0; i < t; i++ {
		a, b := 0, 0;
		fmt.Fscan(in, &a, &b);
		if (a == b) {
			fmt.Fprintln(out, 0);
		} else if ((b - a) > 0 && (b - a) % 2 == 1) {
			fmt.Fprintln(out, 1);
		} else if ((b - a) < 0 && (b - a) % 2 == 0) {
			fmt.Fprintln(out, 1);
		} else {
			fmt.Fprintln(out, 2);
		}
	}
	out.Flush();
}

// https://codeforces.com/problemset/problem/1311/A
package main

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

func findMoves(x, y string) {
	a, _ := strconv.ParseInt(x, 10, 32)
	b, _ := strconv.ParseInt(y, 10, 32)
	var ans string
	if a == b {
		ans = "0"
	} else if (a % 2) == (b % 2) {
		if a > b {
			ans = "1"
		} else {
			ans = "2"
		}
	} else {
		if a < b {
			ans = "1"
		} else {
			ans = "2"
		}
	}
	fmt.Println(ans)
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	inputs, _ := strconv.ParseInt(scanner.Text(), 10, 32)
	var i int64
	for i = 0; i < inputs; i++ {
		var ab []string
		scanner.Scan()
		ab = strings.Split(scanner.Text(), " ")
		findMoves(ab[0], ab[1])
	}
}

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

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

func main() {
	s := bufio.NewScanner(os.Stdin)
	s.Buffer(make([]byte,1<<12), 1<<20)
	s.Split(bufio.ScanWords)

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

	n := scanInt(s)

	for i := 0; i < n; i++ {
		a, b := scanInt(s), scanInt(s)
		c := 0
		if a < b {
			if (b - a)%2 == 0 {
				c = 2
			} else {
				c = 1
			}
		} else if a > b {
			if (a - b)%2 == 0 {
				c = 1
			} else {
				c = 2
			}
		} else {
			c = 0
		}
		fmt.Fprintln(w, c)
	}
}

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { f += "\n"; fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { f += "\n"; fmt.Fscanf(reader, f, a...) }

func main() {
	defer writer.Flush()

	var t int
	scanf("%d", &t)

	for i := 0; i < t; i++ {
		var a, b int
		scanf("%d %d", &a, &b)

		if a == b {
			printf("0")
			continue
		}

		bit := ((b-a) % 2 == 1) || ((b-a) % 2 == -1)
		sign := (b-a) > 0

		if bit == sign {
			printf("1")
		} else {
			printf("2")
		}
	}
}

 package main

 import (
         "fmt"
 )

 func main() {

         t := 0
         fmt.Scanf("%d\n", &t)
         for i := 0; i < t; i++ {
             var a,b int
             fmt.Scanf("%d %d\n", &a,&b)
             if a == b{
                 fmt.Println(0)

             }else if a < b{
                 if (b-a)%2 == 0{
                     fmt.Println(2)
                 }else{
                     fmt.Println(1)
                 }
             }else{
                 if (a-b)%2 == 0{
                     fmt.Println(2)
                 }else{
                     fmt.Println(1)
                 }
             }

        }
 }

package main

import (
	"fmt"
)

func main() {
	var tests int
	fmt.Scanf("%d", &tests)

	for i := 0; i < tests; i++ {
		var a, b int
		fmt.Scanf("%d %d", &a, &b)
		fmt.Println(steps(a, b))
	}
}

func steps(a, b int) int {
	if a < b {
		// increase a by odd number.
		delta := b - a
		if isEven(delta) {
			delta--
		}
		// calculate again.
		return steps(a+delta, b) + 1
	}

	if a > b {
		// decrease a by even number.
		delta := a - b
		if isOdd(delta) {
			delta++
		}
		// calculate again.
		return steps(a-delta, b) + 1
	}

	return 0
}

func isOdd(num int) bool {
	return num%2 != 0
}

func isEven(num int) bool {
	return num%2 == 0
}

package main

import (
	"fmt"
)

func main() {
	n := 0
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		a, b := 0, 0
		fmt.Scan(&a, &b)
		if a < b {
			if (b - a) % 2 == 0 {
				println(2)
			} else {
				println(1)
			}
		} else if b < a {
			if (a - b) % 2 == 0 {
				println(1)
			} else {
				println(2)
			}
		} else {
			println(0)
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	n := 0
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		a, b := 0, 0
		fmt.Scan(&a, &b)
		if a < b {
			if (b - a) % 2 == 0 {
				println(2)
			} else {
				println(1)
			}
		} else if b < a {
			if (a - b) % 2 == 0 {
				println(1)
			} else {
				println(2)
			}
		} else {
			print(0)
		}
	}
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scanf("%d", &t)
	for ; t > 0; t-- {
		var a, b int
		fmt.Scanf("%d %d", &a, &b)
		var diff = b - a
		if diff == 0 {
			fmt.Println(0)
		} else if diff > 0 {
			if diff%2 == 0 {
				fmt.Println(2)
			} else {
				fmt.Println(1)
			}
		} else {
			if diff%2 == 0{
				fmt.Println(1)
			} else{
				fmt.Println(2)
			}
		}
	}
}


This is an easy version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from $$$n$$$ vertices. We remind you that a tree of $$$n$$$ vertices is an undirected connected graph of $$$n$$$ vertices and $$$n-1$$$ edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets $$$\{3, 2, 5\}$$$, $$$\{1, 5, 4\}$$$, $$$\{1, 4\}$$$ are passable, and $$$\{1, 3, 5\}$$$, $$$\{1, 2, 3, 4, 5\}$$$ are not.  Polycarp asks you to answer $$$q$$$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.

The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of vertices. Following $$$n - 1$$$ lines a description of the tree.. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — indices of vertices connected by an edge. Following line contains single integer $$$q$$$ ($$$1 \le q \le 5$$$) — number of queries. The following $$$2 \cdot q$$$ lines contain descriptions of sets. The first line of the description contains an integer $$$k$$$ ($$$1 \le k \le n$$$) — the size of the set. The second line of the description contains $$$k$$$ of distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) — indices of the vertices of the set. It is guaranteed that the sum of $$$k$$$ values for all queries does not exceed $$$2 \cdot 10^5$$$.

Output $$$q$$$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

package main

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

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

func main() {
	defer ww.Flush()
	var n int
	fmt.Fscan(rr, &n)
	edges := make([][]int, n)
	for i:=1;i<n;i++ {
		var u, v int
		fmt.Fscan(rr, &u, &v)
		u, v = u - 1, v - 1
		edges[u] = append(edges[u], v)
		edges[v] = append(edges[v], u)
	}
	var q int
	fmt.Fscan(rr, &q)
	for qq:=0;qq<q;qq++ {
		set := map[int]bool{}
		var m int
		fmt.Fscan(rr, &m)
		for i:=0;i<m;i++ {
			var a int
			fmt.Fscan(rr, &a)
			set[a-1] = true
		}
		ans := "YES"
		var dfs func(i int, last int, has bool) int
		dfs = func(i, last int, has bool) int {
			cnt := 0
			sum := 0
			newhas := has
			if set[i] {
				newhas = true
			}
			maxcur := 1
			for _, v := range edges[i] {
				if v == last {
					continue
				}
				cur := dfs(v, i, newhas)
				maxcur = max(maxcur, cur)
				if cur >= 2 && set[i] {
					ans = "NO"
				}
				if cur > 0 {
					cnt++
				}
				sum += cur
			}
			if sum >= 3 {
				ans = "NO"
			}
			if cnt == 1 {
				return maxcur
			} else if cnt == 2 {
				return 2
			} else if cnt >= 3 {
				ans = "NO"
				return 2
			} else if set[i] {
				return 1
			} else {
				return 0
			}
		}
		dfs(0, -1, false)
		fmt.Fprintln(ww, ans)
	}
}

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

package main

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

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

	var buf bytes.Buffer

	n := readNum(reader)
	edges := make([][]int, n-1)
	for i := 0; i < n-1; i++ {
		edges[i] = readNNums(reader, 2)
	}
	q := readNum(reader)
	queries := make([][]int, q)

	for i := 0; i < q; i++ {
		k := readNum(reader)
		queries[i] = readNNums(reader, k)
	}
	res := solve(n, edges, queries)
	for _, ans := range res {
		if ans {
			buf.WriteString("YES\n")
		} else {
			buf.WriteString("NO\n")
		}
	}

	fmt.Print(buf.String())
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

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 H = 20

func solve(n int, edges [][]int, queries [][]int) []bool {

	g := NewGraph(n, 2*(n-1))

	for _, edge := range edges {
		u, v := edge[0]-1, edge[1]-1
		g.AddEdge(u, v)
		g.AddEdge(v, u)
	}

	D := make([]int, n)

	in := make([]int, n)
	out := make([]int, n)

	P := make([][]int, n)
	for i := 0; i < n; i++ {
		P[i] = make([]int, H)
	}

	var dfs func(p, u int)
	var time int
	dfs = func(p, u int) {
		P[u][0] = p
		for i := 1; i < H; i++ {
			P[u][i] = P[P[u][i-1]][i-1]
		}
		in[u] = time
		time++
		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if p != v {
				D[v] = D[u] + 1
				dfs(u, v)
			}
		}
		out[u] = time
		time++
	}

	dfs(0, 0)

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

	lca := func(u, v int) int {
		if D[u] < D[v] {
			u, v = v, u
		}
		for i := H - 1; i >= 0; i-- {
			if D[u]-(1<<i) >= D[v] {
				u = P[u][i]
			}
		}
		if u == v {
			return u
		}
		for i := H - 1; i >= 0; i-- {
			if P[u][i] != P[v][i] {
				u = P[u][i]
				v = P[v][i]
			}
		}
		return P[u][0]
	}

	arr := make([]int, n)

	check := func(query []int) bool {
		if len(query) <= 2 {
			return true
		}
		m := len(query)

		for i := 0; i < m; i++ {
			query[i]--
		}
		sort.Slice(query, func(i, j int) bool {
			a := query[i]
			b := query[j]
			return D[a] < D[b]
		})

		var it int

		x := query[m-1]

		for i := m - 2; i >= 0; i-- {
			y := query[i]
			if isAncestor(y, x) {
				x = y
			} else {
				arr[it] = y
				it++
			}
		}
		if it == 0 {
			return true
		}
		// last one is x
		u := arr[0]

		for i := 1; i < it; i++ {
			v := arr[i]
			if !isAncestor(v, u) {
				return false
			}
			u = v
		}

		p1 := lca(arr[0], query[m-1])
		p2 := lca(u, x)

		return p1 == p2
	}

	ans := make([]bool, len(queries))

	for i, cur := range queries {
		ans[i] = check(cur)
	}
	return ans
}

type Graph struct {
	node []int
	next []int
	to   []int
	cur  int
}

func NewGraph(n int, e int) *Graph {
	g := new(Graph)
	g.node = make([]int, n)
	g.next = make([]int, e+1)
	g.to = make([]int, e+1)
	g.cur = 0
	return g
}

func (g *Graph) AddEdge(u, v int) {
	g.cur++
	g.next[g.cur] = g.node[u]
	g.node[u] = g.cur
	g.to[g.cur] = v
}

package main

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

func solve0(n int, a [][]int, s []bool) {
	k := get()
	for i := range s {
		s[i] = false
	}
	var start int
	for t := k; t > 0; t-- {
		start = get() - 1
		s[start] = true
	}

	var dfs func(v, p, max int) int
	dfs = func(v, p, max int) int {
		count := 0
		for _, u := range a[v] {
			if u != p {
				switch dfs(u, v, 1) {
				case 1:
					if count == max {
						return 2
					}
					count++
				case 2:
					return 2
				}
			}
		}
		if count > 0 || s[v] {
			return 1
		}
		return 0
	}
	yn(dfs(start, -1, 2) != 2)
}

func solve() {
	n := get()
	a := make([][]int, n)
	for t := n - 1; t > 0; t-- {
		v := get() - 1
		u := get() - 1
		a[v] = append(a[v], u)
		a[u] = append(a[u], v)
	}

	q := get()
	s := make([]bool, n)
	for t := q; t > 0; t-- {
		solve0(n, a, s)
	}
}

const (
	once       = true
	maxBufSize = 10000000
)

var (
	splitFunc = bufio.ScanWords
)

func main() {
	in = bufio.NewScanner(bufio.NewReader(os.Stdin))
	in.Split(splitFunc)
	in.Buffer(make([]byte, maxBufSize), maxBufSize)

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

	if once {
		solve()
		return
	}

	t := get()
	for t > 0 {
		solve()
		t--
	}
}

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

func get() int {
	x, _ := strconv.Atoi(gets())
	return x
}

func get64() int64 {
	x, _ := strconv.ParseInt(gets(), 10, 64)
	return x
}

func getf() float64 {
	x, _ := strconv.ParseFloat(gets(), 64)
	return x
}

func gets() string {
	in.Scan()
	return in.Text()
}

func putc(c rune) {
	out.WriteRune(c)
}

func put(x int) {
	out.WriteString(strconv.Itoa(x))
}

func put64(x int64) {
	out.WriteString(strconv.FormatInt(x, 10))
}

func puts(s string) {
	out.WriteString(s)
}

func yn(y bool) {
	if y {
		yes()
		return
	}
	no()
}

func yes() {
	puts("YES")
	line()
}

func no() {
	puts("NO")
	line()
}

//func putf(x float64) {
//	out.WriteString(strconv.FormatFloat(x))
//}

func line() {
	out.WriteRune('\n')
}

func space() {
	out.WriteRune(' ')
}

package main

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

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

func main() {
	defer ww.Flush()
	var n int
	fmt.Fscan(rr, &n)
	edges := make([][]int, n)
	for i:=1;i<n;i++ {
		var u, v int
		fmt.Fscan(rr, &u, &v)
		u, v = u - 1, v - 1
		edges[u] = append(edges[u], v)
		edges[v] = append(edges[v], u)
	}
	var q int
	fmt.Fscan(rr, &q)
	for qq:=0;qq<q;qq++ {
		set := map[int]bool{}
		var m int
		fmt.Fscan(rr, &m)
		for i:=0;i<m;i++ {
			var a int
			fmt.Fscan(rr, &a)
			set[a-1] = true
		}
		ans := "YES"
		var dfs func(i int, last int, has bool) int
		dfs = func(i, last int, has bool) int {
			cnt := 0
			sum := 0
			newhas := has
			if set[i] {
				newhas = true
			}
			for _, v := range edges[i] {
				if v == last {
					continue
				}
				cur := dfs(v, i, newhas)
				if cur == 2 && set[i] {
					ans = "NO"
				}
				if cur > 0 {
					cnt++
				}
				sum += cur
			}
			if sum >= 3 {
				ans = "NO"
			}
			if cnt == 1 {
				return 1
			} else if cnt == 2 {
				return 2
			} else if cnt >= 3 {
				ans = "NO"
				return 2
			} else if set[i] {
				return 1
			} else {
				return 0
			}
		}
		dfs(0, -1, false)
		fmt.Fprintln(ww, ans)
	}
}

package main

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

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

func main() {
	defer ww.Flush()
	var n int
	fmt.Fscan(rr, &n)
	edges := make([][]int, n)
	for i:=1;i<n;i++ {
		var u, v int
		fmt.Fscan(rr, &u, &v)
		u, v = u - 1, v - 1
		edges[u] = append(edges[u], v)
		edges[v] = append(edges[v], u)
	}
	var q int
	fmt.Fscan(rr, &q)
	for qq:=0;qq<q;qq++ {
		set := map[int]bool{}
		var m int
		fmt.Fscan(rr, &m)
		for i:=0;i<m;i++ {
			var a int
			fmt.Fscan(rr, &a)
			set[a-1] = true
		}
		ans := "YES"
		var dfs func(i int, last int, has bool) int
		dfs = func(i, last int, has bool) int {
			cnt := 0
			sum := 0
			newhas := has
			if set[i] {
				newhas = true
			}
			for _, v := range edges[i] {
				if v == last {
					continue
				}
				cur := dfs(v, i, newhas)
				if cur > 0 {
					cnt++
				}
				sum += cur
			}
			if set[i] {
				sum++
			}
			if (cnt >= 2 && has) || (cnt >= 3) {
				ans = "NO"
			}
			return sum
		}
		dfs(0, -1, false)
		fmt.Fprintln(ww, ans)
	}
}


Omkar is building a house. He wants to decide how to make the floor plan for the last floor.Omkar's floor starts out as $$$n$$$ rows of $$$m$$$ zeros ($$$1 \le n,m \le 100$$$). Every row is divided into intervals such that every $$$0$$$ in the row is in exactly $$$1$$$ interval. For every interval for every row, Omkar can change exactly one of the $$$0$$$s contained in that interval to a $$$1$$$. Omkar defines the quality of a floor as the sum of the squares of the sums of the values in each column, i. e. if the sum of the values in the $$$i$$$-th column is $$$q_i$$$, then the quality of the floor is $$$\sum_{i = 1}^m q_i^2$$$.Help Omkar find the maximum quality that the floor can have.

The first line contains two integers, $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 100$$$), which are the number of rows and number of columns, respectively. You will then receive a description of the intervals in each row. For every row $$$i$$$ from $$$1$$$ to $$$n$$$: The first row contains a single integer $$$k_i$$$ ($$$1 \le k_i \le m$$$), which is the number of intervals on row $$$i$$$. The $$$j$$$-th of the next $$$k_i$$$ lines contains two integers $$$l_{i,j}$$$ and $$$r_{i,j}$$$, which are the left and right bound (both inclusive), respectively, of the $$$j$$$-th interval of the $$$i$$$-th row. It is guaranteed that all intervals other than the first interval will be directly after the interval before it. Formally, $$$l_{i,1} = 1$$$, $$$l_{i,j} \leq r_{i,j}$$$ for all $$$1 \le j \le k_i$$$, $$$r_{i,j-1} + 1 = l_{i,j}$$$ for all $$$2 \le j \le k_i$$$, and $$$r_{i,k_i} = m$$$.

Output one integer, which is the maximum possible quality of an eligible floor plan.

NoteThe given test case corresponds to the following diagram. Cells in the same row and have the same number are a part of the same interval.  The most optimal assignment is:  The sum of the $$$1$$$st column is $$$4$$$, the sum of the $$$2$$$nd column is $$$2$$$, the sum of the $$$3$$$rd and $$$4$$$th columns are $$$0$$$, and the sum of the $$$5$$$th column is $$$4$$$.The quality of this floor plan is $$$4^2 + 2^2 + 0^2 + 0^2 + 4^2 = 36$$$. You can show that there is no floor plan with a higher quality.

package main

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

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

	n, m := readTwoNums(reader)
	segs := make([][][]int, n)

	for i := 0; i < n; i++ {
		x := readNum(reader)
		segs[i] = make([][]int, x)
		for j := 0; j < x; j++ {
			segs[i][j] = readNNums(reader, 2)
		}
	}
	fmt.Println(solve(n, m, segs))
}

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
}

func solve(n, m int, segs [][][]int) int {
	dp := make([][]int, m)
	for i := 0; i < m; i++ {
		dp[i] = make([]int, m)
	}

	left := make([][]int, n)
	right := make([][]int, n)
	for i := 0; i < n; i++ {
		left[i] = make([]int, m)
		right[i] = make([]int, m)
		for j := 0; j < m; j++ {
			left[i][j] = m
			right[i][j] = m
		}
		ss := segs[i]
		for _, s := range ss {
			for j := s[0] - 1; j <= s[1]-1; j++ {
				left[i][j] = s[0] - 1
				right[i][j] = s[1] - 1
			}
		}
	}

	get := func(l, r int) int {
		if l > r {
			return 0
		}
		return dp[l][r]
	}

	for l := m - 1; l >= 0; l-- {
		for r := l; r < m; r++ {
			for x := l; x <= r; x++ {
				var cnt int
				for i := 0; i < n; i++ {
					// x所在的区间处于 范围 [l...r]中间
					if left[i][x] >= l && right[i][x] <= r {
						cnt++
					}
				}
				dp[l][r] = max(dp[l][r], cnt*cnt+get(l, x-1)+get(x+1, r))
			}
		}
	}
	return dp[0][m-1]
}

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


You are given a weighted tree with $$$n$$$ vertices. Recall that a tree is a connected graph without any cycles. A weighted tree is a tree in which each edge has a certain weight. The tree is undirected, it doesn't have a root.Since trees bore you, you decided to challenge yourself and play a game on the given tree.In a move, you can travel from a node to one of its neighbors (another node it has a direct edge with).You start with a variable $$$x$$$ which is initially equal to $$$0$$$. When you pass through edge $$$i$$$, $$$x$$$ changes its value to $$$x ~\mathsf{XOR}~ w_i$$$ (where $$$w_i$$$ is the weight of the $$$i$$$-th edge). Your task is to go from vertex $$$a$$$ to vertex $$$b$$$, but you are allowed to enter node $$$b$$$ if and only if after traveling to it, the value of $$$x$$$ will become $$$0$$$. In other words, you can travel to node $$$b$$$ only by using an edge $$$i$$$ such that $$$x ~\mathsf{XOR}~ w_i = 0$$$. Once you enter node $$$b$$$ the game ends and you win.Additionally, you can teleport at most once at any point in time to any vertex except vertex $$$b$$$. You can teleport from any vertex, even from $$$a$$$.Answer with "YES" if you can reach vertex $$$b$$$ from $$$a$$$, and "NO" otherwise.Note that $$$\mathsf{XOR}$$$ represents the bitwise XOR operation.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$2 \leq n \leq 10^5$$$), ($$$1 \leq a, b \leq n; a \ne b$$$) — the number of vertices, and the starting and desired ending node respectively. Each of the next $$$n-1$$$ lines denotes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$  — the labels of vertices it connects ($$$1 \leq u_i, v_i \leq n; u_i \ne v_i; 1 \leq w_i \leq 10^9$$$) and the weight of the respective edge. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output "YES" if you can reach vertex $$$b$$$, and "NO" otherwise.

NoteFor the first test case, we can travel from node $$$1$$$ to node $$$3$$$, $$$x$$$ changing from $$$0$$$ to $$$1$$$, then we travel from node $$$3$$$ to node $$$2$$$, $$$x$$$ becoming equal to $$$3$$$. Now, we can teleport to node $$$3$$$ and travel from node $$$3$$$ to node $$$4$$$, reaching node $$$b$$$, since $$$x$$$ became equal to $$$0$$$ in the end, so we should answer "YES".For the second test case, we have no moves, since we can't teleport to node $$$b$$$ and the only move we have is to travel to node $$$2$$$ which is impossible since $$$x$$$ wouldn't be equal to $$$0$$$ when reaching it, so we should answer "NO".

package main

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

func dfs(adj [][][]int, vis []bool, xor []int, i, x int, b int) {
	vis[i] = true
	xor[i] = x
	if i == b {
		return
	}

	for _, v := range adj[i] {
		if ! vis[v[0]] {
			dfs(adj, vis, xor, v[0], x ^ v[1], b)
		}
	}
}

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, a, b int
		fmt.Fscan(r, &n, &a, &b)
		a--
		b--

		adj := make([][][]int, n)
		for i := 0; i < n-1; i++ {
			var u, v, w int
			fmt.Fscan(r, &u, &v, &w)
			u--
			v--
			adj[u] = append(adj[u], []int{v, w})
			adj[v] = append(adj[v], []int{u, w})
		}

		// fmt.Fprintln(w, "%%% n a b", n, a, b)
		// fmt.Fprintln(w, "%%% vis1", vis1)
		// fmt.Fprintln(w, "%%% adj", adj)
		xor1 := make([]int, n)
		for i := range xor1 {
			xor1[i] = -1
		}
		vis1 := make([]bool, n)
		dfs(adj, vis1, xor1, a, 0, b)

		xor2 := make([]int, n)
		vis2 := make([]bool, n)
		dfs(adj, vis2, xor2, b, 0, -1)

		m := make(map[int]bool)
		for i, v := range xor2 {
			if i != b {
				m[v] = true
			}
		}

		res := "NO"
		for i, v := range xor1 {
			if (i != b && m[v]) || (i == b && v == 0) {
				res = "YES"
				break
			}
		}

		fmt.Fprintln(w, res)
	}

}

package main
import (
  "bufio"
  "fmt"
  //"sort"
  "os"
)
/*
题意：一棵树中，x起始值为0，每走过一条值为w的边，值变为x^w。最多允许在两点之间瞬移一次（且不允许瞬移到b），
进入点b的条件是x为0。问：从某个节点a出发，能否到达点b？

用u->v:val表示：从u出发到达某点v时路径上的异或和为val。设a->c(不经过点b):val1, b->d:val2，
也就是说存在这样的点c和d，使得val1==val2，若c与d相同，表示不使用瞬移，
那么解法就是分别求a,b出发的异或和，检查是否存在相同值。
若不采用“分别求异或和再检查交集”的做法，可以在求b出发的异或和时边在f(a)的结果中检测，及时返回。
*/
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 main(){
  I,O:=bufio.NewReader(os.Stdin),bufio.NewWriter(os.Stdout);defer O.Flush()

  var t,n,a,b,u,v,w int
  fmt.Fscan(I,&t)
  for i:=0;i<t;i++{
    fmt.Fscan(I,&n,&a,&b);g:=make([][][]int,n+1)
    for j:=0;j<n-1;j++{
      fmt.Fscan(I,&u,&v,&w)
      g[u]=append(g[u],[]int{v,w});g[v]=append(g[v],[]int{u,w}) //带权图
    }

    m:=map[int]bool{};ok:=false
    var f1 func(int,int,int)
    f1=func(u,fa,x int){
      if u==b{if x==0{ok=true};return}
      m[x]=true
      for _,V:=range g[u]{v,w:=V[0],V[1];if v!=fa{f1(v,u,x^w)}}
    }
    f1(a,0,0)
    if ok{fmt.Fprintln(O,"YES");continue}

    var f2 func(int,int,int)
    f2=func(u,fa,x int){
      if u!=b && m[x]{ok=true;return}
      for _,V:=range g[u]{v,w:=V[0],V[1];if v!=fa{f2(v,u,x^w)}}
    }
    f2(b,0,0);z:="NO"
    if ok{z="YES"}
    fmt.Fprintln(O,z)
  }
}

package main
import (
  "bufio"
  "fmt"
  //"sort"
  "os"
)
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 main(){
  I,O:=bufio.NewReader(os.Stdin),bufio.NewWriter(os.Stdout);defer O.Flush()

  var t,n,a,b,u,v,w int
  fmt.Fscan(I,&t)
  for i:=0;i<t;i++{
    fmt.Fscan(I,&n,&a,&b);g:=make([][][]int,n+1)
    for j:=0;j<n-1;j++{
      fmt.Fscan(I,&u,&v,&w)
      g[u]=append(g[u],[]int{v,w});g[v]=append(g[v],[]int{u,w}) //带权图
    }
    var f func(int)map[int]bool
    f=func(start int)(map[int]bool){
      z:=map[int]bool{}
      var dfs func(int,int,int)
      dfs=func(u,fa,x int){
        if u!=b{z[x]=true}
        for _,V:=range g[u]{v,w:=V[0],V[1];if v!=fa && v!=b{dfs(v,u,x^w)}}
      }
      dfs(start,0,0)
      return z
    }
    // a->c路径值为x，b->d路径（长度最短为2）值为y，c和d可以相同（此时不使用瞬移）
    // 即求是否存在x==y
    z:="NO";v1,v2:=f(a),f(b)
    if len(v1)>len(v2){v1,v2=v2,v1}
    for k:=range v1{
      if ok:=v2[k];ok{z="YES";break}
    }
    fmt.Fprintln(O,z)
  }
}

package main

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

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

// source: https://codeforces.com/contest/1760/problem/G
func solve() {
	n, a, b := _readInt(), _readInt(), _readInt()
	graph := make([]map[int]int, n+1)
	for i := 0; i < n-1; i++ {
		u, v, w := _readInt(), _readInt(), _readInt()
		if graph[u] == nil {
			graph[u] = make(map[int]int)
		}
		if graph[v] == nil {
			graph[v] = make(map[int]int)
		}
		graph[u][v] = w
		graph[v][u] = w
	}

	vals := make(map[int]bool)
	var dfs1 func(v, prev, x int)
	dfs1 = func(v, prev, x int) {
		if v == b {
			return
		}
		vals[x] = true
		for u, w := range graph[v] {
			if u == prev {
				continue
			}
			dfs1(u, v, w^x)
		}
	}
	dfs1(a, -1, 0)

	var dfs2 func(v, prev, x int) bool
	dfs2 = func(v, prev, x int) bool {
		if v != b && vals[x] {
			return true
		}
		for u, w := range graph[v] {
			if u == prev {
				continue
			}
			if dfs2(u, v, w^x) {
				return true
			}
		}
		return false
	}

	if dfs2(b, -1, 0) {
		_print("YES")
	} else {
		_print("NO")
	}
}

func main() {
	defer out.Flush()
	var t int
	for fmt.Fscanln(in, &t); t > 0; t-- {
		solve()
	}
}

// ====
func _readInt() int {
	var x int
	fmt.Fscan(in, &x)
	return x
}
func _readStr() string {
	var x string
	fmt.Fscan(in, &x)
	return x
}
func _readArr(x ...int) (int, []int) {
	var n int
	if len(x) == 0 {
		fmt.Fscan(in, &n)
	} else {
		n = x[0]
	}
	var v = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &v[i])
	}
	return n, v
}
func _print(x ...any) {
	fmt.Fprintln(out, x...)
}
func _max(x ...int) int {
	mi := 0
	for i := 1; i < len(x); i++ {
		if x[i] > x[mi] {
			mi = i
		}
	}
	return x[mi]
}
func _min(x ...int) int {
	mi := 0
	for i := 1; i < len(x); i++ {
		if x[i] < x[mi] {
			mi = i
		}
	}
	return x[mi]
}
func _sum(x ...int) int {
	res := 0
	for _, i := range x {
		res += i
	}
	return res
}
func _abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func _sortStr(x string) string {
	r := []rune(x)
	sort.Slice(r, func(i, j int) bool {
		return r[i] < r[j]
	})
	return string(r)
}
func _reverseInts(x []int) {
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
}
func _reverseStr(s string) string {
	x := []rune(s)
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
	return string(x)
}
func _makeMatrix(n, m int) [][]int {
	x := make([][]int, n)
	for i := range x {
		x[i] = make([]int, m)
	}
	return x
}

package main

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

const cf = true

type edge struct {
	to int
	w  int
}

func solve() {
	var n, a, b int
	fmt.Fscan(in, &n, &a, &b)
	graph := map[int][]edge{}
	for i := 1; i < n; i++ {
		var u, v, w int
		fmt.Fscan(in, &u, &v, &w)
		graph[u] = append(graph[u], edge{to: v, w: w})
		graph[v] = append(graph[v], edge{to: u, w: w})
	}

	vals := map[int]struct{}{}

	visitedB := map[int]struct{}{}

	dfsB := func(cur int, x int) { panic(1) }
	dfsB = func(cur int, x int) {
		visitedB[cur] = struct{}{}
		if cur != b {
			vals[x] = struct{}{}
		}
		for _, neighbour := range graph[cur] {
			if _, ok := visitedB[neighbour.to]; !ok {
				dfsB(neighbour.to, x^neighbour.w)
			}
		}
	}
	dfsB(b, 0)

	visitedA := map[int]struct{}{}

	dfsA := func(cur, x int) bool { panic(1) }
	dfsA = func(cur, x int) bool {
		if cur == b {
			return false
		}
		visitedA[cur] = struct{}{}
		if _, ok := vals[x]; ok {
			return true
		}
		for _, neighbour := range graph[cur] {
			if _, ok := visitedA[neighbour.to]; !ok {
				if dfsA(neighbour.to, x^neighbour.w) {
					return true
				}
			}
		}
		return false
	}
	if dfsA(a, 0) {
		fmt.Fprintln(out, "YES")
	} else {
		fmt.Fprintln(out, "NO")
	}
}

func main() {
	defer out.Flush()
	t := 1
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		solve()
	}
}

func LCM(a, b int) int {
	return a * b / GCD(a, b)
}

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

	return a
}

type SqrtInt interface {
	SignedSqrt | UnsignedSqrt
}

type SignedSqrt interface {
	~int | ~int32 | ~int64
}

type UnsignedSqrt interface {
	~uint | ~uint32 | ~uint64 | ~uintptr
}

func sqrt[T SqrtInt](x T) T {
	l, r := T(0), T(2000000123)
	for l < r {
		mid := (l + r) / 2
		if mid*mid > x {
			r = mid
		} else {
			l = mid + 1
		}
	}
	return l - 1
}

func ConvertInt(val string, base, toBase int) (string, error) {
	i, err := strconv.ParseInt(val, base, 64)
	if err != nil {
		return "", err
	}
	return strconv.FormatInt(i, toBase), nil
}

const MaxUint = ^uint(0)
const MinUint = 0
const MaxInt = int(MaxUint >> 1)
const MinInt = -MaxInt - 1

func reverseStr(s string) string {
	r := []byte(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type Ordered interface {
	Integer | Float | ~string
}

func abs[T Signed](x T) T {
	if x < 0 {
		return -x
	}
	return x
}

func min[T Ordered](x, y T) T {
	if x < y {
		return x
	}
	return y
}

func max[T Ordered](x, y T) T {
	if x > y {
		return x
	}
	return y
}

var (
	in  = getReader()
	out = getWriter()
)

func getReader() *bufio.Reader {
	if cf {
		return bufio.NewReader(os.Stdin)
	} else {
		in, _ := os.Open("input.txt")
		return bufio.NewReader(in)
	}
}

func getWriter() *bufio.Writer {
	if cf {
		return bufio.NewWriter(os.Stdout)
	} else {
		out, _ := os.Create("output.txt")
		return bufio.NewWriter(out)
	}
}

package main

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

// https://space.bilibili.com/206214
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	solve := func(curCase int) {
		var n,a,b int
		Fscan(in, &n,&a,&b)
		a--
		b--
		type nb struct{ to, wt int }
		g := make([][]nb, n)
		for i := 0; i < n-1; i++ {
			v, w, wt := 0, 0, 0
			Fscan(in, &v, &w, &wt)
			v--
			w--
			g[v] = append(g[v], nb{w, wt})
			g[w] = append(g[w], nb{v, wt})
		}

		m := map[int]bool{}
		ok := false
		var d0 func(v, fa ,xor int)
		d0 = func(v, fa ,xor int) {
			m[xor] = true
			for _, e := range g[v] {
				w := e.to
				if w != fa  {
					if w == b {
						if xor ^e.wt == 0 {
							ok = true
						}
						continue
					}
					d0(w, v,xor ^ e.wt)
				}
			}
		}
		d0(a, -1, 0)
		if ok {
			Fprintln(out, "YES")
			return
		}

		var d1 func(v, fa ,xor int)
		d1 = func(v, fa ,xor int) {
			if fa != -1 && m[xor] {
				ok = true
			}
			for _, e := range g[v] {
				w := e.to
				if w != fa  {
					d1(w, v,xor ^ e.wt)
				}
			}
		}
		d1(b, -1, 0)

		if ok{
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}

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

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

}

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

package main

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

func dfs(adj [][][]int, vis []bool, xor []int, i, x int) {
	vis[i] = true
	xor[i] = x

	for _, v := range adj[i] {
		if ! vis[v[0]] {
			dfs(adj, vis, xor, v[0], x ^ v[1])
		}
	}
}

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, a, b int
		fmt.Fscan(r, &n, &a, &b)
		a--
		b--

		adj := make([][][]int, n)
		xor1 := make([]int, n)
		xor2 := make([]int, n)
		vis1 := make([]bool, n)
		vis2 := make([]bool, n)

		for i := 0; i < n-1; i++ {
			var u, v, w int
			fmt.Fscan(r, &u, &v, &w)
			u--
			v--
			adj[u] = append(adj[u], []int{v, w})
			adj[v] = append(adj[v], []int{u, w})
		}

		// fmt.Fprintln(w, "%%% n a b", n, a, b)
		// fmt.Fprintln(w, "%%% vis1", vis1)
		// fmt.Fprintln(w, "%%% adj", adj)
		dfs(adj, vis1, xor1, a, 0)
		dfs(adj, vis2, xor2, b, 0)

		m := make(map[int]bool)
		for i, v := range xor2 {
			if i != b {
				m[v] = true
			}
		}

		res := "NO"
		for i, v := range xor1 {
			if (i != b && m[v]) || (i == b && v == 0) {
				res = "YES"
				break
			}
		}

		fmt.Fprintln(w, res)
	}

}

package main

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

type deque[T any] struct {
	q []T
}

func (q *deque[T]) emplace(n T) {
	q.q = append(q.q, n)
}

func (q deque[T]) empty() bool {
	return len(q.q) == 0
}

func (q deque[T]) back() T {
	if q.empty() {
		panic("back() performed on empty deque")
	}
	return q.q[len(q.q)-1]
}

func (q *deque[T]) popback() T {
	if q.empty() {
		panic("popback() performed on empty deque")
	}
	res := q.back()
	q.q = q.q[:len(q.q)-1]
	return res
}

func (q deque[T]) front() T {
	if q.empty() {
		panic("front() performed on empty deque")
	}
	return q.q[0]
}

func (q *deque[T]) popfront() T {
	if q.empty() {
		panic("popfront() performed on empty deque")
	}
	res := q.front()
	q.q = q.q[1:]
	return res
}

func getdeque[T any](capacity int) deque[T] {
	return deque[T]{ make([]T, 0, capacity) }
}

func bfs(adj [][][]int, vis []bool, xor []int, i, x int) {
	q := getdeque[int](1e6)
	vis[i] = true
	q.emplace(i)

	for ! q.empty() {
		j := q.popfront()
		for _, v := range adj[j] {
			if ! vis[v[0]] {
				vis[v[0]] = true
				xor[v[0]] = x ^ v[1]
				q.emplace(v[0])
			}
		}
	}
}

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, a, b int
		fmt.Fscan(r, &n, &a, &b)
		a--
		b--

		adj := make([][][]int, n)
		xor1 := make([]int, n)
		xor2 := make([]int, n)
		vis1 := make([]bool, n)
		vis2 := make([]bool, n)

		for i := 0; i < n-1; i++ {
			var u, v, w int
			fmt.Fscan(r, &u, &v, &w)
			u--
			v--
			adj[u] = append(adj[u], []int{v, w})
			adj[v] = append(adj[v], []int{u, w})
		}

		// fmt.Fprintln(w, "%%% n a b", n, a, b)
		// fmt.Fprintln(w, "%%% vis1", vis1)
		// fmt.Fprintln(w, "%%% adj", adj)
		bfs(adj, vis1, xor1, a, 0)
		bfs(adj, vis2, xor2, b, 0)

		m := make(map[int]bool)
		for i, v := range xor2 {
			if i != b {
				m[v] = true
			}
		}

		res := "NO"
		for i, v := range xor1 {
			if (i != b && m[v]) || (i == b && v == 0) {
				res = "YES"
				break
			}
		}

		fmt.Fprintln(w, res)
	}

}

package main
import (
  "bufio"
  "fmt"
  //"sort"
  "os"
)
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 main(){
  I,O:=bufio.NewReader(os.Stdin),bufio.NewWriter(os.Stdout);defer O.Flush()

  var t,n,a,b int
  fmt.Fscan(I,&t)
  for i:=0;i<t;i++{
    fmt.Fscan(I,&n,&a,&b);g:=make([][][]int,n+1)
    for j:=0;j<n-1;j++{
      var u,v,w int
      fmt.Fscan(I,&u,&v,&w)
      g[u]=append(g[u],[]int{v,w});g[v]=append(g[v],[]int{u,w}) //带权图
    }
    var f func(int)map[int]bool
    f=func(start int)(map[int]bool){
      z:=map[int]bool{}
      var dfs func(int,int,int)
      dfs=func(u,fa,x int){
        if u!=b{z[x]=true}
        for _,V:=range g[u]{v,w:=V[0],V[1];if v!=fa{dfs(v,u,x^w)}}
      }
      dfs(start,0,0)
      return z
    }
    // a->c路径值为x，b->d路径（长度最短为2）值为y，c和d可以相同（此时不使用瞬移）
    // 即求是否存在x==y
    z:="NO";v1,v2:=f(a),f(b)
    if len(v1)>len(v2){v1,v2=v2,v1}
    for k:=range v1{
      if ok:=v2[k];ok{z="YES";break}
    }
    fmt.Fprintln(O,z)
  }
}


The only difference between easy and hard versions is constraints.You are given $$$n$$$ segments on the coordinate axis $$$OX$$$. Segments can intersect, lie inside each other and even coincide. The $$$i$$$-th segment is $$$[l_i; r_i]$$$ ($$$l_i \le r_i$$$) and it covers all integer points $$$j$$$ such that $$$l_i \le j \le r_i$$$.The integer point is called bad if it is covered by strictly more than $$$k$$$ segments.Your task is to remove the minimum number of segments so that there are no bad points at all.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 200$$$) — the number of segments and the maximum number of segments by which each integer point can be covered. The next $$$n$$$ lines contain segments. The $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 200$$$) — the endpoints of the $$$i$$$-th segment.

In the first line print one integer $$$m$$$ ($$$0 \le m \le n$$$) — the minimum number of segments you need to remove so that there are no bad points. In the second line print $$$m$$$ distinct integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le n$$$) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.

package main

import (
	"bufio"
	"container/heap"
	"os"
	"runtime"
	"sort"
	"strconv"
)

/* solution */

type sect struct {
	l int
	r int
}

type event struct {
	t     int
	time  int
	index int
}

type eventArr []event

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

type heapItem struct {
	index int
	r     int
}

type heapStorage struct {
	storage []heapItem
	pos     []int
}

func (h heapStorage) Len() int           { return len(h.storage) }
func (h heapStorage) Less(i, j int) bool { return h.storage[i].r > h.storage[j].r }
func (h heapStorage) Swap(i, j int) {
	h.storage[i], h.storage[j] = h.storage[j], h.storage[i]
	h.pos[h.storage[i].index] = i
	h.pos[h.storage[j].index] = j
}

func (h *heapStorage) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	item := x.(heapItem)
	h.storage = append(h.storage, item)
	h.pos[item.index] = len(h.storage) - 1
}

func (h *heapStorage) Pop() interface{} {
	old := *h
	n := len(old.storage)
	x := old.storage[n-1]
	h.pos[x.index] = -1
	h.storage = old.storage[0 : n-1]
	return x
}

func solve() {

	n, k := readInt(), readInt()
	a := make([]sect, n)
	e := make(eventArr, 2*n)
	for i := 0; i < n; i++ {
		l, r := readInt(), readInt()
		a[i] = sect{l: l, r: r}
		e[2*i] = event{t: 1, time: l, index: i}
		e[2*i+1] = event{t: -1, time: r + 1, index: i}
	}

	sort.Sort(e)

	h := &heapStorage{storage: make([]heapItem, 0), pos: make([]int, n)}
	ans := make([]int, 0)

	for i := 0; i < 2*n; i++ {
		if e[i].t == 1 {
			heap.Push(h, heapItem{index: e[i].index, r: a[e[i].index].r})
		} else {
			idx := h.pos[e[i].index]
			if idx > -1 {
				h.storage[idx].r = 1000000
				heap.Fix(h, idx)
				heap.Pop(h)
			}
		}
		if i < 2*n-1 && e[i+1].time == e[i].time {
			continue
		}
		for len(h.storage) > k {
			x := heap.Pop(h).(heapItem)
			ans = append(ans, x.index+1)
		}
	}

	printInt(len(ans))
	ln()
	for i := 0; i < len(ans); i++ {
		printInt(ans[i])
	}

}

/* stubs */

func main() {

	var f *os.File
	if runtime.GOROOT() == "C:\\Soft\\Go" {
		f, _ = os.Open("input.txt")
		defer f.Close()
	} else {
		f = os.Stdin
	}

	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	reader = bufio.NewScanner(f)

	const maxCapacity = 1024 * 1024
	buf := make([]byte, maxCapacity)
	reader.Buffer(buf, maxCapacity)

	reader.Split(bufio.ScanWords)

	solve()

}

var reader *bufio.Scanner
var writer *bufio.Writer

func read() string {
	reader.Scan()
	return reader.Text()
}

func readInt() int {
	reader.Scan()
	ret, _ := strconv.Atoi(reader.Text())
	return ret
}

func print(s string) {
	writer.WriteString(s)
	writer.WriteString(" ")
}

func ln() {
	writer.WriteString("\n")
}

func printInt(i int) {
	print(strconv.Itoa(i))
}

func printInt64(i int64) {
	print(strconv.FormatInt(i, 10))
}

func readInt64() int64 {
	reader.Scan()
	ret, _ := strconv.ParseInt(reader.Text(), 10, 64)
	return ret
}

package main

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

type Pair struct {
	value int
	idx int
}

type PairSorter [] Pair

func (a PairSorter) Less(i, j int) bool {return a[i].value < a[j].value}

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

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

const N = 222
var n, k int
var seg[N] PairSorter

func main()  {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	fmt.Fscanf(reader, "%d %d\n", &n, &k)
	for i := 1; i <= n; i++ {
		var u, v int
		fmt.Fscanf(reader, "%d %d\n", &u, &v)
		if seg[u] == nil {
			seg[u] = make([]Pair, 0)
		}
		seg[u] = append(seg[u], Pair{v, i})
	}

	var cur = make(PairSorter, 0)
	var clr = make([]int, 0)

	for i := 1; i < N; i++ {
		for _, value := range seg[i] {
			cur = append(cur, value)
		}
		sort.Sort(cur)

		var wt = 0
		var newSt = make(PairSorter, 0)

		for _, value := range cur {
			if value.value >= i {
				wt++
				if wt <= k {
					newSt = append(newSt, value)
				} else {
					clr = append(clr, value.idx)
				}
			}
		}

		cur = newSt
	}

	fmt.Fprintf(writer, "%d\n", len(clr))
	for _, value := range clr {
		fmt.Fprintf(writer, "%d ", value)
	}
}