You are a coach at your local university. There are $$$n$$$ students under your supervision, the programming skill of the $$$i$$$-th student is $$$a_i$$$.You have to form $$$k$$$ teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than $$$k$$$ (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than $$$5$$$. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter).It is possible that some students not be included in any team at all.Your task is to report the maximum possible total number of students in no more than $$$k$$$ (and at least one) non-empty balanced teams.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is a programming skill of the $$$i$$$-th student.

Print one integer — the maximum possible total number of students in no more than $$$k$$$ (and at least one) non-empty balanced teams.

package main

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

type SA []int

func (s SA) Len() int {
	return len(s)
}

func (s SA) Swap(a, b int) {
	tmp := s[a]
	s[a] = s[b]
	s[b] = tmp
}
func (s SA) Less(i, j int) bool {
	if s[i] < s[j] {
		return true
	}
	return false
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n, k int
	fmt.Fscanf(buf, "%d %d\n", &n, &k)
	mat := make(SA, n)

	for i := 0; i < n; i++ {

		fmt.Fscanf(buf, "%d", &mat[i])
	}
	fmt.Fscanf(buf, "\n")
	//for i:=1;i <=k;i++{
	//	dp[i]=1
	//}
	sort.Sort(mat)
	ans := 1

	var f int
	var dp [5010][5010]int
	dp[0][1] = 1
	dp[10][10]=0
	for i := 1; i < n; i++ {
		for f <= i && mat[i]-mat[f] > 5 {
			f++
		}
		if f == 0 {
			dp[i][1] = i+1
	//		fmt.Printf("%v\n", dp[i])
			continue
		}
		for j := k - 1; j >= 0; j-- {

			if j > 0 && dp[f-1][j] == 0 {
				continue
			}
			if dp[i-1][j+1] < dp[f-1][j]+i-f+1 {
				dp[i][j+1] = dp[f-1][j] + i - f + 1
			} else {
				dp[i][j+1] = dp[i-1][j+1]
			}
		}

	//	fmt.Printf("%v\n", dp[i])
	}
	for i := 1; i <= k; i++ {
		if dp[n-1][i] > ans {
			ans = dp[n-1][i]
		}
	}
	fmt.Printf("%d\n", ans)
}

/**
0 0
0 1
3
UDD
 */

package main

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

func Sol1133E(reader io.Reader, writer io.Writer) {
	max := func(a, b int) int {
		if a >= b {
			return a
		}
		return b
	}

	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	const maxTeamDelta = 5

	var n, k int
	Fscan(in, &n, &k)
	arr := make([]int, n+1)
	for i := 1; i <= n; i++ {
		Fscan(in, &arr[i])
	}
	sort.Ints(arr)

	deltaPos := make([][maxTeamDelta + 1]int, n+1)
	for j := 0; j <= maxTeamDelta; j++ {
		deltaPos[1][j] = 1
	}
	for i := 2; i <= n; i++ {
		for j := 0; j <= maxTeamDelta; j++ {
			deltaPos[i][j] = i
		}
		if delta := arr[i] - arr[i-1]; delta <= maxTeamDelta {
			copy(deltaPos[i][delta:], deltaPos[i-1][:maxTeamDelta+1-delta])
		}
	}

	var dp [2][5001]int
	for j := 1; j <= n; j++ {
		dp[0][j] = max(dp[0][j-1], j-deltaPos[j][maxTeamDelta]+1)
	}
	row := 0
	for i := 2; i <= k; i++ {
		row ^= 1
		for j := i; j <= n; j++ {
			posL := deltaPos[j][maxTeamDelta]
			// max(not count student j, count student j)
			dp[row][j] = max(dp[row][j-1], dp[row^1][posL-1]+j-posL+1)
		}
	}
	Fprintln(out, max(dp[row][n], dp[row^1][n]))
}

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

package main

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

func Sol1133E(reader io.Reader, writer io.Writer) {
	max := func(a, b int) int {
		if a >= b {
			return a
		}
		return b
	}

	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	const maxTeamDelta = 5

	var n, k int
	Fscan(in, &n, &k)
	arr := make([]int, n+1)
	for i := 1; i <= n; i++ {
		Fscan(in, &arr[i])
	}
	sort.Ints(arr)

	deltaPos := make([][maxTeamDelta + 1]int, n+1)
	for j := 0; j <= maxTeamDelta; j++ {
		deltaPos[1][j] = 1
	}
	for i := 2; i <= n; i++ {
		for j := 0; j <= maxTeamDelta; j++ {
			deltaPos[i][j] = i
		}
		if delta := arr[i] - arr[i-1]; delta <= maxTeamDelta {
			copy(deltaPos[i][delta:], deltaPos[i-1][:maxTeamDelta+1-delta])
		}
	}

	var dp [2][5001]int
	for j := 1; j <= n; j++ {
		dp[0][j] = max(dp[0][j-1], j-deltaPos[j][maxTeamDelta]+1)
	}
	row := 0
	for i := 2; i <= k; i++ {
		row ^= 1
		for j := i; j <= n; j++ {
			posL := deltaPos[j][maxTeamDelta]
			// max(not count student j, count student j)
			dp[row][j] = max(dp[row][j-1], dp[row^1][posL-1]+j-posL+1)
		}
	}
	Fprintln(out, dp[row][n])
}

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


Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.

package main

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

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

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

	n := nextInt()
	_ = n

	s := next()

	i, count := 0, 0

	for i<len(s) && s[i]=='.' {
		i++
	}

	if i==len(s) {
		println(len(s))
		return
	}

	lastPush := i
	i++

	if s[lastPush]=='R' {
		count += lastPush
	}

	for i<len(s) {
		if s[i] != '.' {
			if s[i] == 'R' {
				count += i - lastPush - 1
			} else {
				if (i-lastPush)%2 == 0 {
					count++
				}
			}
			lastPush = i
		}
		i++
	}

	if s[lastPush]=='L' {
		count += len(s) - lastPush - 1
	}

	println(count)
}

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

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	return n
}

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

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

package main

import "fmt"

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

package main

import "fmt"

func main() {
    var n int					// variabel n dengan jenis int
    var s string				// variabel s dengan jenis string
    fmt.Scan(&n)				// mengambil input
    fmt.Scan(&s)				// mengambil input
    a := make([]int,n)			// membuat variabel a yang diisi slice of int ukuran n
    for i := 0; i < n; i++ {   // looping
        if s[i] == 'L' {		// jika s[i] sama dengan 'L'
            a[i] = 1			// a[i] sama dengan 1
            for j := i-1; (j >= 0) && (s[j] == '.'); j-- { // looping ke 2
                if a[j] == (i-j) {		// jika a[j] sama dengan (i-j)
                    a[j] = 0			//  a[j] sama dengan 0
                    break				// keluar dari fungsi
                }
                a[j] = i-j			//   a[j] sama dengan i-j
            }
        } else if s[i] == 'R' {		// lainnya jika s[i] sama dengan 'R'
            a[i] = 1				//   a[i] sama dengan 1
            for j := i+1; (j < n) && (s[j] == '.'); j++ { // looping ke 3
                a[j] = j-i				// a[j] sama dengan j-i
            }
        }
    }
    ans := 0					// membuat variabel ans dengan isi 0
    for i := 0; i < n; i++ {		// looping ke 4
        if a[i] == 0 { ans++ }		// jika a[i] sama dengan 0, ans ditambah terus
    }
    fmt.Println(ans)			// cetak hasil ans
}

/*********************************************************************************
*     File Name           :     B.go
*     Created By          :     YIMMON, yimmon.zhuang@gmail.com
*     Creation Date       :     [2014-03-29 22:34]
*     Last Modified       :     [2014-03-29 22:52]
*     Description         :
**********************************************************************************/

package main

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

func Solve(str []byte) int {
    ans := 0
    var i, j int
    for i = 0; i < len(str); i++ {
        if str[i] != '.' {
            break
        }
    }
    if i >= len(str) {
        ans = len(str)
    } else if str[i] == 'L' {
        if i+1 < len(str) {
            ans = Solve(str[i+1:])
        }
    } else {
        ans = i
        for j = i; j < len(str); j++ {
            if str[j] == 'L' {
                break
            }
        }
        if j < len(str) && (j-i+1)&1 == 1 {
            ans++
        }
        if j+1 < len(str) {
            ans += Solve(str[j+1:])
        }
    }
    return ans
}

