Vasiliy has an exam period which will continue for n days. He has to pass exams on m subjects. Subjects are numbered from 1 to m.About every day we know exam for which one of m subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day. On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest. About each subject Vasiliy know a number ai — the number of days he should prepare to pass the exam number i. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during ai days for the exam number i. He can mix the order of preparation for exams in any way.Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time.

The first line contains two integers n and m (1 ≤ n, m ≤ 105) — the number of days in the exam period and the number of subjects.  The second line contains n integers d1, d2, ..., dn (0 ≤ di ≤ m), where di is the number of subject, the exam of which can be passed on the day number i. If di equals 0, it is not allowed to pass any exams on the day number i.  The third line contains m positive integers a1, a2, ..., am (1 ≤ ai ≤ 105), where ai is the number of days that are needed to prepare before passing the exam on the subject i.

Print one integer — the minimum number of days in which Vasiliy can pass all exams. If it is impossible, print -1.

NoteIn the first example Vasiliy can behave as follows. On the first and the second day he can prepare for the exam number 1 and pass it on the fifth day, prepare for the exam number 2 on the third day and pass it on the fourth day.In the second example Vasiliy should prepare for the exam number 3 during the first four days and pass it on the fifth day. Then on the sixth day he should prepare for the exam number 2 and then pass it on the seventh day. After that he needs to prepare for the exam number 1 on the eighth day and pass it on the ninth day. In the third example Vasiliy can't pass the only exam because he hasn't anough time to prepare for it.

package main

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

func solve() {
    n, m := readInt(), readInt()
    dd, a := readIntArray(n), readIntArray(m)

    can := func(t int) bool {
        d, was, ord := make([]int, n), make([]bool, m), []int{}
        copy(d, dd)
        for i := t; i >= 0; i-- {
            if ex := d[i]-1; ex >= 0 && !was[ex] {
                was[ex] = true
                ord = append(ord, ex)
            } else {
                d[i] = 0
            }
        }
        if len(ord) < m {
            return false
        }
        p, j := make([]int, m), m-1
        for i := 0; i <= t; i++ {
            if d[i] == 0 {
                ex := ord[j]
                p[ex]++
                if p[ex] == a[ex] && j > 0 {
                    j--
                }
            } else {
                ex := d[i]-1
                if p[ex] < a[ex] {
                    return false
                }
            }
        }
        return true
    }

    l, r := 0, n
    for l < r {
        if mid := (l + r) / 2; can(mid) {
            r = mid
        } else {
            l = mid+1
        }
    }

    if r == n {
        fmt.Println(-1)
    } else {
        fmt.Println(r+1)
    }
}

// Helpers

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func main() {
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

// Math

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

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

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

// IO

func readString() string {
	scanner.Scan()
	return scanner.Text()
}

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

func readInt64() int64 {
	v, _ := strconv.ParseInt(readString(), 10, 64)
	return v
}

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

func readInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := 0; i < n; i++ {
		res[i] = readInt64()
	}
	return res
}

// Sort

type Ints64 []int64

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

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer

var m int
var d, a, last, cnt []int
var chose []bool

func passed(n int) bool {
	for i := 0; i <= m; i++ {
		last[i] = -1
	}

	for i := 1; i <= n; i++ {
		last[d[i]] = i
		chose[i] = false
	}

	for i := 1; i <= m; i++ {
		pos := last[i]
		if pos == -1 {
			return false
		}
		chose[pos] = true
	}

	cnt := 0
	for i := 1; i <= n; i++ {
		if chose[i] {
			cnt -= a[d[i]]
			if cnt < 0 {
				return false
			}
		} else {
			cnt++
		}
	}

	return true
}

func solution(n int) int {
	res := -1

	last = make([]int, m+1)
	chose = make([]bool, n+1)

	low := 1
	high := n

	for low <= high {
		mid := (low + high) / 2
		if passed(mid) {
			res = mid
			high = mid - 1
		} else {
			low = mid + 1
		}
	}

	return res
}

func main() {
	bufin = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
	defer bufout.Flush()

	var n int
	fmt.Fscanf(bufin, "%d %d\n", &n, &m)

	d = make([]int, n+1)
	for i := 1; i <= n; i++ {
		fmt.Fscanf(bufin, "%d\n", &d[i])
	}

	a = make([]int, m+1)
	for i := 1; i <= m; i++ {
		fmt.Fscanf(bufin, "%d\n", &a[i])
	}

	fmt.Fprintf(bufout, "%d\n", solution(n))
}

package main

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

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

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

    d := make([]int, n)
    f := 0
    p := make(map[int]int)
    line, _ := bin.ReadString('\n')
    for i, v := range strings.Split(line, " ") {
        d[i], _ = strconv.Atoi(strings.TrimSpace(v))
        if _, ok := p[d[i]]; !ok {
            p[d[i]] = i
            if i > f {
                f = i
            }
        }
    }

    s := int64(m - 1)
    line, _ = bin.ReadString('\n')
    for _, v := range strings.Split(line, " ") {
        x, _ := strconv.Atoi(strings.TrimSpace(v))
        s += int64(x)
    }
    if s < int64(f) {
        s = int64(f)
    }

    for i := s; i < int64(n); i++ {
        if d[i] > 0 {
            fmt.Printf("%d\n", i + 1)
            return
        }
    }
    fmt.Printf("-1\n");
}

package main

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

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

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r:rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

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

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

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

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}
func fill(arr []int, v int) {
	for i := 0; i < len(arr); i++ {
		arr[i] = v
	}
}
func max(a int, b int) int {
	if a < b {
		return b
	}
	return a
}