func main() {
    scanner.Split(bufio.ScanWords)

    scanner.NextInt()
    str := scanner.Next()
    fmt.Println(Solve([]byte(str)))
}

type Scanner struct {
    *bufio.Scanner
}

var scanner = Scanner{bufio.NewScanner(os.Stdin)}

func (self *Scanner) Next() string {
    if !self.Scan() {
        panic(self.Err())
    }
    return self.Text()
}

func (self *Scanner) NextInt() int {
    x, err := strconv.Atoi(self.Next())
    if err != nil {
        panic(err)
    }
    return x
}

// 405B-mic
package main

import (
    "fmt"
)

func main() {
    var n, k int
    sum := 0
    fall := false
    k = -1

    var s string
    fmt.Scan(&n, &s)

    for i := 0; i < n; i++ {
        switch s[i] {
        case 'R':
            if !fall {
                sum += i - k - 1
            }
            fall = true
            k = i
        case 'L':
            if fall {
                fall = false
                if (i-k)%2 == 0 {
                    sum += 1
                }
            }
            k = i
        }
    }
    if !fall {
        sum += n - k - 1
    }
    fmt.Println(sum)
}

package main

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

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

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

	n := nextInt()
	_ = n

	s := next()

	i, count := 0, 0

	for i<len(s) && s[i]=='.' {
		i++
	}

	if i==len(s) {
		println(0)
		return
	}

	lastPush := i
	i++

	if s[lastPush]=='R' {
		count += lastPush
	}

	for i<len(s) {
		if s[i] != '.' {
			if s[i] == 'R' {
				count += i - lastPush - 1
			} else {
				if (i-lastPush)%2 == 0 {
					count++
				}
			}
			lastPush = i
		}
		i++
	}

	if s[lastPush]=='L' {
		count += len(s) - lastPush - 1
	}

	println(count)
}

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

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	return n
}

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

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}


You are the gym teacher in the school.There are $$$n$$$ students in the row. And there are two rivalling students among them. The first one is in position $$$a$$$, the second in position $$$b$$$. Positions are numbered from $$$1$$$ to $$$n$$$ from left to right.Since they are rivals, you want to maximize the distance between them. If students are in positions $$$p$$$ and $$$s$$$ respectively, then distance between them is $$$|p - s|$$$. You can do the following operation at most $$$x$$$ times: choose two adjacent (neighbouring) students and swap them.Calculate the maximum distance between two rivalling students after at most $$$x$$$ swaps.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of each test case contains four integers $$$n$$$, $$$x$$$, $$$a$$$ and $$$b$$$ ($$$2 \le n \le 100$$$, $$$0 \le x \le 100$$$, $$$1 \le a, b \le n$$$, $$$a \neq b$$$) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.

NoteIn the first test case you can swap students in positions $$$3$$$ and $$$4$$$. And then the distance between the rivals is equal to $$$|4 - 2| = 2$$$.In the second test case you don't have to swap students. In the third test case you can't swap students.

package main

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

/* solution */

func solve() {
	t := readInt()
	for i := 0; i < t; i++ {
		solveOne()
	}
}

func solveOne() {
	n, x, a, b := readInt(), readInt(), readInt(), readInt()
	ans := b - a
	if ans < 0 {
		ans = -ans
	}
	ans += x
	if ans > n-1 {
		ans = n - 1
	}
	printInt(ans)
}

/* 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("\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"
)

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

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// A. Two Rival Students
/*
You are the gym teacher in the school.

There are 𝑛 students in the row. And there are two rivalling students among them. The first one is in position 𝑎, the second in position 𝑏. Positions are numbered from 1 to 𝑛 from left to right.

Since they are rivals, you want to maximize the distance between them. If students are in positions 𝑝 and 𝑠 respectively, then distance between them is |𝑝−𝑠|.

You can do the following operation at most 𝑥 times: choose two adjacent (neighbouring) students and swap them.

Calculate the maximum distance between two rivalling students after at most 𝑥 swaps.

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

The only line of each test case contains four integers 𝑛, 𝑥, 𝑎 and 𝑏 (2≤𝑛≤100, 0≤𝑥≤100, 1≤𝑎,𝑏≤𝑛, 𝑎≠𝑏) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.

Output
For each test case print one integer — the maximum distance between two rivaling students which you can obtain.
Example
Input
3
5 1 3 2
100 33 100 1
6 0 2 3

Output
2
99
1

Note
In the first test case you can swap students in positions 3 and 4. And then the distance between the rivals is equal to |4−2|=2.

In the second test case you don't have to swap students.

In the third test case you can't swap students.
*/
package main

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

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

	for i := 0; i < t; i++ {
		input2, _ := reader.ReadString('\n')
		arr := strings.Split(strings.TrimSpace(input2), " ")

		n, _ := strconv.Atoi(arr[0])
		x, _ := strconv.Atoi(arr[1])
		a, _ := strconv.Atoi(arr[2])
		b, _ := strconv.Atoi(arr[3])

		if x == 0 {
			fmt.Println(abs(a - b))
		} else if abs(a-b)+x >= (n - 1) {
			fmt.Println(n - 1)
		} else {
			fmt.Println(abs(a-b) + x)
		}
	}
}

func abs(n int) int {
	b := n >> 63
	return (n ^ b) - b
}

package main

import "fmt"

func main() {
	var q, n, x, a, b int64
	fmt.Scan(&q)
	for ; q > 0; q-- {
		fmt.Scan(&n, &x, &a, &b)
		max := b - a
		if max < 0 {
			max = -max
		}
		max += x
		if max > n-1 {
			max = n - 1
		}
		fmt.Println(max)
	}
}

package main

import "fmt"

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

	i := 0
	for i < t {
		var n int
		var x int
		var a int
		var b int
		fmt.Scanln(&n, &x, &a, &b)

		present := 0
		if a > b {
			present = a - b
		} else {
			present = b - a
		}
		max := n - 1
		remain := max - present

		if x >= remain {
			ans := max
			fmt.Println(ans)
		} else {
			ans := x + present
			fmt.Println(ans)
		}

		i++
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	text, _ := reader.ReadString('\n')
	t, _ := strconv.ParseInt(strings.TrimSpace(text), 10, 64)
	for i := int64(0); i < t; i++ {
		text, _ = reader.ReadString('\n')
		parts := strings.Split(text, " ")
		n, _ := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64)
		x, _ := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64)
		a, _ := strconv.ParseInt(strings.TrimSpace(parts[2]), 10, 64)
		b, _ := strconv.ParseInt(strings.TrimSpace(parts[3]), 10, 64)
		if a > b {
			a, b = b, a
		}
		ret := b - a + min(x, a+n-b-1)
		fmt.Println(ret)
	}
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func readInt() int {
	var ch byte
	var err error
	for {
		ch, err = reader.ReadByte()
		if err != nil {
			return 0
		}
		if unicode.IsDigit(rune(ch)) {
			break
		}
	}
	result := int(ch & 0xf)
	for {
		ch, err = reader.ReadByte()
		if err != nil || !unicode.IsDigit(rune(ch)) {
			return result
		}
		result = result*10 + int(ch&0xf)
	}
}

func main() {
	t := readInt()

	for t > 0 {
		n, x, a, b := readInt(), readInt(), readInt(), readInt()
		fmt.Println(minInt(n-1, absInt(a-b)+x))
		t--
	}
}

func absInt(x int) int {
	if x < 0 {
		return -x
	}

	return x
}

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

	return b
}

package main

import "fmt"

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

func main() {
	var n int
	fmt.Scan(&n)
	ans := make([]int, 0)
	for i := 0; i < n; i++ {
		var num, swap, a, b, ma, mb int
		fmt.Scan(&num, &swap, &a, &b)
		if a > b {
			a, b = b, a
		}
		mb += min(swap, num-b)
		swap -= mb
		ma -= min(swap, a-1)
		b += mb
		a += ma
		// fmt.Println("i", i, "mb", mb, "ma", ma)
		ans = append(ans, b-a)
	}
	for i := range ans {
		fmt.Println(ans[i])
	}
}

package main

import (
	"fmt"
)

func abs(x int) int {
	if x < 0 {
		x = -x
	}
	return x
}

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

func main() {
	var t int
	fmt.Scanf("%d ", &t)
	for t > 0 {
		var n, x, a, b int
		fmt.Scanf("%d %d %d %d ", &n, &x, &a, &b)
		fmt.Println(min(abs(a-b)+x, n-1))
		t--
	}
}

package main

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

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

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

func readInt64() int64 {
	i, err := strconv.ParseInt(ReadString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// ReadIntSlice returns an integer slice that has n integers.
func ReadIntSlice(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt()
	}
	return b
}

// ReadInt64Slice returns as int64 slice that has n integers.
func ReadInt64Slice(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt64()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Debugging ***********/

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

/*********** DP sub-functions ***********/

// ChMin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// ChMax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		// str := strconv.FormatInt(A[i], 10)  // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

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

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*******************************************************************/

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var t int
var n, x, a, b int

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		n, x, a, b = ReadInt4()
		solve()
	}
}

func solve() {
	if a > b {
		a, b = b, a
	}

	for {
		if x == 0 || a == 1 {
			break
		}

		a--
		x--
	}

	for {
		if x == 0 || b == n {
			break
		}

		b++
		x--
	}

	fmt.Println(AbsInt(b - a))
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

/*******************************************************************/

package main

import "fmt"

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

	for i := 0; i < q; i++ {
		var n, x, a, b int
		fmt.Scan(&n, &x, &a, &b)
		fmt.Println(min(n-1, dif(a, b)+x))
	}
}

func min(num1, num2 int) int {
	if num1 > num2 {
		return num2
	}

	return num1
}

func dif(num1, num2 int) int {
	if num1 > num2 {
		return num1 - num2
	}

	return num2 - num1
}

package main

import (
	"fmt"
)

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

package main

import (
	"fmt"
)

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func main() {
	var caseNum int
	fmt.Scanf("%d\n", &caseNum)
	for i := 0; i < caseNum; i++ {
		var n, x, a, b int
		fmt.Scanf("%d %d %d %d\n", &n, &x, &a, &b)
		fmt.Println(max(a, b) - min(a, b) + min(min(a, b)-1+n-max(a, b), x))
	}
}

package main

import "fmt"

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

	return a
}

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

		if b < a {
			a, b = b, a
		}

		toOne := min(a-1, swaps)
		ans := toOne
		swaps -= toOne
		toLast := min(n-b, swaps)
		ans += toLast
		fmt.Println(ans + (b - a))
	}
}

package main

import "fmt"

func min(a, b int) int {
    if a < b {
        return a
    } else {
        return b
    }
}
func main() {
    var T int
    fmt.Scanf("%d\n", &T)
    for T > 0 {
        T--
        var n, x, a, b int
        fmt.Scanf("%d %d %d %d\n", &n, &x, &a, &b)
        if a > b {
            a, b = b, a
        }
        fmt.Printf("%d\n", min(n-1, b - a + x))
    }
}

package main

import "fmt"

func abs(a int) int{
	if a < 0{
		return -a
	} else{
		return a
	}
}

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

func main(){
	var q int
	fmt.Scanln(&q)
	for i:= 0;i < q ; i++ {
		var n, x, a, b int
		fmt.Scanln(&n, &x, &a, &b)
		fmt.Println(min(n - 1, x + abs(a - b)))
	}
}

package main

import "fmt"

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

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d\n", &t)
	for t > 0 {
		t--
		fmt.Scanf("%d %d %d %d\n", &n, &x, &a, &b)
		//fmt.Printf("%d, %d, %d, %d, %d, %v, ", n, x, a, b, num, err)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

// A. Two Rival Students
/*
You are the gym teacher in the school.

There are 𝑛 students in the row. And there are two rivalling students among them. The first one is in position 𝑎, the second in position 𝑏. Positions are numbered from 1 to 𝑛 from left to right.

Since they are rivals, you want to maximize the distance between them. If students are in positions 𝑝 and 𝑠 respectively, then distance between them is |𝑝−𝑠|.

You can do the following operation at most 𝑥 times: choose two adjacent (neighbouring) students and swap them.

Calculate the maximum distance between two rivalling students after at most 𝑥 swaps.

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

The only line of each test case contains four integers 𝑛, 𝑥, 𝑎 and 𝑏 (2≤𝑛≤100, 0≤𝑥≤100, 1≤𝑎,𝑏≤𝑛, 𝑎≠𝑏) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.

Output
For each test case print one integer — the maximum distance between two rivaling students which you can obtain.
Example
Input
3
5 1 3 2
100 33 100 1
6 0 2 3

Output
2
99
1

Note
In the first test case you can swap students in positions 3 and 4. And then the distance between the rivals is equal to |4−2|=2.

In the second test case you don't have to swap students.

In the third test case you can't swap students.
*/
package main

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

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

	for i := 0; i < t; i++ {
		input2, _ := reader.ReadString('\n')
		arr := strings.Split(strings.TrimSpace(input2), " ")

		n, _ := strconv.Atoi(arr[0])
		x, _ := strconv.Atoi(arr[1])
		a, _ := strconv.Atoi(arr[2])
		b, _ := strconv.Atoi(arr[3])

		if x == 0 {
			fmt.Println(abs(a - b))
		} else if abs(a-b) == (n - 1) {
			fmt.Println(abs(a - b))
		} else {
			fmt.Println(abs(a-b) + x)
		}
	}
}

func abs(n int) int {
	b := n >> 63
	return (n ^ b) - b
}

package main

import "fmt"

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

	i := 0
	for i < t {
		var n int
		var x int
		var a int
		var b int
		fmt.Scanln(&n, &x, &a, &b)
		fmt.Println(n, x, a, b)

		// max distance is n-1 n-length of array x-max no of swaps a,b- pos of two
		present := 0
		if a > b {
			present = a - b
		} else {
			present = b - a
		}
		max := n - 1
		remain := max - present

		if x >= remain {
			ans := max
			fmt.Println(ans)
		} else {
			ans := x + present
			fmt.Println(ans)
		}
		i++
	}
}

package main

import (
	"fmt"
)

func abs(x int) int {
	if x < 0 {
		x = -x
	}
	return x
}

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

func main() {
	var t int
	fmt.Scanf("%d", &t)
	for t > 0 {
		var n, x, a, b int
		fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
		fmt.Println(min(abs(a-b)+x, n-1))
		t--
	}
}

package main

import (
	"fmt"
)

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

package main

import "fmt"

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func main() {
	var caseNum int
	fmt.Scanf("%d", &caseNum)
	for i := 0; i < caseNum; i++ {
		var n, x, a, b int
		fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
		fmt.Println(max(a, b) - min(a, b) + min(min(a, b)-1+n-max(a, b), x))
	}
}

package main

import "fmt"

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

	return a
}

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

		if b < a {
			a, b = b, a
		}

		toOne := min(a-1, swaps)
		ans := toOne
		swaps -= toOne
		toLast := min(n-b, swaps)
		ans += toLast
		fmt.Println(ans + (b - a))
	}
}

package main

import "fmt"

func min(a, b int) int {
    if a > b {
        return a
    } else {
        return b
    }
}
func main() {
    var T int
    fmt.Scanf("%d", &T)
    for T > 0 {
        T--
        var n, x, a, b int
        fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
        if a > b {
            var tmp = a;
            a = b;
            b = tmp;
        }
        fmt.Printf("%d\n", min(n-1, b - a + x))
    }
}

package main

import "fmt"

func min(a, b int) int {
    if a < b {
        return a
    } else {
        return b
    }
}
func main() {
    var T int
    fmt.Scanf("%d", &T)
    for T > 0 {
        T--
        var n, x, a, b int
        fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
        if a > b {
            var tmp = a;
            a = b;
            b = tmp;
        }
        fmt.Printf("%d\n", min(n-1, b - a + x))
    }
}