func main() {
	sc := NewScanner()
	n, m := sc.NextInt(), sc.NextInt()
	d := sc.NextIntArray()
	a := sc.NextIntArray()

	l := 0
	r := n
	count := make([]int, m + 1)

	check := func(c int) bool {
		che := make([]bool, m + 1)
		for j := 0; j < m; j++ {
			count[j + 1] = a[j]
		}
		queue := make([]int, m + 1)
		p := 0
		cur := 0
		for i := c; i >= 0; i-- {
			if d[i] > 0 && !che[d[i]] {

				che[d[i]] = true
				queue[p] = d[i]
				p += 1

			} else {
				if cur < p {
					count[queue[cur]]--
					if count[queue[cur]] == 0 {
						cur++
					}
				}

			}
		}

		for j := 1; j <= m; j++ {
			if count[j] > 0 {
				return false
			}
		}
		return true
	}

	for r - l > 1 {
		c := (l + r) / 2
		if check(c) {
			r = c
		} else {
			l = c
		}
	}
	if r == n {
		fmt.Println(-1)
	} else {
		fmt.Println(r + 1)
	}

}

package main

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

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

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

    d := make([]int, n)
    line, _ := bin.ReadString('\n')
    for i, v := range strings.Split(line, " ") {
        d[i], _ = strconv.Atoi(strings.TrimSpace(v))
    }

    s := int64(m)
    line, _ = bin.ReadString('\n')
    for _, v := range strings.Split(line, " ") {
        x, _ := strconv.Atoi(strings.TrimSpace(v))
        s += int64(x)
    }

    for i := s - 1; i < int64(n); i++ {
        if d[i] > 0 {
            fmt.Printf("%d\n", i + 1)
            return
        }
    }
    fmt.Printf("-1\n");
}

package main

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

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

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

    d := make([]int, n)
    line, _ := bin.ReadString('\n')
    for i, v := range strings.Split(line, " ") {
        d[i], _ = strconv.Atoi(strings.TrimSpace(v))
    }

    s := int64(m)
    line, _ = bin.ReadString('\n')
    for _, v := range strings.Split(line, " ") {
        x, _ := strconv.Atoi(strings.TrimSpace(v))
        s += int64(x)
    }

    for i := s - 1; i < int64(n); i++ {
        if d[i] > 0 {
            fmt.Printf("%d\n", i + 1)
            return
        }
    }
    fmt.Printf("-1\n");
}

package main

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

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

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r:rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

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

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

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

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}
func fill(arr []int, v int) {
	for i := 0; i < len(arr); i++ {
		arr[i] = v
	}
}
func max(a int, b int) int {
	if a < b {
		return b
	}
	return a
}

func main() {
	sc := NewScanner()
	n, m := sc.NextInt(), sc.NextInt()
	d := sc.NextIntArray()
	a := sc.NextIntArray()

	l := 0
	r := n
	count := make([]int, m + 1)

	check := func(c int) bool {
		check := make([]bool, m + 1)
		for j := 0; j < m; j++ {
			count[j + 1] = a[j]
		}
		queue := make([]int, m + 1)
		p := 0
		cur := 0
		for i := c; i >= 0; i-- {
			if p >= 0 && cur < p {
				count[queue[cur]]--
				if count[queue[cur]] == 0 {
					cur++
				}
			}
			if d[i] > 0 && !check[d[i]] {

				check[d[i]] = true
				queue[p] = d[i]
				p += 1

			}
		}

		for j := 1; j <= m; j++ {
			if count[j] > 0 {
				return false
			}
		}
		return true
	}

	for r - l > 1 {
		c := (l + r) / 2
		if check(c) {
			r = c
		} else {
			l = c
		}
	}
	if r == n {
		fmt.Println(-1)
	} else {
		fmt.Println(r + 1)
	}

}


Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.

The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 100, 1 ≤ q ≤ 10 000) — dimensions of the matrix and the number of turns in the experiment, respectively. Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 ≤ ti ≤ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 ≤ ri ≤ n) or ci (1 ≤ ci ≤ m) follows, while for the operations of the third type three integers ri, ci and xi (1 ≤ ri ≤ n, 1 ≤ ci ≤ m,  - 109 ≤ xi ≤ 109) are given. Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.

Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value. If there are multiple valid solutions, output any of them.

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	mul := 1
	for _, b := range in.Bytes() {
		if b == '-' {
			mul *= -1
			continue
		}
		res = res*10 + int(b-'0')
	}
	return mul * res
}

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

	n := readInt()
	m := readInt()
	q := readInt()

	val := make([]int, n*m)
	matrix := make([][]int, n)
	for i := range matrix {
		matrix[i] = make([]int, m)
		for j := range matrix[i] {
			matrix[i][j] = i*m + j
		}
	}
	for iq := 0; iq < q; iq++ {
		switch readInt() {
		case 1:
			row := matrix[readInt()-1]
			first := row[0]
			for i := range row[1:] {
				row[i] = row[i+1]
			}
			row[len(row)-1] = first
		case 2:
			c := readInt() - 1
			first := matrix[0][c]
			for i := range matrix[1:] {
				matrix[i][c] = matrix[i+1][c]
			}
			matrix[len(matrix)-1][c] = first
		case 3:
			val[matrix[readInt()-1][readInt()-1]] = readInt()
		default:
			panic("switch")
		}
	}
	for i, v := range val {
		if (i+1)%m == 0 {
			fmt.Fprintln(out, v)
		} else {
			fmt.Fprint(out, v, " ")
		}
	}
}

package main

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

func main() {
	defer out.Flush()
	n := in.NextInt()
	m := in.NextInt()
	q := in.NextInt()
	qs := make([]Query, q)
	for i := range qs {
		qs[i].t = in.NextInt()
		switch qs[i].t {
		case 1:
			qs[i].r = in.NextInt() - 1
		case 2:
			qs[i].c = in.NextInt() - 1
		case 3:
			qs[i].r = in.NextInt() - 1
			qs[i].c = in.NextInt() - 1
			qs[i].x = in.NextInt()
		}
	}
	ans := make([][]int, n)
	for i := range ans {
		ans[i] = make([]int, m)
	}
	for i := q - 1; i >= 0; i-- {
		q := qs[i]
		switch q.t {
		case 1:
			last := ans[q.r][m-1]
			for i := m - 1; i > 0; i-- {
				ans[q.r][i] = ans[q.r][i-1]
			}
			ans[q.r][0] = last
		case 2:
			last := ans[n-1][q.c]
			for i := n - 1; i > 0; i-- {
				ans[i][q.c] = ans[i-1][q.c]
			}
			ans[0][q.c] = last
		case 3:
			ans[q.r][q.c] = q.x
		}
	}
	for i := range ans {
		for j := range ans[i] {
			if j != 0 {
				fmt.Fprint(out, " ")
			}
			fmt.Fprint(out, ans[i][j])
		}
		fmt.Fprintln(out)
	}
}