package main

import "fmt"

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

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("%d%d%d%d", &n, &x, &a, &b)
		fmt.Sprintf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func main() {
	var t, n, x, a, b int
	num, err := fmt.Scanf("%d", &t)
	fmt.Printf("%d, %v\n", num, err)
	for t > 0 {
		t--
		num, err = fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
		fmt.Printf("%d, %d, %d, %d, %d, %v, ", n, x, a, b, num, err)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
		fmt.Printf("%d, %d, %d, %d, ", n, x, a, b)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("%d%d%d%d", &n, &x, &a, &b)
		fmt.Printf("%d, %d, %d, %d", n, x, a, b)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("%d%d%d%d", &n, &x, &a, &b)
		fmt.Printf("%d, %d, ", abs(b-a)+x, abs(a-b)+x)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("%d%d%d%d", &n, &x, &a, &b)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func main() {
	var t, n, x, a, b int
	num, err := fmt.Scanf("%d\n", &t)
	for t > 0 {
		t--
		num, err = fmt.Scanf("%d %d %d %d", &n, &x, &a, &b)
		fmt.Printf("%d, %d, %d, %d, %d, %v, ", n, x, a, b, num, err)
		fmt.Printf("%d\n", min(n-1, abs(b-a)+x))
	}
}

package main

import "fmt"

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

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func main() {
	var t, n, x, a, b int
	fmt.Scanf("%d", &t)
	for t > 0 {
		t--

		fmt.Scanf("&d&d&d&d", &n, &x, &a, &b)
		fmt.Sprintf("%d\n", min(n-1, abs(b-a)+x))
	}
}


Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i, o}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i, m}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string s = s1s2...sm is called lexicographically smaller than a string t = t1t2...tm (where s ≠ t) if si < ti where i is the smallest index such that si ≠ ti. (so sj = tj for all j < i)

The first line of input contains a string s of length n (1 ≤ n ≤ 3·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially.

The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally.

NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx.

package main

import (
	"container/list"
	"fmt"
)

var n int
var stra string
var strb string
var mapa [500]int
var mapb [500]int

var sa int
var sb int

func main() {
	fmt.Scan(&stra)
	fmt.Scan(&strb)
	n = len(stra)

	lista := list.New()
	listb := list.New()
	//fmt.Println(lena)

	sa = n / 2
	sb = n / 2
	if n%2 == 1 {
		sb++
	}

	for _, chr := range stra {
		mapa[chr]++
	}
	for _, chr := range strb {
		mapb[chr]++
	}

	for chr := 'z'; chr >= 'a'; chr-- {
		if sa == 0 {
			break
		}
		if mapa[chr] > 0 {
			if sa <= mapa[chr] {
				mapa[chr] -= sa
				sa = 0
				break
			} else {
				sa -= mapa[chr]
				mapa[chr] = 0
			}
		}
	}

	for chr := 'a'; chr <= 'z'; chr++ {
		if sb == 0 {
			break
		}
		if mapb[chr] > 0 {
			if sb <= mapb[chr] {
				mapb[chr] -= sb
				sb = 0
				break
			} else {
				sb -= mapb[chr]
				mapb[chr] = 0
			}
		}
	}

	for i := 0; i < n; i++ {

		var mina rune
		for chr := 'a'; chr <= 'z'; chr++ {
			if mapa[chr] > 0 {
				mina = chr
				break
			}
		}

		var maxa rune
		for chr := 'z'; chr >= 'a'; chr-- {
			if mapa[chr] > 0 {
				maxa = chr
				break
			}
		}

		var minb rune
		for chr := 'a'; chr <= 'z'; chr++ {
			if mapb[chr] > 0 {
				minb = chr
				break
			}
		}

		var maxb rune
		for chr := 'z'; chr >= 'a'; chr-- {
			if mapb[chr] > 0 {
				maxb = chr
				break
			}
		}

		if i%2 == 0 {
			if maxb <= mina {
				listb.PushFront(maxa)
				mapa[maxa]--
			} else {
				lista.PushBack(mina)
				mapa[mina]--
			}

		} else {
			if maxb <= mina {
				listb.PushFront(minb)
				mapb[minb]--
			} else {
				lista.PushBack(maxb)
				mapb[maxb]--
			}
		}
	}

	for lista.Len() > 0 {
		fmt.Printf("%c", lista.Front().Value)
		lista.Remove(lista.Front())
	}

	for listb.Len() > 0 {
		fmt.Printf("%c", listb.Front().Value)
		listb.Remove(listb.Front())
	}

}
//asdfasd

package main

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

func findMin(letter []int) int {
	for i := 0;i < 26;i ++ {
		if letter[i] != 0 {
			return i
		}
	}
	return -1
}
func findMax(letter []int) int {
	for i := 25;i >= 0;i -- {
		if letter[i] != 0 {
			return i
		}
	}
	return 26
}
func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var olegString, igorString string
	olegLetter := make([]int, 26)
	igorLetter := make([]int, 26)
	fmt.Fscanf(reader, "%s\n", &olegString)
	fmt.Fscanf(reader, "%s\n", &igorString)
	n := len(olegString)
	ans := make([]byte, n)
	for i := 0;i < n;i ++ {
		olegLetter[int(olegString[i] - 'a')] ++
		igorLetter[int(igorString[i] - 'a')] ++
		ans[i] = '?'
	}
	olegCount, igorCount := (n + 1) / 2, n / 2
	olegSum, igorSum := 0, 0
	for i := 0;i < 26;i ++ {
		if olegSum + olegLetter[i] >= olegCount {
			olegLetter[i] = olegCount - olegSum
		}
		olegSum += olegLetter[i]
	}
	for i := 25;i >= 0;i -- {
		if igorSum + igorLetter[i] >= igorCount {
			igorLetter[i] = igorCount - igorSum
		}
		igorSum += igorLetter[i]
	}
	// turn = true => oleg
	// turn = false => igor
	for left, right, turn := 0, n - 1, true;left <= right; turn = !turn {
		olegMin := findMin(olegLetter)
		igorMax := findMax(igorLetter)
		if turn {
			if olegMin < igorMax {
				ans[left] = 'a' + byte(olegMin)
				left ++
				olegLetter[olegMin] --
			} else {
				olegMax := findMax(olegLetter)
				ans[right] = 'a' + byte(olegMax)
				right --
				olegLetter[olegMax] --
			}
		} else {
			if igorMax > olegMin {
				ans[left] = 'a' + byte(igorMax)
				left ++
				igorLetter[igorMax] --
			} else {
				igorMin := findMin(igorLetter)
				ans[right] = 'a' + byte(igorMin)
				right --
				igorLetter[igorMin] --
			}
		}
	}
	fmt.Printf("%s", string(ans))
}

package main

import "fmt"

var lena int
var stra string
var strb string
var mapa [500]int
var mapb [500]int

func main() {
	fmt.Scan(&stra)
	fmt.Scan(&strb)
	lena = len(stra)

	//fmt.Println(lena)

	for _, chr := range stra {
		mapa[chr]++
	}
	for _, chr := range strb {
		mapb[chr]++
	}

	for i := 0; i < lena; i++ {
		if i%2 == 0 {
			for chr := 'a'; chr <= 'z'; chr++ {
				if mapa[chr] > 0 {
					mapa[chr]--
					fmt.Printf("%c", chr)
					break
				}
			}
		} else {
			for chr := 'z'; chr >= 'a'; chr-- {
				if mapb[chr] > 0 {
					mapb[chr]--
					fmt.Printf("%c", chr)
					break
				}

			}
		}
	}

}

package main

import (
	"container/list"
	"fmt"
)

var n int
var stra string
var strb string
var mapa [500]int
var mapb [500]int

var sa int
var sb int

func main() {
	fmt.Scan(&stra)
	fmt.Scan(&strb)
	n = len(stra)

	lista := list.New()
	listb := list.New()
	//fmt.Println(lena)

	sa = n / 2
	sb = n / 2

	for _, chr := range stra {
		mapa[chr]++
	}
	for _, chr := range strb {
		mapb[chr]++
	}

	for chr := 'z'; chr >= 'a'; chr-- {
		if sa == 0 {
			break
		}
		if mapa[chr] > 0 {
			if sa <= mapa[chr] {
				mapa[chr] -= sa
				sa = 0
				break
			} else {
				sa -= mapa[chr]
				mapa[chr] = 0
			}
		}
	}

	for chr := 'a'; chr <= 'z'; chr++ {
		if sb == 0 {
			break
		}
		if mapb[chr] > 0 {
			if sb <= mapb[chr] {
				mapb[chr] -= sb
				sb = 0
				break
			} else {
				sb -= mapb[chr]
				mapb[chr] = 0
			}
		}
	}

	for i := 0; i < n; i++ {

		var mina rune
		for chr := 'a'; chr <= 'z'; chr++ {
			if mapa[chr] > 0 {
				mina = chr
				break
			}
		}

		var maxa rune
		for chr := 'z'; chr >= 'a'; chr-- {
			if mapa[chr] > 0 {
				maxa = chr
				break
			}
		}

		var minb rune
		for chr := 'a'; chr <= 'z'; chr++ {
			if mapb[chr] > 0 {
				minb = chr
				break
			}
		}

		var maxb rune
		for chr := 'z'; chr >= 'a'; chr-- {
			if mapb[chr] > 0 {
				maxb = chr
				break
			}
		}

		if i%2 == 0 {
			if maxb <= mina {
				listb.PushFront(maxa)
				mapa[maxa]--
			} else {
				lista.PushBack(mina)
				mapa[mina]--
			}

		} else {
			if maxb <= mina {
				listb.PushFront(minb)
				mapb[minb]--
			} else {
				lista.PushBack(maxb)
				mapb[maxb]--
			}
		}
	}

	for lista.Len() > 0 {
		fmt.Printf("%c", lista.Front().Value)
		lista.Remove(lista.Front())
	}

	for listb.Len() > 0 {
		fmt.Printf("%c", listb.Front().Value)
		listb.Remove(listb.Front())
	}

}

package main

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

func findMin(letter []int) int {
	for i := 0;i < 26;i ++ {
		if letter[i] != 0 {
			return i
		}
	}
	return -1
}
func findMax(letter []int) int {
	for i := 25;i >= 0;i -- {
		if letter[i] != 0 {
			return i
		}
	}
	return 26
}
func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var olegString, igorString string
	olegLetter := make([]int, 26)
	igorLetter := make([]int, 26)
	fmt.Fscanf(reader, "%s\n", &olegString)
	fmt.Fscanf(reader, "%s\n", &igorString)
	n := len(olegString)
	ans := make([]byte, n)
	for i := 0;i < n;i ++ {
		olegLetter[int(olegString[i] - 'a')] ++
		igorLetter[int(igorString[i] - 'a')] ++
		ans[i] = '?'
	}
	olegCount, igorCount := (n + 1) / 2, n / 2
	olegSum, igorSum := 0, 0
	for i := 0;i < 26;i ++ {
		if olegSum + olegLetter[i] >= olegCount {
			olegLetter[i] = olegCount - olegSum
			olegSum += olegLetter[i]
		}
	}
	for i := 25;i >= 0;i -- {
		if igorSum + igorLetter[i] >= igorCount {
			igorLetter[i] = igorCount - igorSum
			igorSum += igorLetter[i]
		}
	}
	// turn = true => oleg
	// turn = false => igor
	for left, right, turn := 0, n - 1, true;left <= right; turn = !turn {
		olegMin := findMin(olegLetter)
		igorMax := findMax(igorLetter)
		if turn {
			if olegMin < igorMax {
				ans[left] = 'a' + byte(olegMin)
				left ++
				olegLetter[olegMin] --
			} else {
				olegMax := findMax(olegLetter)
				ans[right] = 'a' + byte(olegMax)
				right --
				olegLetter[olegMax] --
			}
		} else {
			if igorMax > olegMin {
				ans[left] = 'a' + byte(igorMax)
				left ++
				igorLetter[igorMax] --
			} else {
				igorMin := findMin(igorLetter)
				ans[right] = 'a' + byte(igorMin)
				right --
				igorLetter[igorMin] --
			}
		}
	}
	fmt.Printf("%s", string(ans))
}


During the study of the Martians Petya clearly understood that the Martians are absolutely lazy. They like to sleep and don't like to wake up. Imagine a Martian who has exactly n eyes located in a row and numbered from the left to the right from 1 to n. When a Martian sleeps, he puts a patch on each eye (so that the Martian morning doesn't wake him up). The inner side of each patch has an uppercase Latin letter. So, when a Martian wakes up and opens all his eyes he sees a string s consisting of uppercase Latin letters. The string's length is n. "Ding dong!" — the alarm goes off. A Martian has already woken up but he hasn't opened any of his eyes. He feels that today is going to be a hard day, so he wants to open his eyes and see something good. The Martian considers only m Martian words beautiful. Besides, it is hard for him to open all eyes at once so early in the morning. So he opens two non-overlapping segments of consecutive eyes. More formally, the Martian chooses four numbers a, b, c, d, (1 ≤ a ≤ b < c ≤ d ≤ n) and opens all eyes with numbers i such that a ≤ i ≤ b or c ≤ i ≤ d. After the Martian opens the eyes he needs, he reads all the visible characters from the left to the right and thus, he sees some word.Let's consider all different words the Martian can see in the morning. Your task is to find out how many beautiful words are among them.

The first line contains a non-empty string s consisting of uppercase Latin letters. The strings' length is n (2 ≤ n ≤ 105). The second line contains an integer m (1 ≤ m ≤ 100) — the number of beautiful words. Next m lines contain the beautiful words pi, consisting of uppercase Latin letters. Their length is from 1 to 1000. All beautiful strings are pairwise different.

Print the single integer — the number of different beautiful strings the Martian can see this morning.

NoteLet's consider the sample test. There the Martian can get only the second beautiful string if he opens segments of eyes a = 1, b = 2 and c = 4, d = 5 or of he opens segments of eyes a = 1, b = 2 and c = 6, d = 7.

package main

import "fmt"

func reverse(s string) string {
	b := []byte(s)

	for l, r := 0, len(b) - 1; l < r; l, r = l+1, r-1 {
		b[l], b[r] = b[r], b[l]
	}

	return string(b)
}

func match(s, p string) ([]int, bool) {
	// fmt.Println("match", s, p)
	l := make([]int, len(p))
	l[0] = 0

	k := 0
	for i := 1; i < len(p); i++ {
		for k > 0 && p[k] != p[i] {
			k = l[k-1]
		}

		if p[k] == p[i] {
			k++
		}

		l[i] = k
	}
	// fmt.Println("l =", l)

	ends := make([]int, len(p))
	for i := 0; i < len(p); i++ {
		ends[i] = -1
	}

	k = 0
	for i := 0; i < len(s); i++ {
		for k > 0 && p[k] != s[i] {
			k = l[k-1]
		}

		if p[k] == s[i] {
			k++
		}

		if k == len(p) {
			return nil, true
		}

		if ends[k] == -1 || i < ends[k] {
			ends[k] = i
		}
	}

	// fmt.Println("ends", ends)

	return ends, false
}

func matchBeauty(s, t string) bool {
	ends, f := match(s, t)
	if f {
		return true
	}

	revEnds, f := match(reverse(s), reverse(t))
	if f {
		return true
	}

	for i := 1; i < len(t); i++ {
		if i1, i2 := ends[i], revEnds[len(t)-i]; i1 != -1 && i2 != -1 && i1 < len(s)-1-i2 {
			return true
		}
	}

	return false
}

func main() {
	var s string; fmt.Scan(&s)
	var m int; fmt.Scan(&m)

	c := 0
	for i := 0; i < m; i++ {
		var t string; fmt.Scan(&t)

		if len(t) == 1 {
			continue
		}

		if matchBeauty(s, t) {
			c++
		}
	}

	fmt.Println(c)
}