type Query struct {
	t, r, c, x int
}

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

type FastReader struct {
	r   *bufio.Reader
	buf string
}

func NewFastReader(r io.Reader) *FastReader {
	return &FastReader{
		r: bufio.NewReader(r),
	}
}

func (r *FastReader) advance() {
	for len(r.buf) != 0 && r.buf[0] == ' ' {
		r.buf = r.buf[1:]
	}
	var err error
	for len(r.buf) == 0 && err != io.EOF {
		buf := new(bytes.Buffer)
		for {
			var chunk []byte
			var more bool
			chunk, more, err = r.r.ReadLine()
			buf.Write(chunk)
			if !more {
				break
			}
		}
		r.buf = buf.String()
	}
}

func (r *FastReader) NextLine() string {
	r.advance()
	line := r.buf
	r.buf = ""
	return line
}

func (r *FastReader) NextWord() string {
	r.advance()
	var word string
	wordStart := 0
	for i := 0; i < len(r.buf); i++ {
		b := r.buf[i]
		if b == ' ' {
			if i != wordStart {
				word = r.buf[wordStart:i]
				r.buf = r.buf[i:]
				break
			}
			wordStart = i + 1
		}
	}
	if len(word) == 0 {
		word = r.buf
		r.buf = ""
	}
	return word
}

func (r *FastReader) NextInt() int {
	return parseInt(r.NextWord())
}

func parseInt(word string) int {
	sign := 1
	if word[0] == '-' {
		sign = -1
		word = word[1:]
	}
	result := 0
	for i := 0; i < len(word); i++ {
		result = result*10 + int(word[i]) - '0'
	}
	result *= sign
	return result
}


You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions:  A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj.  The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l].  The suffix of string s of length l (1 ≤ l ≤ |s|) is string s[|s| - l + 1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring.

The single line contains a sequence of characters s1s2...s|s| (1 ≤ |s| ≤ 105) — string s. The string only consists of uppercase English letters.

In the first line, print integer k (0 ≤ k ≤ |s|) — the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li.

package main

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

var reader io.Reader
var scanner *bufio.Scanner

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

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

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

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

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

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

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

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

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

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

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

func kmp(s []byte, p []int) {
	n := len(s)
	p[0] = 0
	p[1] = 0
	for i := 1; i < n; i++ {
		k := p[i]
		for k > 0 && s[i] != s[k] {
			k = p[k]
		}
		if s[i] == s[k] {
			k++
		}
		p[i+1] = k
	}
}

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

	s := NextBytes()
	n := len(s)
	p := make([]int, n+1)
	cnt := make([]int, n+1)
	kmp(s, p)
	stderr(string(s))
	stderr(p)

	for i := 1; i <= n; i++ {
		cnt[i]++
	}
	for i := n; i >= 1; i-- {
		k := p[i]
		if k > 0 {
			cnt[p[i]] += cnt[i]
		}
	}
	stderr(cnt)

	result := make([][2]int, 0)
	for k := n; k > 0; k = p[k] {
		stderr("checkng", k)
		result = append(result, [2]int{k, cnt[k]})
	}

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

	fmt.Fprintln(out, len(result))
	for _, row := range result {
		fmt.Fprintln(out, row[0], row[1])
	}
}

package main

import "fmt"

type Result struct {
	Length int
	Count  int
}

func psfix(p string) {
	var res []Result
	next := make([]int, len(p)+1)
	dp := make([]int, len(p)+1)
	next[0] = -1
	for i, j := 0, -1; i < len(p); {
		if j == -1 || p[i] == p[j] {
			i++
			j++
			next[i] = j
		} else {
			j = next[j]
		}
	}
	for i := len(p); i > 0; i-- {
		dp[i]++
		dp[next[i]] += dp[i]
	}
	res = append(res, Result{len(p), 1})
	for i := next[len(p)]; i != 0; i = next[i] {
		res = append(res, Result{i, dp[i]})
	}
	fmt.Println(len(res))
	for i := len(res) - 1; i >= 0; i-- {
		fmt.Printf("%d %d\n", res[i].Length, res[i].Count)
	}
}

func main() {
	var s string
	fmt.Scan(&s)
	psfix(s)
}

package main

import (
	"bufio"
	"bytes"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"strconv"
	"time"
	"unicode/utf8"
)

// ******************************** CODE STARTS ********************************

var ()

func prefixFunction(s []byte) []int {
	n := len(s)
	p := make([]int, n)

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

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

		p[i] = k
	}

	return p
}

func solve() {
	s := []byte(readString())
	p := prefixFunction(s)
	n := len(s)
	count := make([]int, n)

	for i := n - 1; i >= 0; i-- {
		count[i]++
		if p[i] > 0 {
			count[p[i] - 1] += count[i]
		}
	}

	var L []int
	var C []int
	L = append(L, n)
	C = append(C, 1)

//	logln(s)
//	logln(p)
//	logln(count)
	k := p[n - 1]
	for k > 0 {
		L = append(L, k)
		C = append(C, count[k - 1])
		k = p[k - 1]
	}

	printInt(len(L))
	printLine()
	for i := len(L) - 1; i >= 0; i-- {
		printInt(L[i])
		printString(" ")
		printInt(C[i])
		printLine()
	}
}

// ********************************* CODE ENDS *********************************

// IO.

var (
	scanner *Scanner
	writer  *bufio.Writer
	logger  *log.Logger
)