Aleksey has $$$n$$$ friends. He is also on a vacation right now, so he has $$$m$$$ days to play this new viral cooperative game! But since it's cooperative, Aleksey will need one teammate in each of these $$$m$$$ days.On each of these days some friends will be available for playing, and all others will not. On each day Aleksey must choose one of his available friends to offer him playing the game (and they, of course, always agree). However, if any of them happens to be chosen strictly more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times, then all other friends are offended. Of course, Aleksey doesn't want to offend anyone.Help him to choose teammates so that nobody is chosen strictly more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\leq n, m\leq 100\,000$$$) standing for the number of friends and the number of days to play, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains an integer $$$k_i$$$ ($$$1\leq k_i\leq n$$$), followed by $$$k_i$$$ distinct integers $$$f_{i1}$$$, ..., $$$f_{ik_i}$$$ ($$$1\leq f_{ij}\leq n$$$), separated by spaces — indices of available friends on the day $$$i$$$. It is guaranteed that the sums of $$$n$$$ and $$$m$$$ over all test cases do not exceed $$$100\,000$$$. It's guaranteed that the sum of all $$$k_i$$$ over all days of all test cases doesn't exceed $$$200\,000$$$.

Print an answer for each test case. If there is no way to achieve the goal, print "NO". Otherwise, in the first line print "YES", and in the second line print $$$m$$$ space separated integers $$$c_1$$$, ..., $$$c_m$$$. Each $$$c_i$$$ must denote the chosen friend on day $$$i$$$ (and therefore must be one of $$$f_{ij}$$$). No value must occur more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times. If there is more than one possible answer, print any of them.

package main

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

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

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

	for ; t > 0; t-- {
		fmt.Fscan(in, &n, &m)

		freeFriends := make([][]int, m)
		freeDaysCnt := make([]int, n)
		for i := 0; i < m; i++ {
			fmt.Fscan(in, &k)
			freeFriends[i] = make([]int, k)
			for j := 0; j < k; j++ {
				fmt.Fscan(in, &freeFriends[i][j])
				freeDaysCnt[freeFriends[i][j]-1]++
			}
		}

		// find most available friend
		f, maxFreeDays := 0, 0
		for i := range freeDaysCnt {
			if freeDaysCnt[i] > maxFreeDays {
				f, maxFreeDays = i+1, freeDaysCnt[i]
			}
		}

		// save his free days
		freeDays := make([]int, 0, maxFreeDays)
		for i := 0; i < m; i++ {
			for j := range freeFriends[i] {
				if freeFriends[i][j] == f {
					freeDays = append(freeDays, i)
				}
			}
		}

		schedule := make([]int, m)
		if maxFreeDays <= (m+1)/2 {
			// nobody will occur more than allowed
			for i := 0; i < m; i++ {
				schedule[i] = freeFriends[i][0]
			}
		} else {
			// count days when most available friend is only option
			cnt := 0
			for i := 0; i < m; i++ {
				if len(freeFriends[i]) == 1 && freeFriends[i][0] == f {
					schedule[i] = f
					cnt++
				}
			}
			if cnt > (m+1)/2 {
				fmt.Fprintln(out, "NO")
				out.Flush()
				continue
			}
			// schedule most available friend till count is (m+1)/2
			for i := range freeDays {
				if cnt == (m+1)/2 {
					break
				}
				if schedule[freeDays[i]] == 0 {
					schedule[freeDays[i]] = f
					cnt++
				}
			}
			// fill other days with any friend except most available
			for i := 0; i < m; i++ {
				if schedule[i] > 0 {
					continue
				}
				j := 0
				for ; freeFriends[i][j] == f; j++ {
				}
				schedule[i] = freeFriends[i][j]
			}
		}

		fmt.Fprintln(out, "YES")
		for i := range schedule {
			fmt.Fprint(out, schedule[i], " ")
		}
		fmt.Fprintln(out)
		out.Flush()
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1483A(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var T, n, m, k, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		ans := make([]int, m)
		one := make([]int, n+1)
		pos := make([][]int, n+1)
		mx := 0
		for i := 0; i < m; i++ {
			Fscan(in, &k)
			for j := 0; j < k; j++ {
				Fscan(in, &v)
				if k == 1 {
					one[v]++
					ans[i] = v
				}
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
			}
		}
		c := one[mx]
		if c > (m+1)/2 {
			Fprintln(out, "NO")
			continue
		}
		for _, p := range pos[mx] {
			if c == (m+1)/2 {
				break
			}
			if ans[p] == 0 {
				ans[p] = mx
				c++
			}
		}
		for i, ps := range pos {
			if i != mx {
				for _, p := range ps {
					if ans[p] == 0 {
						ans[p] = i
					}
				}
			}
		}
		Fprintln(out, "YES")
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}
func main() { CF1483A(os.Stdin, os.Stdout) }

package main
import (
	"bufio"
	. "fmt"
	"io"
	"os"
)
// github.com/EndlessCheng/codeforces-go
func CF1483A(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var T, n, m, k,v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		m2 := (m + 1) / 2
		cnt := make([]int, n+1)
		pos := make([][]int, n+1)
		mx := 0
		ans := make([]int, m)
		for i := 0; i < m; i++ {
			Fscan(in, &k)
			if k == 1 {
				Fscan(in, &v)
				cnt[v]++
				ans[i] = v
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
				continue
			}
			for ; k > 0; k-- {
				Fscan(in, &v)
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
			}
		}
		c := cnt[mx]
		if c > m2 {
			Fprintln(out, "NO")
			continue
		}
		for _, p := range pos[mx] {
			if c == m2 {
				break
			}
			if ans[p] == 0 {
				ans[p] = mx
				c++
			}
		}
		for i, ps := range pos {
			if i != mx {
				for _, p := range ps {
					if ans[p] == 0 {
						ans[p] = i
					}
				}
			}
		}
		Fprintln(out, "YES")
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}

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

package main

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

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

	var T, n, m, k, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		m2 := (m + 1) / 2
		cnt := make([]int, n+1)
		pos := make([][]int, n+1)
		mx := 0
		ans := make([]int, m)
		for i := 0; i < m; i++ {
			Fscan(in, &k)
			if k == 1 {
				Fscan(in, &v)
				cnt[v]++
				ans[i] = v
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
				continue
			}
			for ; k > 0; k-- {
				Fscan(in, &v)
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
			}
		}
		c := cnt[mx]
		if c > m2 {
			Fprintln(out, "NO")
			continue
		}
		for _, p := range pos[mx] {
			if c == m2 {
				break
			}
			if ans[p] == 0 {
				ans[p] = mx
				c++
			}
		}
		for i, ps := range pos {
			if i != mx {
				for _, p := range ps {
					if ans[p] == 0 {
						ans[p] = i
					}
				}
			}
		}
		Fprintln(out, "YES")
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}
func main() { CF1483A(os.Stdin, os.Stdout) }

package main

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

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

	var t int
	for fmt.Fscan(reader, &t); t > 0; t-- {
		var n, m int
		fmt.Fscan(reader, &n, &m)

		limit := int(math.Ceil(float64(m) / 2.0))
		weights := make([]int, n+1)
		avail := make([][]int, m)
		final := make([]int, m)
		canMake := true

		for i := 0; i < m; i++ {
			var a, temp int
			fmt.Fscan(reader, &a)
			for j := 0; j < a; j++ {
				fmt.Fscan(reader, &temp)
				avail[i] = append(avail[i], temp)
			}

			if a == 0 {
				canMake = false
			}
			if a == 1 {
				weights[temp]++
				final[i] = temp
				if weights[temp] > limit {
					canMake = false
				}
			}
		}

		if !canMake {
			fmt.Fprintln(writer, "NO")
			continue
		}

		for i := 0; i < m; i++ {
			if len(avail[i]) > 1 {
				minimum := avail[i][0]
				for _, val := range avail[i] {
					if weights[val] < weights[minimum] {
						minimum = val
					}
				}
				final[i] = minimum
				weights[minimum]++
				if weights[minimum] > limit {
					canMake = false
					break
				}
			}
		}

		if !canMake {
			fmt.Fprintln(writer, "NO")
			continue
		}

		fmt.Fprintln(writer, "YES")
		for i, val := range final {
			fmt.Fprint(writer, val)
			if i != len(final)-1 {
				fmt.Fprint(writer, " ")
			}
		}
		fmt.Fprintln(writer)

	}
	writer.Flush()
}

package main

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

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

	var T, n, m, k, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		ans := make([]int, m)
		one := make([]int, n+1)
		pos := make([][]int, n+1)
		mx := 0
		for i := 0; i < m; i++ {
			Fscan(in, &k)
			for j := 0; j < k; j++ {
				Fscan(in, &v)
				if k == 1 {
					one[v]++
					ans[i] = v
				}
				pos[v] = append(pos[v], i)
				if len(pos[v]) > len(pos[mx]) {
					mx = v
				}
			}
		}
		c := one[mx]
		if c > (m+1)/2 {
			Fprintln(out, "NO")
			continue
		}
		for _, p := range pos[mx] {
			if c == (m+1)/2 {
				break
			}
			if ans[p] == 0 {
				ans[p] = mx
				c++
			}
		}
		for i, ps := range pos {
			if i != mx {
				for _, p := range ps {
					if ans[p] == 0 {
						ans[p] = i
					}
				}
			}
		}
		Fprintln(out, "YES")
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}

package main

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

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

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

	for ; t > 0; t-- {
		fmt.Fscan(in, &n, &m)

		freeFriends := make([][]int, m)
		freeDaysCnt := make([]int, n)
		for i := 0; i < m; i++ {
			fmt.Fscan(in, &k)
			freeFriends[i] = make([]int, k)
			for j := 0; j < k; j++ {
				fmt.Fscan(in, &freeFriends[i][j])
				freeDaysCnt[freeFriends[i][j]-1]++
			}
		}

		// find most available friend
		f, maxFreeDays := 0, 0
		for i := range freeDaysCnt {
			if freeDaysCnt[i] > maxFreeDays {
				f, maxFreeDays = i+1, freeDaysCnt[i]
			}
		}

		// save his free days
		freeDays := make([]int, 0, maxFreeDays)
		for i := 0; i < m; i++ {
			for j := range freeFriends[i] {
				if freeFriends[i][j] == f {
					freeDays = append(freeDays, i)
				}
			}
		}

		schedule := make([]int, m)
		if maxFreeDays <= (m+1)/2 {
			// nobody will occur more than allowed
			for i := 0; i < m; i++ {
				schedule[i] = freeFriends[i][0]
			}
		} else {
			// count days when most available friend is only option
			cnt := 0
			for i := 0; i < m; i++ {
				if len(freeFriends[i]) == 1 && freeFriends[i][0] == f {
					schedule[i] = f
					cnt++
				}
			}
			if cnt > (m+1)/2 {
				fmt.Fprintln(out, "NO")
				out.Flush()
				continue
			}
			// schedule most available friend till count is (m+1)/2
			for i := range freeDays {
				if schedule[freeDays[i]] == 0 {
					schedule[freeDays[i]] = f
					cnt++
				}
				if cnt == (m+1)/2 {
					break
				}
			}
			// fill other days with any friend except most available
			for i := 0; i < m; i++ {
				if schedule[i] > 0 {
					continue
				}
				j := 0
				for ; freeFriends[i][j] == f; j++ {
				}
				schedule[i] = freeFriends[i][j]
			}
		}

		fmt.Fprintln(out, "YES")
		for i := range schedule {
			fmt.Fprint(out, schedule[i], " ")
		}
		fmt.Fprintln(out)
		out.Flush()
	}
}


Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $$$n$$$ sessions follow the identity permutation (ie. in the first game he scores $$$1$$$ point, in the second game he scores $$$2$$$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up! Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $$$[1,2,3]$$$ can yield $$$[3,1,2]$$$ but it cannot yield $$$[3,2,1]$$$ since the $$$2$$$ is in the same position. Given a permutation of $$$n$$$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $$$10^{18}$$$.An array $$$a$$$ is a subarray of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the given permutation. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ ($$$1 \leq a_{i} \leq n$$$)  — the initial permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.

NoteIn the first permutation, it is already sorted so no exchanges are needed.It can be shown that you need at least $$$2$$$ exchanges to sort the second permutation.$$$[3, 2, 4, 5, 1, 6, 7]$$$Perform special exchange on range ($$$1, 5$$$)$$$[4, 1, 2, 3, 5, 6, 7]$$$Perform special exchange on range ($$$1, 4$$$)$$$[1, 2, 3, 4, 5, 6, 7]$$$

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

type priorityQueue [][2]int

func (pq priorityQueue) Len() int {
	return len(pq)
}

func (pq priorityQueue) Less(i, j int) bool {
	return pq[i][1] > pq[j][1]
}

func (pq priorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *priorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.([2]int))
}

func (pq *priorityQueue) Pop() (res interface{}) {
	res = (*pq)[len(*pq)-1]
	*pq = (*pq)[:len(*pq)-1]
	return res
}

var err error

func NextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func NextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("in")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

	for cases := NextInt(); cases > 0; cases-- {
		n := NextInt()
		tot := 0
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = NextInt()
			if i+1 != arr[i] {
				if i == 0 || arr[i-1] == i {
					tot++
				}
			}
		}
		if tot > 2 {
			tot = 2
		}
		printf("%d\n", tot)
	}
}

package main

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

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

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)
		A := readNNums(reader, n)
		fmt.Println(solve(n, A))
	}
}

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 int, A []int) int {
	var i int
	for i < n && i+1 == A[i] {
		i++
	}
	if i == n {
		return 0
	}

	j := n - 1
	for j >= 0 && j+1 == A[j] {
		j--
	}

	k := i
	for k <= j && k+1 != A[k] {
		k++
	}

	if k > j {
		return 1
	}

	return 2
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var t, n int
	fmt.Fscan(reader, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(reader, &n)
		a := make([]int, n + 1)
		for j := 1; j <= n; j++ {
			fmt.Fscan(reader, &a[j])
		}
		var l, r, res int
		for l = 1; l <= n; l++ {
			if a[l] != l {
				break
			}
		}
		for r = n; r >= 1; r-- {
			if a[r] != r {
				break
			}
		}
		if r == 0 {
			res = 0
		} else {
			res = 1
		}
		for ; l <= r; l++ {
			if a[l] == l {
				res = 2
			}
		}
		fmt.Fprintln(writer, res)
	}
}//2020-07-29 22:20:05.502

package main

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

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	var T int
	con.Scan(&T)
	for testcase := 0; testcase < T; testcase++ {
		var n int
		con.Scan(&n)
		x := make([]bool, n)
		c := 0
		for i := 0; i < n; i++ {
			var a int
			con.Scan(&a)
			if a == i+1 {
				c++
				x[i] = true
			}
		}
		if c == n {
			con.Println(0)
			continue
		}
		p := 0
		for i := 0; i < n; i++ {
			if !x[i] && (i == 0 || x[i-1]) {
				p++
			}
		}
		if p == 1 {
			con.Println(1)
		} else {
			con.Println(2)
		}
	}
	return nil
}

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

type priorityQueue [][2]int

func (pq priorityQueue) Len() int {
	return len(pq)
}

func (pq priorityQueue) Less(i, j int) bool {
	return pq[i][1] > pq[j][1]
}

func (pq priorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *priorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.([2]int))
}

func (pq *priorityQueue) Pop() (res interface{}) {
	res = (*pq)[len(*pq)-1]
	*pq = (*pq)[:len(*pq)-1]
	return res
}

var err error

func NextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func NextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}
func Euclid(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	gcd, s1, s2 := Euclid(b, a%b)
	return gcd, s2, s1 - s2*(a/b)
}

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("in")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

	for cases := NextInt(); cases > 0; cases-- {
		n := NextInt()
		tot := 0
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = NextInt()
			if i+1 != arr[i] {
				if i == 0 || arr[i-1] == i {
					tot++
				}
			}
		}
		printf("%d\n", tot)
	}
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	//defer writer.Flush()
	var t, n int
	fmt.Fscan(reader, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(reader, &n)
		a := make([]int, n + 1)
		for j := 1; j <= n; j++ {
			fmt.Fscan(reader, &a[j])
		}
		var l, r, res int
		for l = 1; l <= n; l++ {
			if a[l] != l {
				break
			}
		}
		for r = n; r >= 1; r-- {
			if a[r] != r {
				break
			}
		}
		if r == 0 {
			res = 0
		} else {
			res = 1
		}
		for ; l <= r; l++ {
			if a[l] == l {
				res = 2
			}
		}
		fmt.Fprintln(writer, res)
	}
}