func main() {
	local := flag.Bool("local", false, "Equals true, if run is local.")
	flag.Parse()

	var (
		input  *os.File
		output *os.File
	)

	if *local {
		startTime := time.Now()
		defer func() {
			println(fmt.Sprintf("Time: %.5fs", time.Since(startTime).Seconds()))
		}()
		input, _ = os.Open("/home/outside/coding/workspace/go/io/input.txt")
		output, _ = os.Create("/home/outside/coding/workspace/go/io/output.txt")
		logger = log.New(output, "log: ", 0)
	} else {
		input = os.Stdin
		output = os.Stdout
		// input, _ = os.Open("")
		// output, _ = os.Create("")
	}
	defer input.Close()
	defer output.Close()

	scanner = NewScanner(input)
	scanner.Split(bufio.ScanWords)

	writer = bufio.NewWriter(output)
	defer writer.Flush()

	solve()
}

// Read.

func readString() string {
	scanner.Scan()
	ans := scanner.Text()
	return ans
}

func readLine() string {
	scanner.Split(bufio.ScanLines)
	defer scanner.Split(bufio.ScanWords)
	return readString()
}

func readInt() int {
	ans, _ := strconv.ParseInt(readString(), 10, 0)
	return int(ans)
}

func readInt64() int64 {
	ans, _ := strconv.ParseInt(readString(), 10, 64)
	return ans
}

func readFloat64() float64 {
	ans, _ := strconv.ParseFloat(readString(), 64)
	return ans
}

// Write.

func printString(value string) {
	writer.WriteString(value)
}

func printLine() {
	printString("\n")
}

func printInt(value int) {
	printString(strconv.FormatInt(int64(value), 10))
}

func printInt64(value int64) {
	printString(strconv.FormatInt(value, 10))
}

func printFLoat64(value float64) {
	printString(strconv.FormatFloat(value, 'f', 20, 64))
}

// Log.

func logln(value ...interface{}) {
	writer.Flush()
	logger.Println(value...)
}
func logf(format string, value ...interface{}) {
	writer.Flush()
	logger.Printf(format, value...)
}

// Tuple

type Tuple struct {
	a, b int
}

func (p Tuple) Equals(key Key) bool {
	return p.a == key.(Tuple).a
}

func (p Tuple) Less(key Key) bool {
	return p.a < key.(Tuple).a
}

type TupleSlice []Tuple

func (p TupleSlice) Len() int {
	return len(p)
}

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

func (p TupleSlice) Swap(j, i int) {
	p[j], p[i] = p[i], p[j]
}

// Min, max, abs.

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

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

func absInt(a int) int {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

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

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

func absInt64(a int64) int64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a < b {
		return a
	} else {
		return b
	}
}

func absFloat64(a float64) float64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

// Set Key interface implementations.

type Int int

func (p Int) Equals(key Key) bool {
	return int(p) == int(key.(Int))
}

func (p Int) Less(key Key) bool {
	return int(p) < int(key.(Int))
}

// Set.

type Key interface {
	Equals(key Key) bool
	Less(key Key) bool
}

type node struct {
	key   Key
	left  *node
	right *node
}

func newNode(key Key) *node {
	return &node{key, nil, nil}
}

type SplayTree struct {
	root *node
	tmp  *node
	len  int
}

func NewSplayTree() *SplayTree {
	return &SplayTree{nil, newNode(nil), 0}
}

func rotateLeft(x, p *node) {
	p.right = x.left
	x.left = p
}

func rotateRight(x, p *node) {
	p.left = x.right
	x.right = p
}

func (p *SplayTree) splay(x *node, key Key) *node {
	if x == nil {
		return nil
	}

	left := p.tmp
	right := p.tmp

	for {
		if key.Less(x.key) {
			y := x.left
			if y == nil {
				break
			}
			if key.Less(y.key) { // zig-zig
				rotateRight(y, x)
				x = y
				if x.left == nil {
					break
				}
			}
			// link right
			right.left = x
			right = x
			// move left
			x = x.left
		} else if x.key.Less(key) {
			y := x.right
			if y == nil {
				break
			}
			if y.key.Less(key) { // zig-zig
				rotateLeft(y, x)
				x = y
				if x.right == nil {
					break
				}
			}
			// link left
			left.right = x
			left = x
			// move right
			x = x.right
		} else {
			break
		}
	}

	left.right = x.left
	right.left = x.right
	x.left = p.tmp.right
	x.right = p.tmp.left

	return x
}

// left <= key < right
func (p *SplayTree) split(key Key) (left, right *node) {
	p.root = p.splay(p.root, key)
	if p.root.key.Equals(key) || p.root.key.Less(key) {
		right := p.root.right
		p.root.right = nil
		return p.root, right
	} else {
		left := p.root.left
		p.root.left = nil
		return left, p.root
	}
}

// keys from left tree must be less then keys from right tree
func (p *SplayTree) join(left, right *node) *node {
	if left == nil {
		return right
	} else if right == nil {
		return left
	}
	left = p.splay(left, right.key)
	left.right = right
	return left
}

type Set interface {
	Len() int
	Insert(key Key) error
	Find(key Key) bool
	Remove(key Key) error
}

func NewSet() Set {
	return Set(NewSplayTree())
}

func (p *SplayTree) Len() int {
	return p.len
}

func (p *SplayTree) Insert(key Key) error {
	if p.root == nil {
		p.root = newNode(key)
		p.len++
	} else {
		p.root = p.splay(p.root, key)
		if p.root.key.Equals(key) {
			return errors.New("Such key already exists")
		} else {
			left, right := p.split(key)
			p.root = newNode(key)
			p.root.left = left
			p.root.right = right
			p.len++
		}
	}
	return nil
}

func (p *SplayTree) Find(key Key) bool {
	if p.root == nil {
		return false
	}
	p.root = p.splay(p.root, key)
	return p.root.key.Equals(key)
}

func (p *SplayTree) Remove(key Key) error {
	p.root = p.splay(p.root, key)
	if p.root == nil || !p.root.key.Equals(key) {
		return errors.New("Such key doesn't exist")
	}
	p.root = p.join(p.split(key))
	return nil
}

// Copied scan.go
// Scanner provides a convenient interface for reading data such as
// a file of newline-delimited lines of text. Successive calls to
// the Scan method will step through the 'tokens' of a file, skipping
// the bytes between the tokens. The specification of a token is
// defined by a split function of type SplitFunc; the default split
// function breaks the input into lines with line termination stripped. Split
// functions are defined in this package for scanning a file into
// lines, bytes, UTF-8-encoded runes, and space-delimited words. The
// client may instead provide a custom split function.
//
// Scanning stops unrecoverably at EOF, the first I/O error, or a token too
// large to fit in the buffer. When a scan stops, the reader may have
// advanced arbitrarily far past the last token. Programs that need more
// control over error handling or large tokens, or must run sequential scans
// on a reader, should use bufio.Reader instead.
//
type Scanner struct {
        r            io.Reader // The reader provided by the client.
        split        SplitFunc // The function to split the tokens.
        maxTokenSize int       // Maximum size of a token; modified by tests.
        token        []byte    // Last token returned by split.
        buf          []byte    // Buffer used as argument to split.
        start        int       // First non-processed byte in buf.
        end          int       // End of data in buf.
        err          error     // Sticky error.
}

// SplitFunc is the signature of the split function used to tokenize the
// input. The arguments are an initial substring of the remaining unprocessed
// data and a flag, atEOF, that reports whether the Reader has no more data
// to give. The return values are the number of bytes to advance the input
// and the next token to return to the user, plus an error, if any. If the
// data does not yet hold a complete token, for instance if it has no newline
// while scanning lines, SplitFunc can return (0, nil, nil) to signal the
// Scanner to read more data into the slice and try again with a longer slice
// starting at the same point in the input.
//
// If the returned error is non-nil, scanning stops and the error
// is returned to the client.
//
// The function is never called with an empty data slice unless atEOF
// is true. If atEOF is true, however, data may be non-empty and,
// as always, holds unprocessed text.
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

// Errors returned by Scanner.
var (
        ErrTooLong         = errors.New("bufio.Scanner: token too long")
        ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
        ErrAdvanceTooFar   = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
)

const (
        // Maximum size used to buffer a token. The actual maximum token size
        // may be smaller as the buffer may need to include, for instance, a newline.
        MaxScanTokenSize = 1 << 30
)

// NewScanner returns a new Scanner to read from r.
// The split function defaults to ScanLines.
func NewScanner(r io.Reader) *Scanner {
        return &Scanner{
                r:            r,
                split:        ScanLines,
                maxTokenSize: MaxScanTokenSize,
                buf:          make([]byte, 4096), // Plausible starting size; needn't be large.
        }
}

// Err returns the first non-EOF error that was encountered by the Scanner.
func (s *Scanner) Err() error {
        if s.err == io.EOF {
                return nil
        }
        return s.err
}

// Bytes returns the most recent token generated by a call to Scan.
// The underlying array may point to data that will be overwritten
// by a subsequent call to Scan. It does no allocation.
func (s *Scanner) Bytes() []byte {
        return s.token
}

// Text returns the most recent token generated by a call to Scan
// as a newly allocated string holding its bytes.
func (s *Scanner) Text() string {
        return string(s.token)
}

// Scan advances the Scanner to the next token, which will then be
// available through the Bytes or Text method. It returns false when the
// scan stops, either by reaching the end of the input or an error.
// After Scan returns false, the Err method will return any error that
// occurred during scanning, except that if it was io.EOF, Err
// will return nil.
func (s *Scanner) Scan() bool {
        // Loop until we have a token.
        for {
                // See if we can get a token with what we already have.
                if s.end > s.start {
                        advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
                        if err != nil {
                                s.setErr(err)
                                return false
                        }
                        if !s.advance(advance) {
                                return false
                        }
                        s.token = token
                        if token != nil {
                                return true
                        }
                }
                // We cannot generate a token with what we are holding.
                // If we've already hit EOF or an I/O error, we are done.
                if s.err != nil {
                        // Shut it down.
                        s.start = 0
                        s.end = 0
                        return false
                }
                // Must read more data.
                // First, shift data to beginning of buffer if there's lots of empty space
                // or space is neded.
                if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
                        copy(s.buf, s.buf[s.start:s.end])
                        s.end -= s.start
                        s.start = 0
                }
                // Is the buffer full? If so, resize.
                if s.end == len(s.buf) {
                        if len(s.buf) >= s.maxTokenSize {
                                s.setErr(ErrTooLong)
                                return false
                        }
                        newSize := len(s.buf) * 2
                        if newSize > s.maxTokenSize {
                                newSize = s.maxTokenSize
                        }
                        newBuf := make([]byte, newSize)
                        copy(newBuf, s.buf[s.start:s.end])
                        s.buf = newBuf
                        s.end -= s.start
                        s.start = 0
                        continue
                }
                // Finally we can read some input. Make sure we don't get stuck with
                // a misbehaving Reader. Officially we don't need to do this, but let's
                // be extra careful: Scanner is for safe, simple jobs.
                for loop := 0; ; {
                        n, err := s.r.Read(s.buf[s.end:len(s.buf)])
                        s.end += n
                        if err != nil {
                                s.setErr(err)
                                break
                        }
                        if n > 0 {
                                break
                        }
                        loop++
                        if loop > 100 {
                                s.setErr(io.ErrNoProgress)
                                break
                        }
                }
        }
}

// advance consumes n bytes of the buffer. It reports whether the advance was legal.
func (s *Scanner) advance(n int) bool {
        if n < 0 {
                s.setErr(ErrNegativeAdvance)
                return false
        }
        if n > s.end-s.start {
                s.setErr(ErrAdvanceTooFar)
                return false
        }
        s.start += n
        return true
}

// setErr records the first error encountered.
func (s *Scanner) setErr(err error) {
        if s.err == nil || s.err == io.EOF {
                s.err = err
        }
}