package main

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

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

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)
		A := readNNums(reader, n)
		fmt.Println(solve(n, A))
	}
}

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 int, A []int) int {
	var i int
	for i < n && i+1 == A[i] {
		i++
	}
	if i == n {
		return 0
	}
	j := i
	for j < n && j+1 != A[j] {
		j++
	}
	if j == n {
		return 1
	}
	j = n - 1
	for j >= 0 && j+1 == A[j] {
		j--
	}
	// j won't < 0
	i = j
	for i >= 0 && i+1 != A[i] {
		i--
	}

	if i < 0 {
		return 1
	}

	return 2
}

package main

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

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

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)
		A := readNNums(reader, n)
		fmt.Println(solve(n, A))
	}
}

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 int, A []int) int {
	var loop func(i, j int, flipped bool)

	var res int

	loop = func(i, j int, flipped bool) {
		for i < j && (A[i] == i+1) == !flipped {
			i++
		}
		for j > i && (A[j-1] == j) == !flipped {
			j--
		}
		if i < j {
			res++
			loop(i, j, !flipped)
		}
	}

	loop(0, n, false)

	return res
}


You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$:   $$$\mathit{in'}_v < \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$;  $$$\mathit{out'}_v < \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.

Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.

NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func I(a int) int64 { return int64(a) }
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int64 { i,e := strconv.ParseInt(gs(),10,64); if e != nil {panic(e)}; return i }
func gi2() (int64,int64) { return gi(),gi() }
func gi3() (int64,int64,int64) { return gi(),gi(),gi() }
func gi4() (int64,int64,int64,int64) { return gi(),gi(),gi(),gi() }
func gis(n int64) []int64 { res := make([]int64,n); for i:=I(0);i<n;i++ { res[i] = gi() }; return res }
func gf() float64 { f,e := strconv.ParseFloat(gs(),64); if e != nil {panic(e)}; return f }
func gbs() []byte { return []byte(gs()) }
func gfs(n int64) []float64  { res := make([]float64,n); for i:=I(0);i<n;i++ { res[i] = gf() }; return res }
func gss(n int64) []string  { res := make([]string,n); for i:=I(0);i<n;i++ { res[i] = gs() }; return res }
func ia(m int64) []int64 { return make([]int64,m) }
func iai(m int64,v int64) []int64 { a := make([]int64,m); for i:=I(0);i<m;i++ { a[i] = v }; return a }
func twodi(n int64,m int64,v int64) [][]int64 {
	r := make([][]int64,n); for i:=I(0);i<n;i++ { x := make([]int64,m); for j:=I(0);j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill2(m int64) ([]int64,[]int64) { a,b := ia(m),ia(m); for i:=I(0);i<m;i++ {a[i],b[i] = gi(),gi()}; return a,b }
func fill3(m int64) ([]int64,[]int64,[]int64) { a,b,c := ia(m),ia(m),ia(m); for i:=I(0);i<m;i++ {a[i],b[i],c[i] = gi(),gi(),gi()}; return a,b,c }
func fill4(m int64) ([]int64,[]int64,[]int64,[]int64) { a,b,c,d := ia(m),ia(m),ia(m),ia(m); for i:=I(0);i<m;i++ {a[i],b[i],c[i],d[i] = gi(),gi(),gi(),gi()}; return a,b,c,d }
func abs(a int64) int64 { if a < 0 { return -a }; return a }
func rev(a []int64) { i,j := I(0),I(len(a)-1); for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
func max(a,b int64) int64 { if a > b { return a }; return b }
func min(a,b int64) int64 { if a > b { return b }; return a }
func tern(cond bool, a int64, b int64) int64 { if cond { return a }; return b }
func terns(cond bool, a string, b string) string { if cond { return a }; return b }
func maxarr(a []int64) int64 { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr(a []int64) int64 { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr(a []int64) int64 { ans := I(0); for _,aa := range(a) { ans += aa }; return ans }
func zeroarr(a []int64) { for i:=I(0); i<I(len(a)); i++ { a[i] = 0 } }
func powmod(a,e,mod int64) int64 { res, m := I(1), a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint(a,e int64) int64 { res, m := I(1), a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd(a,b int64) int64 { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended(a,b int64) (int64,int64,int64) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv(a,m int64) (int64,bool) { g,x,_ := gcdExtended(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func makefact(n int64,mod int64) ([]int64,[]int64) {
	fact,factinv := make([]int64,n+1),make([]int64,n+1)
	fact[0] = 1; for i:=I(1);i<=n;i++ { fact[i] = fact[i-1] * i % mod }
	factinv[n] = powmod(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * (i+1) % mod }
	return fact,factinv
}
const inf int64 = 1000000000000000000
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	N,M := gi(),gi(); U,V := fill2(M); for i:=I(0);i<M;i++ { U[i]--; V[i]-- }
	gr:=make([][]int64,N); grrev := make([][]int64,N)
	for i:=I(0);i<M;i++ { u,v := U[i],V[i]; gr[u] = append(gr[u],v); grrev[v] = append(grrev[v],u) }
	numdeps := make([]int64,N); for i:=I(0);i<N;i++ { numdeps[i] = I(len(gr[i])) }
	q := make([]int64,0); for i:=I(0);i<N;i++ { if numdeps[i] == 0 { q = append(q,i) } }
	ans := I(1)
	maxsuffix := make([]int64,N)
	for len(q) != 0 {
		n := q[0]; q = q[1:]
		startok := len(gr[n]) >= 2
		endok   := len(grrev[n]) >= 2
		cand := I(1)
		if startok {
			for _,c := range gr[n] { cand = max(cand,1+maxsuffix[c]) }
			ans = max(cand,ans)
		}
		if endok { maxsuffix[n] = 1 }
		if startok && endok { maxsuffix[n] = cand }
		for _,p := range grrev[n] { numdeps[p]--; if numdeps[p] == 0 { q = append(q,p) } }
	}
	fmt.Println(ans)
}

package main

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

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

var g [][]int
var inn, outt, dp []int

func solve() {
	var n, m int
	fmt.Fscan(in, &n, &m)
	g = make([][]int, 200009)
	inn = make([]int, 200009)
	outt = make([]int, 200009)
	dp = make([]int, 200009)
	for i := 0; i < m; i++ {
		var u, v int
		fmt.Fscan(in, &u, &v)
		g[v] = append(g[v], u)
		outt[v]++
		inn[u]++
	}
	z := make([]int, 200009)
	copy(z, inn)
	q := make([]int, 0)
	for i := 1; i <= n; i++ {
		dp[i] = 1
		if inn[i] == 0 {
			q = append(q, i)
		}
	}
	ans := 1
	for len(q) > 0 {
		x := q[0]
		q = q[1:]
		if len(g[x]) < 2 {
			if len(g[x]) == 1 {
				z[g[x][0]]--
				if z[g[x][0]] == 0 {
					q = append(q, g[x][0])
				}
			}
			ans = max(ans, dp[x])
			continue
		}
		for _, v := range g[x] {
			if inn[v] == 1 {
				q = append(q, v)
				dp[v] = max(dp[v], 1)
				ans = max(ans, dp[v])
				z[v]--
				continue
			}
			z[v]--
			dp[v] = max(dp[v], dp[x]+1)
			ans = max(ans, dp[v])
			if z[v] == 0 {
				q = append(q, v)
			}
		}
	}
	fmt.Fprintf(out, "%d\n", ans)
}

func main() {
	defer out.Flush()
	var t int
	for t = 1; t > 0; t-- {
		solve()
	}
}
func min(a int, b int) int {
	if a < b {
		return a
	}
	return b
}

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