// Split sets the split function for the Scanner. If called, it must be
// called before Scan. The default split function is ScanLines.
func (s *Scanner) Split(split SplitFunc) {
        s.split = split
}

// Split functions

// ScanBytes is a split function for a Scanner that returns each byte as a token.
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
        if atEOF && len(data) == 0 {
                return 0, nil, nil
        }
        return 1, data[0:1], nil
}

var errorRune = []byte(string(utf8.RuneError))

// ScanRunes is a split function for a Scanner that returns each
// UTF-8-encoded rune as a token. The sequence of runes returned is
// equivalent to that from a range loop over the input as a string, which
// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd".
// Because of the Scan interface, this makes it impossible for the client to
// distinguish correctly encoded replacement runes from encoding errors.
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) {
        if atEOF && len(data) == 0 {
                return 0, nil, nil
        }

        // Fast path 1: ASCII.
        if data[0] < utf8.RuneSelf {
                return 1, data[0:1], nil
        }

        // Fast path 2: Correct UTF-8 decode without error.
        _, width := utf8.DecodeRune(data)
        if width > 1 {
                // It's a valid encoding. Width cannot be one for a correctly encoded
                // non-ASCII rune.
                return width, data[0:width], nil
        }

        // We know it's an error: we have width==1 and implicitly r==utf8.RuneError.
        // Is the error because there wasn't a full rune to be decoded?
        // FullRune distinguishes correctly between erroneous and incomplete encodings.
        if !atEOF && !utf8.FullRune(data) {
                // Incomplete; get more bytes.
                return 0, nil, nil
        }

        // We have a real UTF-8 encoding error. Return a properly encoded error rune
        // but advance only one byte. This matches the behavior of a range loop over
        // an incorrectly encoded string.
        return 1, errorRune, nil
}

// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
        if len(data) > 0 && data[len(data)-1] == '\r' {
                return data[0 : len(data)-1]
        }
        return data
}

// ScanLines is a split function for a Scanner that returns each line of
// text, stripped of any trailing end-of-line marker. The returned line may
// be empty. The end-of-line marker is one optional carriage return followed
// by one mandatory newline. In regular expression notation, it is `\r?\n`.
// The last non-empty line of input will be returned even if it has no
// newline.
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
        if atEOF && len(data) == 0 {
                return 0, nil, nil
        }
        if i := bytes.IndexByte(data, '\n'); i >= 0 {
                // We have a full newline-terminated line.
                return i + 1, dropCR(data[0:i]), nil
        }
        // If we're at EOF, we have a final, non-terminated line. Return it.
        if atEOF {
                return len(data), dropCR(data), nil
        }
        // Request more data.
        return 0, nil, nil
}

// isSpace reports whether the character is a Unicode white space character.
// We avoid dependency on the unicode package, but check validity of the implementation
// in the tests.
func isSpace(r rune) bool {
        if r <= '\u00FF' {
                // Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
                switch r {
                case ' ', '\t', '\n', '\v', '\f', '\r':
                        return true
                case '\u0085', '\u00A0':
                        return true
                }
                return false
        }
        // High-valued ones.
        if '\u2000' <= r && r <= '\u200a' {
                return true
        }
        switch r {
        case '\u1680', '\u180e', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
                return true
        }
        return false
}

// ScanWords is a split function for a Scanner that returns each
// space-separated word of text, with surrounding spaces deleted. It will
// never return an empty string. The definition of space is set by
// unicode.IsSpace.
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
        // Skip leading spaces.
        start := 0
        for width := 0; start < len(data); start += width {
                var r rune
                r, width = utf8.DecodeRune(data[start:])
                if !isSpace(r) {
                        break
                }
        }
        if atEOF && len(data) == 0 {
                return 0, nil, nil
        }
        // Scan until space, marking end of word.
        for width, i := 0, start; i < len(data); i += width {
                var r rune
                r, width = utf8.DecodeRune(data[i:])
                if isSpace(r) {
                        return i + width, data[start:i], nil
                }
        }
        // If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
        if atEOF && len(data) > start {
                return len(data), data[start:], nil
        }
        // Request more data.
        return 0, nil, nil
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF432D(_r io.Reader, _w io.Writer) {
	out := bufio.NewWriter(_w)
	defer out.Flush()
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}

	var s []byte
	Fscan(_r, &s)
	n := len(s)
	z := make([]int, n)
	for i, l, r := 1, 0, 0; i < n; i++ {
		z[i] = max(0, min(z[i-l], r-i+1))
		for i+z[i] < n && s[z[i]] == s[i+z[i]] {
			l, r = i, i+z[i]
			z[i]++
		}
	}
	z[0] = n
	sorted := make([]int, len(z))
	copy(sorted, z)
	sort.Ints(sorted)
	ans := [][2]int{}
	for l := 1; l <= n; l++ {
		if z[n-l] == l {
			i := sort.SearchInts(sorted, l)
			ans = append(ans, [2]int{l, n - i})
		}
	}
	Fprintln(out, len(ans))
	for _, p := range ans {
		Fprintln(out, p[0], p[1])
	}
}

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

package main

import "fmt"

type Result struct {
	Length int
	Count  int
}

func psfix(p string) {
	var res []Result
	next := make([]int, len(p)+1)
	fix := make([]int, len(p)+1)
	next[0] = -1
	for i, j := 0, -1; i < len(p); {
		if j == -1 || p[i] == p[j] {
			i++
			j++
			next[i] = j
			fix[j]++
		} else {
			j = next[j]
		}
	}
	res = append(res, Result{len(p), 1})
	for i := next[len(p)]; i != 0; i = next[i] {
		res = append(res, Result{i, fix[i] + 1})
	}
	fmt.Println(len(res))
	for i := len(res) - 1; i >= 0; i-- {
		fmt.Printf("%d %d\n", res[i].Length, res[i].Count)
	}
}

func main() {
	var s string
	fmt.Scan(&s)
	psfix(s)
}


Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below:  There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows:  Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$.

The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$.

For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall.

NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column.

package main

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

const eof = 0

type any = interface{}

type MyIO struct {
	in  *os.File
	out *bufio.Writer
	_i  int
	_n  int
	buf []byte
}

func NewIO(in *os.File, out *os.File) *MyIO {
	return &MyIO{
		in,
		bufio.NewWriter(out),
		0, 0, make([]byte, 1<<12),
	}
}

func (myio *MyIO) rc() byte {
	if myio._i == myio._n {
		myio._n, _ = myio.in.Read(myio.buf)
		if myio._n == 0 { // EOF
			return eof
		}
		myio._i = 0
	}
	b := myio.buf[myio._i]
	myio._i++
	return b
}

func (myio *MyIO) ReadInt() (x int) {
	rc := myio.rc
	b := rc()
	neg := false

	for ; '0' > b || b > '9'; b = rc() {
		if b == eof {
			return
		}
		if b == '-' {
			neg = true
		}
	}
	for ; '0' <= b && b <= '9'; b = rc() {
		x = x*10 + int(b&15)
	}
	if neg {
		return -x
	}
	return x
}

func (myio *MyIO) ReadBytes() (s []byte) {
	rc := myio.rc
	b := rc()
	for ; b <= ' '; b = rc() {
	}
	for ; b > ' '; b = rc() {
		s = append(s, b)
	}
	return
}

func (myio *MyIO) ReadStr() (s string) {
	return string(myio.ReadBytes())
}

func (myio *MyIO) Flush() {
	myio.out.Flush()
}

func (myio *MyIO) Printf(format string, a ...any) (n int, err error) {
	return fmt.Fprintf(myio.out, format, a...)
}

func (myio *MyIO) Println(a ...any) (n int, err error) {
	return fmt.Fprintln(myio.out, a...)
}

func (myio *MyIO) Print(a ...any) (n int, err error) {
	return fmt.Fprint(myio.out, a...)
}

func main() {
	myio := NewIO(os.Stdin, os.Stdout)
	defer myio.Flush()

	t := myio.ReadInt()
	sol := func() {
		n := myio.ReadInt()
		m := myio.ReadInt()
		s := myio.ReadBytes()
		sum := make([]int, m*n+1)
		rc := make([]int, n*m)
		cc := make([]int, n*m)
		sum[0] = 0
		for i, t := range s {
			if t == '1' {
				sum[i+1] = sum[i] + 1
			} else {
				sum[i+1] = sum[i]
			}
		}
		// count rows
		// first in column j
		for j := m - 1; j >= 0; j-- {
			// first in row i
			tmpr := 0
			if sum[j+1]-sum[0] > 0 {
				tmpr = 1
			}
			rc[j] = tmpr
			for i := 1; i < n; i++ {
				if sum[j+i*m+1]-sum[j+i*m-m+1] > 0 {
					tmpr++
				}
				rc[j+i*m] = tmpr
			}
		}
		// myio.Println(rc)
		// count columns
		tmpc := make([]int, m)
		res := 0
		for k, t := range s {
			j := k % m
			if t == '1' {
				if tmpc[j] == 0 {
					res++
				}
				// else if tmpc[j] == 1 {
				// 	res--
				// }
				tmpc[j]++
			}
			cc[k] = res
		}
		// myio.Println(cc)

		for i := 0; i < m*n; i++ {
			myio.Printf("%d ", rc[i]+cc[i])
		}
		myio.Println()
	}
	for ; t > 0; t-- {
		sol()
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func vecintstring(a []int) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.Itoa(a) }; return strings.Join(astr," ") }
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
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N,M := gi(),gi(); S := gs()
		NM := N*M
		ans := make([]int,NM)
		colflag := make([]bool,M); goodcol := 0
		rowsum := make([]int,M); numgood := 0; i:=0
		for j:=0;j<N;j++ {
			for k:=0;k<M;k++ {
				if j == 0 {
					if S[i] == '1' { colflag[k] = true; goodcol++ }
					if S[i] == '1' { numgood++ }
					if numgood > 0 { rowsum[k]++ }
					ans[i] = goodcol + rowsum[k]
				} else {
					if S[i] == '1' && !colflag[k] { colflag[k] = true; goodcol++}
					if S[i] == '1' { numgood++ }
					if S[i-M] == '1' { numgood--}
					if numgood > 0 { rowsum[k]++ }
					ans[i] = goodcol + rowsum[k]
				}
			i++
			}
		}
		fmt.Fprintln(wrtr,vecintstring(ans))
	}
}

package main

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

func solve(in io.Reader, out io.Writer) {
	var n int
	var m int
	var s string
	Fscan(in, &n, &m, &s)

	rsCnt := make([]int, m)
	cs := make([]bool, m)
	csCnt := 0

	lastm := 0
	for r := 0; r < n; r++ {
		for c := 0; c < m; c++ {
			if s[r*m+c] == '1' {
				lastm++
				if !cs[c] {
					cs[c] = true
					csCnt++
				}
			}
			if r*m+c >= m && s[r*m+c-m] == '1' {
				lastm--
			}

			if lastm > 0 {
				rsCnt[c]++
			}

			Fprint(out, rsCnt[c]+csCnt, " ")
		}
	}
	Fprintln(out)
}

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


Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into $$$n$$$ sub-tracks. You are given an array $$$a$$$ where $$$a_i$$$ represents the number of traffic cars in the $$$i$$$-th sub-track. You define the inconvenience of the track as $$$\sum\limits_{i=1}^{n} \sum\limits_{j=i+1}^{n} \lvert a_i-a_j\rvert$$$, where $$$|x|$$$ is the absolute value of $$$x$$$. You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track.Find the minimum inconvenience you can achieve.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0\leq a_i\leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print a single line containing a single integer: the minimum inconvenience you can achieve by applying the given operation any (possibly zero) number of times.

NoteFor the first test case, you can move a car from the $$$3$$$-rd sub-track to the $$$1$$$-st sub-track to obtain $$$0$$$ inconvenience.For the second test case, moving any car won't decrease the inconvenience of the track.

package main

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

func main() {
	in := bufio.NewReaderSize(os.Stdin, 10000)

	var testCount int
	var n, r int64
	fmt.Fscan(in, &testCount)
	list := make([]int64, 0, n)

	for i := 0; i < testCount; i++ {
		fmt.Fscan(in, &n)

		list = list[:0]
		for k := int64(0); k < n; k++ {
			fmt.Fscan(in, &r)
			list = append(list, r)
		}

		var sum int64
		for _, k := range list {
			sum += k
		}
		dif := sum % n

		fmt.Println((int64(len(list)) - dif) * dif)
	}
}

package main

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

func Task(data []int64) int64 {
	var sum int64 = 0
	for _, v := range data {
		sum += v
	}

	n := int64(len(data))
	avg := sum / n
	c := n*avg + n - sum

	return c * (n - c)
}

func main() {

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

	t := 0
	fmt.Fscan(reader, &t)
	for i := 0; i < t; i++ {
		n := 0
		fmt.Fscan(reader, &n)
		data := make([]int64, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(reader, &data[j])
		}
		ret := Task(data)
		fmt.Fprintln(writer, ret)
	}

}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t      int
	n      int64
)

func solve(n, s int64) int64 {
	return (n - s%n) * (s % n)
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		var s, x int64
		for i := int64(0); i < n; i++ {
			fmt.Fscan(reader, &x)
			s += x
		}
		fmt.Println(solve(n, s))
	}
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t, n   int
)

func solve(n int, a []int) int64 {
	s := int64(0)
	for _, x := range a {
		s += int64(x)
	}
	return (int64(n) - s%int64(n)) * (s % int64(n))
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i])
		}
		fmt.Println(solve(n, a))
	}
}

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

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func main() {
	defer writer.Flush()
	var t int
	fmt.Fscan(reader, &t)
	for i := 0; i < t; i++ {
		solve()
	}
}

func solve() {
	var n int64
	var temp int64
	fmt.Fscan(reader, &n)
    s := int64(0)
	for i := 0 ; i < int(n); i++{
		fmt.Fscan(reader, &temp)
		s += temp
	}
	l := s / int64(n)
	fmt.Fprintln(writer, (s -l * n ) * (n - s + l * n))
}

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

func min(nums ...int64) int64 {
	l := len(nums)
	mn := nums[0]
	for i := 0; i < l; i++ {
		if nums[i] < mn {
			mn = nums[i]
		}
	}
	return mn
}

// 1543B. Customising the Track
package main

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

func main() {
	var T int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &T)
	for t := 1; t <= T; t++ {
		var n, curr, rem int64
		fmt.Fscan(reader, &n)
		for i := int64(0); i < n; i++ {
			fmt.Fscan(reader, &curr)
			rem += curr
			rem %= n
		}
		fmt.Println(rem * (n - rem))
	}
}

package main

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

/*

 */

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	var t = 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		var n int64
		scanf("%d\n", &n)

		a := make([]int64, n)

		sum := int64(0)

		for i := range a {
			scanf("%d", &a[i])
			sum += a[i]
		}
		scanf("\n")

		rem := sum % n

		ans := rem * (n - rem)

		fmt.Fprintln(writer, ans)
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div != 0 {
		quot++
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	minimum := nums[0]
	for _, num := range nums {
		if num < minimum {
			minimum = num
		}
	}
	return minimum
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	maximum := nums[0]
	for _, num := range nums {
		if num > maximum {
			maximum = num
		}
	}
	return maximum
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := 5; i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

package main

import ."fmt"
//import "sort"
import "bufio"
import "os"
//import ."math"

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func main() {
    defer writer.Flush()

    var t int
    Fscan(reader, &t)
    for i := 0; i < t; i++ {
        solve()
    }
}
func solve(){
    var n int64
    Fscan(reader, &n)
    a := make([]int64, n)
    for i := int64(0); i < n; i++ {
        Fscan(reader, &a[i])
    }
    s := sum(a)
	mod := s % n
	Fprintln(writer, (n - mod) * mod)
}
func sum(a []int64) int64{
    ans := int64(0)
    for _, i := range a {
        ans += i
    }
    return ans
}
func abs(x int64) int64 {
    if x < 0 {
        return 0 - x
    }
    return x
}
func min(x, y int64) int64 {
    if x < y {
        return x
    }
    return y
}

package main

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

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

	var t int
	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(r, &n)

		a := make([]int, n)

		for k := 0; k < n; k++ {
			fmt.Fscan(r, &a[k])
		}

		solve(a, n)
	}
}

func solve(a []int, n int) {

	//1 4 7 3 2
	//

	var s int64
	var ans int64

	for i := 0; i < n; i++ {
		s += int64(a[i])
	}

	if s < int64(n) {
		ans = s * (int64(n) - s)

	} else {
		//d := s/int64(n)

		r := s % int64(n)

		if r == 0 {
			ans = 0
		} else {
			ans = r * (int64(n) - r)

		}
	}

	fmt.Println(ans)
}

package main

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

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()
		a := sint64s(n)
		printf("%d\n", sol(n, a))
	}
}

func sol(n int64, a []int64) int64 {
	s := sum(a)
	mod := s % n
	return (n - mod) * mod
}

func sum(a []int64) int64 {
	ret := int64(0)
	for _, i := range a {
		ret += i
	}
	return ret
}

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

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func main() {
	defer writer.Flush()
	var t int
	fmt.Fscan(reader, &t)
	for i := 0; i < t; i++ {
		solve()
	}
}

func solve() {
	var n int
	var temp int
	fmt.Fscan(reader, &n)
    s := 0
	for i := 0; i < n; i++{
		fmt.Fscan(reader, &temp)
		s += temp
	}
	l := s / n
	fmt.Fprintln(writer, (s -l * n ) * (n - s + l * n))
}

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

func min(nums ...int64) int64 {
	l := len(nums)
	mn := nums[0]
	for i := 0; i < l; i++ {
		if nums[i] < mn {
			mn = nums[i]
		}
	}
	return mn
}