You are preparing for an exam on scheduling theory. The exam will last for exactly T milliseconds and will consist of n problems. You can either solve problem i in exactly ti milliseconds or ignore it and spend no time. You don't need time to rest after solving a problem, either.Unfortunately, your teacher considers some of the problems too easy for you. Thus, he assigned an integer ai to every problem i meaning that the problem i can bring you a point to the final score only in case you have solved no more than ai problems overall (including problem i).Formally, suppose you solve problems p1, p2, ..., pk during the exam. Then, your final score s will be equal to the number of values of j between 1 and k such that k ≤ apj.You have guessed that the real first problem of the exam is already in front of you. Therefore, you want to choose a set of problems to solve during the exam maximizing your final score in advance. Don't forget that the exam is limited in time, and you must have enough time to solve all chosen problems. If there exist different sets of problems leading to the maximum final score, any of them will do.

The first line contains two integers n and T (1 ≤ n ≤ 2·105; 1 ≤ T ≤ 109) — the number of problems in the exam and the length of the exam in milliseconds, respectively. Each of the next n lines contains two integers ai and ti (1 ≤ ai ≤ n; 1 ≤ ti ≤ 104). The problems are numbered from 1 to n.

In the first line, output a single integer s — your maximum possible final score. In the second line, output a single integer k (0 ≤ k ≤ n) — the number of problems you should solve. In the third line, output k distinct integers p1, p2, ..., pk (1 ≤ pi ≤ n) — the indexes of problems you should solve, in any order. If there are several optimal sets of problems, you may output any of them.

NoteIn the first example, you should solve problems 3, 1, and 4. In this case you'll spend 80 + 100 + 90 = 270 milliseconds, falling within the length of the exam, 300 milliseconds (and even leaving yourself 30 milliseconds to have a rest). Problems 3 and 1 will bring you a point each, while problem 4 won't. You'll score two points.In the second example, the length of the exam is catastrophically not enough to solve even a single problem.In the third example, you have just enough time to solve both problems in 42 + 58 = 100 milliseconds and hand your solutions to the teacher with a smile.

package main

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

var in = bufio.NewScanner(os.Stdin)

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

type problem struct {
	a, t, index int
}

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

	n := readInt()
	T := readInt()
	pr := make([]problem, n)
	for i := range pr {
		pr[i].a = readInt()
		pr[i].t = readInt()
		pr[i].index = i + 1
	}
	sort.Slice(pr, func(i, j int) bool { return pr[i].t < pr[j].t })
	if pr[0].t > T {
		fmt.Println(0)
		fmt.Println(0)
		return
	}
	ans := sort.Search(n+1, func(solved int) bool {
		if solved == 0 {
			return false
		}
		cur := 0
		timeSpent := 0
		for i := range pr {
			if timeSpent+pr[i].t > T {
				break
			}
			if solved <= pr[i].a {
				cur++
				timeSpent += pr[i].t
			}
		}
		return cur < solved
	}) - 1
	fmt.Fprintln(out, ans)
	fmt.Fprintln(out, ans)
	printed := 0
	for i := range pr {
		if ans <= pr[i].a {
			printed++
			if printed == ans {
				fmt.Fprintln(out, pr[i].index)
				break
			} else {
				fmt.Fprint(out, pr[i].index, " ")
			}
		}
	}
}

package main

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

type data struct {
	point int
	time  int
	idx   int
}
type datas []data

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

func main() {
	var n, T int
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	var a datas
	fmt.Sscanf(scanner.Text(), "%d %d\n", &n, &T)
	a = make(datas, n)
	for i := 0; i < n; i++ {
		a[i].idx = i
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d %d\n", &a[i].point, &a[i].time)
	}

	sort.Sort(a)

	lo, hi := 1, n
	for lo <= hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}

	fmt.Println(hi)
	cnt, tTotal := 0, 0
	fmt.Println(hi)
	for i := 0; i < n && cnt < hi; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
			cnt++
		}
	}
	fmt.Println()
}

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol913D(reader io.Reader, writer io.Writer) {
	type pair struct {
		a, t, idx int
	}

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

	var n, t int
	Fscan(in, &n, &t)
	arr := make([]pair, n)
	for i := range arr {
		Fscan(in, &arr[i].a, &arr[i].t)
		arr[i].idx = i + 1
	}

	sort.Slice(arr, func(i, j int) bool { return arr[i].t < arr[j].t })
	f := func(target int) bool {
		if target == 0 {
			return !true
		}
		score, spent := 0, 0
		for _, p := range arr {
			if p.a >= target {
				if spent+p.t > t {
					break
				}
				spent += p.t
				score++
				if score == target {
					break
				}
			}
		}
		return !(score == target)
	}
	ans := sort.Search(n+1, f) - 1
	Fprintln(out, ans)
	Fprintln(out, ans)
	if ans == 0 {
		Fprintln(out)
		return
	}
	score := 0
	for _, p := range arr {
		if p.a >= ans {
			Fprint(out, p.idx, " ")
			score++
			if score == ans {
				break
			}
		}
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol913D(reader io.Reader, writer io.Writer) {
	type pair struct {
		a, t, idx int
	}

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

	var n, t int
	Fscan(in, &n, &t)
	arr := make([]pair, n)
	for i := range arr {
		Fscan(in, &arr[i].a, &arr[i].t)
		arr[i].idx = i + 1
	}

	sort.Slice(arr, func(i, j int) bool { return arr[i].t < arr[j].t })
	var idxAns []interface{}
	f := func(target int) bool {
		if target == 0 {
			return !true
		}
		idxAns = []interface{}{}
		spent := 0
		for _, p := range arr {
			if p.a >= target {
				if spent+p.t > t {
					break
				}
				spent += p.t
				idxAns = append(idxAns, p.idx)
				if len(idxAns) == target {
					break
				}
			}
		}
		return !(len(idxAns) == target)
	}
	ans := sort.Search(n+1, f) - 1
	f(ans)
	Fprintln(out, ans)
	Fprintln(out, ans)
	Fprintln(out, idxAns...)
}

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

package main

import (
	"fmt"
	"sort"
)

type data struct {
	point int
	time  int
	idx   int
}

type datas []data

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

func main() {
	var n, T int
	fmt.Scanf("%d %d", &n, &T)
	a := make(datas, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d %d", &a[i].point, &a[i].time)
		a[i].idx = i
	}
	sort.Sort(a)

	lo, hi := 1, n
	for lo < hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}
	fmt.Println(hi)
	ans, tTotal := 0, 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			ans++
		}
	}
	fmt.Println(ans)
	tTotal = 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
		}
	}
}

package main

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

type data struct {
	point int
	time  int
	idx   int
}
type datas []data

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

func main() {
	var n, T int
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	var a datas
	fmt.Sscanf(scanner.Text(), "%d %d\n", &n, &T)
	a = make(datas, n)
	for i := 0; i < n; i++ {
		a[i].idx = i
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d %d\n", &a[i].point, &a[i].time)
	}

	sort.Sort(a)

	lo, hi := 1, n
	for lo <= hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}

	fmt.Println(hi)
	ans, tTotal := 0, 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			ans++
		}
	}
	fmt.Println(ans)
	tTotal = 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
		}
	}
	fmt.Println()
}

package main

import (
	"fmt"
	"math/rand"
)

type data struct {
	point int
	time  int
	idx   int
}

func qsort(a []data) []data {
	if len(a) < 2 {
		return a
	}

	left, right := 0, len(a)-1

	// Pick a pivot
	pivotIndex := rand.Int() % len(a)

	// Move the pivot to the right
	a[pivotIndex], a[right] = a[right], a[pivotIndex]

	// Pile elements smaller than the pivot on the left
	for i := range a {
		if a[i].time < a[right].time {
			a[i], a[left] = a[left], a[i]
			left++
		}
	}

	// Place the pivot after the last smaller element
	a[left], a[right] = a[right], a[left]

	// Go down the rabbit hole
	qsort(a[:left])
	qsort(a[left+1:])

	return a
}

func main() {
	var n, T int
	fmt.Scanf("%d %d\n", &n, &T)
	var a []data
	for i := 0; i < n; i++ {
		inp := data{}
		inp.idx = i
		fmt.Scanf("%d %d\n", &inp.point, &inp.time)
		a = append(a, inp)
		if i > 10000 {
			return
		}
	}
	qsort(a)

	lo, hi := 1, n
	for lo <= hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}

	fmt.Println(hi)
	ans, tTotal := 0, 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			ans++
		}
	}
	fmt.Println(ans)
	tTotal = 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
		}
	}
	fmt.Println()
}

package main

import (
	"fmt"
	"math/rand"
)

type data struct {
	point int
	time  int
	idx   int
}

func qsort(a []data) []data {
	if len(a) < 2 {
		return a
	}

	left, right := 0, len(a)-1

	// Pick a pivot
	pivotIndex := rand.Int() % len(a)

	// Move the pivot to the right
	a[pivotIndex], a[right] = a[right], a[pivotIndex]

	// Pile elements smaller than the pivot on the left
	for i := range a {
		if a[i].time < a[right].time {
			a[i], a[left] = a[left], a[i]
			left++
		}
	}

	// Place the pivot after the last smaller element
	a[left], a[right] = a[right], a[left]

	// Go down the rabbit hole
	qsort(a[:left])
	qsort(a[left+1:])

	return a
}

func main() {
	var n, T int
	fmt.Scanln(&n, &T)
	var a []data
	a = make([]data, n)
	for i := 0; i < n; i++ {
		a[i].idx = i
		fmt.Scanln(&a[i].point, &a[i].time)
		if i > 10000 {
			return
		}
	}
	qsort(a)

	lo, hi := 1, n
	for lo <= hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}

	fmt.Println(hi)
	ans, tTotal := 0, 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			ans++
		}
	}
	fmt.Println(ans)
	tTotal = 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
		}
	}
	fmt.Println()
}

package main

import (
	"fmt"
	"math/rand"
)

type data struct {
	point int
	time  int
	idx   int
}

func qsort(a []data) []data {
	if len(a) < 2 {
		return a
	}

	left, right := 0, len(a)-1

	// Pick a pivot
	pivotIndex := rand.Int() % len(a)

	// Move the pivot to the right
	a[pivotIndex], a[right] = a[right], a[pivotIndex]

	// Pile elements smaller than the pivot on the left
	for i := range a {
		if a[i].time < a[right].time {
			a[i], a[left] = a[left], a[i]
			left++
		}
	}

	// Place the pivot after the last smaller element
	a[left], a[right] = a[right], a[left]

	// Go down the rabbit hole
	qsort(a[:left])
	qsort(a[left+1:])

	return a
}

func main() {
	var n, T int
	fmt.Scanln(&n, &T)
	var a []data
	for i := 0; i < n; i++ {
		inp := data{}
		inp.idx = i
		fmt.Scanln(&inp.point, &inp.time)
		a = append(a, inp)
		if i > 10000 {
			return
		}
	}
	qsort(a)

	lo, hi := 1, n
	for lo <= hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}

	fmt.Println(hi)
	ans, tTotal := 0, 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			ans++
		}
	}
	fmt.Println(ans)
	tTotal = 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
		}
	}
	fmt.Println()
}

package main

import (
	"fmt"
	"math/rand"
)

type data struct {
	point int
	time  int
	idx   int
}

func qsort(a []data) []data {
	if len(a) < 2 {
		return a
	}

	left, right := 0, len(a)-1

	// Pick a pivot
	pivotIndex := rand.Int() % len(a)

	// Move the pivot to the right
	a[pivotIndex], a[right] = a[right], a[pivotIndex]

	// Pile elements smaller than the pivot on the left
	for i := range a {
		if a[i].time < a[right].time {
			a[i], a[left] = a[left], a[i]
			left++
		}
	}

	// Place the pivot after the last smaller element
	a[left], a[right] = a[right], a[left]

	// Go down the rabbit hole
	qsort(a[:left])
	qsort(a[left+1:])

	return a
}

func main() {
	var n, T int
	fmt.Scanf("%d %d\n", &n, &T)
	var a []data
	inp := data{}
	for i := 0; i < n; i++ {
		inp.idx = i
		fmt.Scanf("%d %d\n", &inp.point, &inp.time)
		a = append(a, inp)
		if i > 10000 {
			return
		}
	}
	qsort(a)

	lo, hi := 1, n
	for lo <= hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}

	fmt.Println(hi)
	ans, tTotal := 0, 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			ans++
		}
	}
	fmt.Println(ans)
	tTotal = 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
		}
	}
	fmt.Println()
}

package main

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

type data struct {
	point int
	time  int
	idx   int
}

func qsort(a []data) []data {
	if len(a) < 2 {
		return a
	}

	left, right := 0, len(a)-1

	// Pick a pivot
	pivotIndex := rand.Int() % len(a)

	// Move the pivot to the right
	a[pivotIndex], a[right] = a[right], a[pivotIndex]

	// Pile elements smaller than the pivot on the left
	for i := range a {
		if a[i].time < a[right].time {
			a[i], a[left] = a[left], a[i]
			left++
		}
	}

	// Place the pivot after the last smaller element
	a[left], a[right] = a[right], a[left]

	// Go down the rabbit hole
	qsort(a[:left])
	qsort(a[left+1:])

	return a
}

func main() {
	var n, T int
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%d %d\n", &n, &T)
	var a []data
	a = make([]data, n)
	for i := 0; i < n; i++ {
		a[i].idx = i
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d %d\n", &a[i].point, &a[i].time)
		if i > 10000 {
			return
		}
	}
	qsort(a)

	lo, hi := 1, n
	for lo <= hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}

	fmt.Println(hi)
	ans, tTotal := 0, 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			ans++
		}
	}
	fmt.Println(ans)
	tTotal = 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
		}
	}
	fmt.Println()
}

package main

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

type data struct {
	point int
	time  int
	idx   int
}
type datas []data

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

func main() {
	var n, T int
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	var a datas
	fmt.Sscanf(scanner.Text(), "%d %d\n", &n, &T)
	a = make(datas, n)
	for i := 0; i < n; i++ {
		a[i].idx = i
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d %d\n", &a[i].point, &a[i].time)
	}

	sort.Sort(a)

	if n > 10000 {
		return
	}
	lo, hi := 1, n
	for lo <= hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}

	fmt.Println(hi)
	ans, tTotal := 0, 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			ans++
		}
	}
	fmt.Println(ans)
	tTotal = 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
		}
	}
	fmt.Println()
}

package main

import (
	"fmt"
	"sort"
)

type data struct {
	point int
	time  int
	idx   int
}

type datas []data

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

func main() {
	var n, T int
	fmt.Scanf("%d %d", &n, &T)
	var a datas
	for i := 0; i < n; i++ {
		inp := data{}
		inp.idx = i
		fmt.Scanf("%d %d", &inp.point, &inp.time)
		a = append(a, inp)
	}
	sort.Sort(a)

	lo, hi := 1, n
	for lo < hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}

	fmt.Println(hi)
	ans, tTotal := 0, 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			ans++
		}
	}
	fmt.Println(ans)
	tTotal = 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
		}
	}
	fmt.Println()
}

package main

import (
	"fmt"
	"sort"
)

type data struct {
	point int
	time  int
	idx   int
}

type datas []data

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

func main() {
	var n, T int
	fmt.Scanf("%d %d", &n, &T)
	a := make(datas, n)
	for i := 0; i < n; i++ {
		a[i].idx = i
		fmt.Scanf("%d %d", &a[i].point, &a[i].time)
	}
	sort.Sort(a)

	lo, hi := 1, n
	for lo < hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}
	fmt.Println(hi)
	ans, tTotal := 0, 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			ans++
		}
	}
	fmt.Println(ans)
	tTotal = 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
		}
	}
}

package main

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

type data struct {
	point int
	time  int
	idx   int
}

func qsort(a []data) []data {
	if len(a) < 2 {
		return a
	}

	left, right := 0, len(a)-1

	// Pick a pivot
	pivotIndex := rand.Int() % len(a)

	// Move the pivot to the right
	a[pivotIndex], a[right] = a[right], a[pivotIndex]

	// Pile elements smaller than the pivot on the left
	for i := range a {
		if a[i].time < a[right].time {
			a[i], a[left] = a[left], a[i]
			left++
		}
	}

	// Place the pivot after the last smaller element
	a[left], a[right] = a[right], a[left]

	// Go down the rabbit hole
	qsort(a[:left])
	qsort(a[left+1:])

	return a
}

func main() {
	var n, T int
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%d %d\n", &n, &T)
	var a []data
	a = make([]data, n)
	for i := 0; i < n; i++ {
		a[i].idx = i
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d %d\n", &a[i].point, &a[i].time)
	}
	if n > 100000 {
		return
	}
	qsort(a)

	lo, hi := 1, n
	for lo <= hi {
		mi, cnt, tTotal := (lo+hi)/2, 0, 0
		for i := 0; i < n; i++ {
			if a[i].point >= mi && tTotal+a[i].time <= T {
				tTotal += a[i].time
				cnt++
			}
		}
		if cnt < mi {
			hi = mi - 1
		} else {
			lo = mi + 1
		}
	}

	fmt.Println(hi)
	ans, tTotal := 0, 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			ans++
		}
	}
	fmt.Println(ans)
	tTotal = 0
	for i := 0; i < n; i++ {
		if a[i].point >= hi && tTotal+a[i].time <= T {
			tTotal += a[i].time
			fmt.Printf("%d ", a[i].idx+1)
		}
	}
	fmt.Println()
}

package main

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

// github.com/EndlessCheng/codeforces-go
func Sol913D(reader io.Reader, writer io.Writer) {
	type pair struct {
		a, t, idx int
	}

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

	var n, t int
	Fscan(in, &n, &t)
	arr := make([]pair, n)
	for i := range arr {
		Fscan(in, &arr[i].a, &arr[i].t)
		arr[i].idx = i + 1
	}

	sort.Slice(arr, func(i, j int) bool { return arr[i].t < arr[j].t })
	var idxAns []interface{}
	f := func(target int) bool {
		if target == 0 {
			return !true
		}
		idxAns = []interface{}{}
		spent := 0
		for _, p := range arr {
			if p.a >= target {
				if spent+p.t > t {
					break
				}
				idxAns = append(idxAns, p.idx)
				spent += p.t
			}
		}
		return !(len(idxAns) >= target)
	}
	ans := sort.Search(n+1, f) - 1
	Fprintln(out, ans)
	Fprintln(out, len(idxAns))
	Fprintln(out, idxAns...)
}

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


Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is the correct formal description of the homework assignment:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c".

For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a substring.

9 10
abcabcabc
1 a
1 b
2 c
3 a
4 b
5 c
8 a
9 b
1 c
4 a

NoteLet's consider the state of the string after each query:   $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed.

package main

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

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

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

	var s string
	fmt.Fscan(in, &s)

	chars := make([]rune, n)
	for i := 0; i < n; i++ {
		chars[i] = rune(s[i])
	}

	var total int
	for i := 0; i < n-2; i++ {
		if chars[i] == 'a' && chars[i+1] == 'b' && chars[i+2] == 'c' {
			total++
			i += 2
		}
	}

	for i := 0; i < q; i++ {
		var pos int
		var c string
		fmt.Fscan(in, &pos, &c)

		pos--
		if chars[pos] == rune(c[0]) {
			fmt.Fprintln(out, total)
			continue
		}

		l, r := 0, n
		if pos-2 > l {
			l = pos - 2
		}

		if pos+3 < r {
			r = pos + 3
		}

		orig := string(chars[l:r])
		chars[pos] = rune(c[0])
		s2 := string(chars[l:r])

		if strings.Contains(orig, "abc") && !strings.Contains(s2, "abc") {
			total--
		} else if !strings.Contains(orig, "abc") && strings.Contains(s2, "abc") {
			total++
		}

		fmt.Fprintln(out, total)
	}
}

package main

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

func main() {

	scanner := bufio.NewScanner(os.Stdin)

	var n int
	var q int
	fmt.Scanln(&n, &q)

	var s string
	fmt.Scanln(&s)

	abcs := 0
	for i := 3; i <= n; i++ {
		if s[i-3:i] == "abc" {
			abcs++
		}
	}

	var split []string

	for ; q > 0; q-- {
		scanner.Scan()
		split = strings.Split(scanner.Text(), " ")
		i, _ := strconv.Atoi(split[0])
		i--
		c := split[1][0]
		if i > 1 && s[i-2:i+1] == "abc" {
			abcs--
		}
		if i > 0 && i+1 < n && s[i-1:i+2] == "abc" {
			abcs--
		}
		if i+2 < n && s[i:i+3] == "abc" {
			abcs--
		}

		s = s[:i] + string(c) + s[i+1:]
		if c == 'c' && i > 1 && s[i-2:i] == "ab" {
			abcs++
		}
		if c == 'b' && i > 0 && i+1 < n && s[i-1:i+2] == "abc" {
			abcs++
		}
		if c == 'a' && i+2 < n && s[i:i+3] == "abc" {
			abcs++
		}

		fmt.Println(abcs)
	}

}

package main

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

var (
	input = bufio.NewReader(os.Stdin)
	output = bufio.NewWriter(os.Stdout)
)

func assert(test bool) {
    if !test {panic("assert!")}
}

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

func main() {
    defer output.Flush()
    solve()
    return
	var t int64
	fmt.Fscan(input, &t)
    for t > 0 {
        t--
        solve()
    }
}

func solve() {
    var n, q int
    fmt.Fscan(input, &n, &q)
    var s string
    fmt.Fscan(input, &s)
    cnt := 0
    for i := 0; i + 3 <= len(s); i++ {
        if s[i:i+3] == "abc" { cnt++ }
    }

    a := []byte(s)
    good := func(p int) bool {
        if p - 2 >= 0 && p + 1 <= len(a) && string(a[p - 2:p + 1]) == "abc" { return true}
        if p - 1 >= 0 && p + 2 <= len(a) && string(a[p - 1:p + 2]) == "abc" { return true}
        if p >= 0 && p + 3 <= len(a) && string(a[p:p + 3]) == "abc" { return true}
        return false
    }

    for q > 0 {
        q--
        var pos int
        var ss string
        fmt.Fscan(input, &pos, &ss)
        pos--
        c := ss[0]

        if good(pos) { cnt-- }
        a[pos] = c
        if good(pos) { cnt++ }

        fmt.Fprintln(output, cnt)
    }
}

package main

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

/*
9 6
aabcabcbc
1 a
2 a
2 c
2 a
7 b
7 a
---
2
2
1
2
1
2
*/

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

	bld := strings.Builder{}

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

	for ; t > 0; t-- {
		var n, q int
		var st string
		scanf("%d %d\n%s\n", &n, &q, &st)

		s := []byte(st)

		abcs := make(map[int]bool)

		for j := 0; j < n-2; j++ {
			if s[j] == 'a' && s[j+1] == 'b' && s[j+2] == 'c' {
				abcs[j] = true
			}
		}

		for k := 0; k < q; k++ {
			var i int
			var s2 string
			scanf("%d %s\n", &i, &s2)
			i--

			ch := s2[0]

			s[i] = ch

			for j := max(0, i-2); j < min(n-2, i+1); j++ {
				if s[j] == 'a' && s[j+1] == 'b' && s[j+2] == 'c' {
					abcs[j] = true
				} else {
					delete(abcs, j)
				}
			}

			fmt.Fprintln(&bld, len(abcs))
		}
	}

	printf("%s", bld.String())
}

const maxUint = ^uint(0)

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

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

//goland:noinspection GoUnusedType
type pair struct {
	fst int
	snd int
}

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

//goland:noinspection GoUnusedFunction
func printf(f string, a ...interface{}) {
	if _, err := fmt.Fprintf(writer, f, a...); err != nil {
		panic(err)
	}
}

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

//goland:noinspection GoUnusedFunction
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

//goland:noinspection GoUnusedFunction
func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

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

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

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

	for i := 5; i*i <= n; i += 6 {
		if n%i == 0 || n%(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, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 2
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	lenNum := int(math.Log10(float64(num))) + 1
	if 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"
	"bufio"
	"os"
)

var (
	input = bufio.NewReader(os.Stdin)
	output = bufio.NewWriter(os.Stdout)
)

func assert(test bool) {
    if !test {panic("assert!")}
}

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

func main() {
    defer output.Flush()
    solve()
    return
	var t int64
	fmt.Fscan(input, &t)
    for t > 0 {
        t--
        solve()
    }
}

func solve() {
    var n, q int
    fmt.Fscan(input, &n, &q)
    var s string
    fmt.Fscan(input, &s)
    cnt := 0
    for i := 0; i < len(s); i++ {
        if i + 3 <= len(s) && s[i:i+3] == "abc" { cnt++ }
    }

    a := []byte(s)
    good := func(p int) bool {
        if p - 2 >= 0 && p + 1 <= len(a) && string(a[p - 2:p + 1]) == "abc" { return true}
        if p - 1 >= 0 && p + 2 <= len(a) && string(a[p - 1:p + 2]) == "abc" { return true}
        if p >= 0 && p + 3 <= len(a) && string(a[p:p + 3]) == "abc" { return true}
        return false
    }

    for q > 0 {
        q--
        var pos int
        var ss string
        fmt.Fscan(input, &pos, &ss)
        pos--
        c := ss[0]
        if c == a[pos] {
            fmt.Fprintln(output, cnt)
            continue
        }

        if good(pos) {
            cnt--
            a[pos] = c
        } else {
            a[pos] = c
            if good(pos) {
                cnt++
            }
        }

        fmt.Fprintln(output, cnt)
    }
}

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


Let us define two functions f and g on positive integer numbers.   You need to process Q queries. In each query, you will be given three integers l, r and k. You need to print the number of integers x between l and r inclusive, such that g(x) = k.

The first line of the input contains an integer Q (1 ≤ Q ≤ 2 × 105) representing the number of queries.  Q lines follow, each of which contains 3 integers l, r and k (1 ≤ l ≤ r ≤ 106, 1 ≤ k ≤ 9).

For each query, print a single line containing the answer for that query.

NoteIn the first example:  g(33) = 9 as g(33) = g(3 × 3) = g(9) = 9  g(47) = g(48) = g(60) = g(61) = 6  There are no such integers between 47 and 55.  g(4) = g(14) = g(22) = g(27) = g(39) = g(40) = g(41) = g(58) = 4

package main

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

func f(n int) int {
	r := 1
	for n > 0 {
		if n%10 > 0 {
			r *= n % 10
		}
		n /= 10
	}
	return r
}

func g(n int) int {
	if n < 10 {
		return n
	}
	return g(f(n))
}

var prefix [1e6 + 47][10]int

func init() {
	for i := 1; i < len(prefix); i++ {
		prefix[i] = prefix[i-1]
		r := g(i)
		prefix[i][r]++
	}
}

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

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

	for i := 0; i < n; i++ {
		var l, r, k int
		fmt.Fscan(in, &l, &r, &k)
		fmt.Fprintln(out, prefix[r][k]-prefix[l-1][k])
	}
}

package main

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

var f[1000010] int
var c[10][1000010] int

func getF(x int) int{
	if f[x] > 0{
		return f[x]
	}
	tmp := 1
	for ;;{
		if x == 0{
			break
		}
		if x % 10 > 0{
			tmp = tmp * (x % 10)
		}
		x /= 10
	}
	return getF(tmp)
}

func prework(){
	for i := 1; i < 10; i++{
		f[i] = i
		c[i][i] = 1
	}
	for i := 10; i < 1000010; i++{
		f[i] = getF(i)
		c[f[i]][i] = 1
	}
	for i := 1; i < 10; i++{
		for j:= 1; j < 1000010; j++{
			c[i][j] = c[i][j - 1] + c[i][j]
		}
	}
}

func main(){
	in := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(in, &n)
	prework()
	for i := 1; i <= n; i++{
		var l, r, k int
		fmt.Fscan(in, &l, &r, &k)
		fmt.Println(c[k][r] - c[k][l - 1])
	}
}


The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond?

The first line of input contain two integers, $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 99$$$, $$$0 \leq k \leq 2\times(n-2)$$$), $$$n$$$ is odd, the width of the city, and the number of hotels to be placed, respectively.

Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra $$$4$$$ lines that describe the city, each line should have $$$n$$$ characters, each of which is "#" if that cell has a hotel on it, or "." if not.

package main

import (
	"fmt"
	"strconv"
)

func Process(width int, k int) (string, [4][]string) {
	var cityArray = [4][]string{}

	for i := 0; i < 4; i++ {
		cityArray[i] = make([]string, width)

		for key := range cityArray[i] {
			cityArray[i][key] = "."
		}
	}

	if k == 0 {
		return "YES", cityArray
	}

	var space = 2 * (width - 2)

	if k > space {
		return "NO", cityArray
	}

	for row := 0; row < 4; row++ {
		if k == 0 {
			break
		}

		if row == 0 || row == 3 {
			continue
		}

		if k%2 == 1 || space == k {
			cityArray[row][width/2] = "#"
			k--
		}

		for col := 0; col < width/2; col++ {
			if k == 0 {
				break
			}

			if col == 0 || col == width-1 {
				continue
			}

			cityArray[row][col] = "#"
			k--

			if k == 0 {
				break
			}

			if col == width/2 {
				continue
			}

			cityArray[row][width-1-col] = "#"
			k--
		}
	}

	for rowKey, row := range cityArray {
		if rowKey == 0 || rowKey == 3 {
			continue
		}

		for colKey := range row {
			if colKey == 0 || colKey == width-1 {
				continue
			}

		}
	}

	return "YES", cityArray
}

func main() {
	var widthString string
	var countString string
	fmt.Scanln(&widthString, &countString)

	var width, _ = strconv.Atoi(widthString)
	var count, _ = strconv.Atoi(countString)

	var result, city = Process(width, count)

	fmt.Println(result)

	if result == "YES" {
		for _, row := range city {
			for _, col := range row {
				fmt.Print(col)
			}
			fmt.Println()
		}
	}
}

package main

import "fmt"

func main() {

	var n, k int
	const length = 4
	fmt.Scan(&n, &k)

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

	counter := 0
	for i := 1; i < int(n/2) && counter < k-1; i++ {
		cityMap[1][i], cityMap[1][n-1-i] = 1, 1
		counter += 2
	}

	if k % 2 == 1 {
		cityMap[1][n/2] = 1
		counter++
	}

	if counter < k {
		for i := 1; i < int(n/2) && counter < k; i++ {
			cityMap[2][i], cityMap[2][n-1-i] = 1, 1
			counter += 2
		}
	}

	if k == 2 * (n-2) {
		cityMap[1][n/2], cityMap[2][n/2] = 1, 1
	}

	fmt.Println("YES")

	for i := 0; i < length; i++ {
		for j := 0; j < n; j++ {
			if cityMap[i][j] == 0 {
				fmt.Print(".")
			} else {
				fmt.Print("#")
			}
		}
		fmt.Println()
	}
}

package main

import (
	"fmt"
	"strconv"
)

func Process(width int, k int) (string, [4][]string) {
	var cityArray = [4][]string{}

	for i := 0; i < 4; i++ {
		cityArray[i] = make([]string, width)

		for key := range cityArray[i] {
			cityArray[i][key] = "."
		}
	}

	if k == 0 {
		return "YES", cityArray
	}

	var space = 2 * (width - 2)

	if k > space {
		return "NO", cityArray
	}

	for row := 0; row < 4; row++ {
		if k == 0 {
			break
		}

		if row == 0 || row == 3 {
			continue
		}

		for col := 0; col < width; col++ {
			if k == 0 {
				break
			}

			if col == 0 || col == width-1 {
				continue
			}

			cityArray[row][col] = "#"
			k--

			if k == 0 {
				break
			}

			if cityArray[row][width-1-col] == "#" {
				continue
			}

			cityArray[row][width-1-col] = "#"
			k--
		}
	}

	for rowKey, row := range cityArray {
		if rowKey == 0 || rowKey == 3 {
			continue
		}

		for colKey := range row {
			if colKey == 0 || colKey == width-1 {
				continue
			}

		}
	}

	return "YES", cityArray
}

func main() {
	var widthString string
	var countString string
	fmt.Scanln(&widthString, &countString)

	var width, _ = strconv.Atoi(widthString)
	var count, _ = strconv.Atoi(countString)

	var result, city = Process(width, count)

	fmt.Println(result)

	if result == "YES" {
		for _, row := range city {
			for _, col := range row {
				fmt.Print(col)
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
	"strconv"
)

func Process(width int, k int) (string, [4][]string) {
	var cityArray = [4][]string{}

	for i := 0; i < 4; i++ {
		cityArray[i] = make([]string, width)

		for key := range cityArray[i] {
			cityArray[i][key] = "."
		}
	}

	if k == 0 {
		return "YES", cityArray
	}

	var space = 2 * (width - 2)

	if k > space {
		return "NO", cityArray
	}

	for row := 0; row < 4; row++ {
		if k == 0 {
			break
		}

		if row == 0 || row == 3 {
			continue
		}

		for col := 0; col < width; col++ {
			if k == 0 {
				break
			}

			if col == 0 || col == width-1 {
				continue
			}

			cityArray[row][col] = "#"
			k--

			if k == 0 {
				break
			}

			cityArray[row][width-1-col] = "#"
			k--
		}
	}

	for rowKey, row := range cityArray {
		if rowKey == 0 || rowKey == 3 {
			continue
		}

		for colKey := range row {
			if colKey == 0 || colKey == width-1 {
				continue
			}

		}
	}

	return "YES", cityArray
}

func main() {
	var widthString string
	var countString string
	fmt.Scanln(&widthString, &countString)

	var width, _ = strconv.Atoi(widthString)
	var count, _ = strconv.Atoi(countString)

	var result, city = Process(width, count)

	fmt.Println(result)

	if result == "YES" {
		for _, row := range city {
			for _, col := range row {
				fmt.Print(col)
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
	"strconv"
)

func Process(width int, k int) (string, [4][]string) {
	var cityArray = [4][]string{}

	for i := 0; i < 4; i++ {
		cityArray[i] = make([]string, width)

		for key := range cityArray[i] {
			cityArray[i][key] = "."
		}
	}

	if k == 0 {
		return "YES", cityArray
	}

	var space = 2 * (width - 2)

	if k > space {
		return "NO", cityArray
	}

	for row := 0; row < 4; row++ {
		if k == 0 {
			break
		}

		if row == 0 || row == 3 {
			continue
		}

		for col := 0; col < width; col++ {
			if k == 0 {
				break
			}

			if col == 0 || col == width-1 {
				continue
			}

			if k == 1 {
				var middle = width / 2
				cityArray[row][middle] = "#"
				k--
			}

			if k == 0 {
				break
			}

			cityArray[row][col] = "#"
			k--

			if k == 0 {
				break
			}

			if cityArray[row][width-1-col] == "#" {
				continue
			}

			cityArray[row][width-1-col] = "#"
			k--
		}
	}

	for rowKey, row := range cityArray {
		if rowKey == 0 || rowKey == 3 {
			continue
		}

		for colKey := range row {
			if colKey == 0 || colKey == width-1 {
				continue
			}

		}
	}

	return "YES", cityArray
}

func main() {
	var widthString string
	var countString string
	fmt.Scanln(&widthString, &countString)

	var width, _ = strconv.Atoi(widthString)
	var count, _ = strconv.Atoi(countString)

	var result, city = Process(width, count)

	fmt.Println(result)

	if result == "YES" {
		for _, row := range city {
			for _, col := range row {
				fmt.Print(col)
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
	"strconv"
)

func Process(width int, k int) (string, [4][]string) {
	var cityArray = [4][]string{}

	for i := 0; i < 4; i++ {
		cityArray[i] = make([]string, width)

		for key := range cityArray[i] {
			cityArray[i][key] = "."
		}
	}

	if k == 0 {
		return "YES", cityArray
	}

	var space = 2 * (width - 2)

	if k > space {
		return "NO", cityArray
	}

	for row := 0; row < 4; row++ {
		if k == 0 {
			break
		}

		if row == 0 || row == 3 {
			continue
		}

		for col := 0; col < width/2; col++ {
			if k == 0 {
				break
			}

			if col == 0 || col == width-1 {
				continue
			}

			if k == 1 {
				cityArray[row][width/2] = "#"
				k--
			}

			if k == 0 {
				break
			}

			cityArray[row][col] = "#"
			k--

			if k == 0 {
				break
			}

			cityArray[row][width-1-col] = "#"
			k--

			if k == 1 {
				cityArray[row][width/2] = "#"
				k--
			}
		}
	}

	for rowKey, row := range cityArray {
		if rowKey == 0 || rowKey == 3 {
			continue
		}

		for colKey := range row {
			if colKey == 0 || colKey == width-1 {
				continue
			}

		}
	}

	return "YES", cityArray
}

func main() {
	var widthString string
	var countString string
	fmt.Scanln(&widthString, &countString)

	var width, _ = strconv.Atoi(widthString)
	var count, _ = strconv.Atoi(countString)

	var result, city = Process(width, count)

	fmt.Println(result)

	if result == "YES" {
		for _, row := range city {
			for _, col := range row {
				fmt.Print(col)
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
	"strconv"
)

func Process(width int, k int) (string, [4][]string) {
	var cityArray = [4][]string{}

	for i := 0; i < 4; i++ {
		cityArray[i] = make([]string, width)

		for key := range cityArray[i] {
			cityArray[i][key] = "."
		}
	}

	if k == 0 {
		return "YES", cityArray
	}

	var space = 2 * (width - 2)

	if k > space {
		return "NO", cityArray
	}

	for row := 0; row < 4; row++ {
		if k == 0 {
			break
		}

		if row == 0 || row == 3 {
			continue
		}

		for col := 0; col < width; col++ {
			if k == 0 {
				break
			}

			if col == 0 || col == width-1 {
				continue
			}

			if k == 1 {
				var middle = width/2 + 1
				cityArray[row][middle] = "#"
			}

			cityArray[row][col] = "#"
			k--

			if k == 0 {
				break
			}

			if cityArray[row][width-1-col] == "#" {
				continue
			}

			cityArray[row][width-1-col] = "#"
			k--
		}
	}

	for rowKey, row := range cityArray {
		if rowKey == 0 || rowKey == 3 {
			continue
		}

		for colKey := range row {
			if colKey == 0 || colKey == width-1 {
				continue
			}

		}
	}

	return "YES", cityArray
}

func main() {
	var widthString string
	var countString string
	fmt.Scanln(&widthString, &countString)

	var width, _ = strconv.Atoi(widthString)
	var count, _ = strconv.Atoi(countString)

	var result, city = Process(width, count)

	fmt.Println(result)

	if result == "YES" {
		for _, row := range city {
			for _, col := range row {
				fmt.Print(col)
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
	"strconv"
)

func Process(width int, k int) (string, [4][]string) {
	var cityArray = [4][]string{}

	for i := 0; i < 4; i++ {
		cityArray[i] = make([]string, width)

		for key := range cityArray[i] {
			cityArray[i][key] = "."
		}
	}

	if k == 0 {
		return "YES", cityArray
	}

	var space = 2 * (width - 2)

	if k > space {
		return "NO", cityArray
	}

	for row := 0; row < 4; row++ {
		if k == 0 {
			break
		}

		if row == 0 || row == 3 {
			continue
		}

		for col := 0; col < width; col++ {
			if k == 0 {
				break
			}

			if col == 0 || col == width-1 {
				continue
			}

			if k == 1 {
				var middle = width/2 + 1
				cityArray[row][middle] = "#"
				k--
			}

			if k == 0 {
				break
			}

			cityArray[row][col] = "#"
			k--

			if k == 0 {
				break
			}

			if cityArray[row][width-1-col] == "#" {
				continue
			}

			cityArray[row][width-1-col] = "#"
			k--
		}
	}

	for rowKey, row := range cityArray {
		if rowKey == 0 || rowKey == 3 {
			continue
		}

		for colKey := range row {
			if colKey == 0 || colKey == width-1 {
				continue
			}

		}
	}

	return "YES", cityArray
}

func main() {
	var widthString string
	var countString string
	fmt.Scanln(&widthString, &countString)

	var width, _ = strconv.Atoi(widthString)
	var count, _ = strconv.Atoi(countString)

	var result, city = Process(width, count)

	fmt.Println(result)

	if result == "YES" {
		for _, row := range city {
			for _, col := range row {
				fmt.Print(col)
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
	"strconv"
)

func Process(width int, k int) (string, [4][]string) {
	var cityArray = [4][]string{}

	for i := 0; i < 4; i++ {
		cityArray[i] = make([]string, width)

		for key := range cityArray[i] {
			cityArray[i][key] = "."
		}
	}

	if k == 0 {
		return "YES", cityArray
	}

	var space = 2 * (width - 2)

	if k > space {
		return "NO", cityArray
	}

	for row := 0; row < 4; row++ {
		if k == 0 {
			break
		}

		if row == 0 || row == 3 {
			continue
		}

		for col := 0; col < width/2; col++ {
			if k == 0 {
				break
			}

			if col == 0 || col == width-1 {
				continue
			}

			if k == 1 {
				cityArray[row][width/2] = "#"
				k--
			}

			if k == 0 {
				break
			}

			cityArray[row][col] = "#"
			k--

			if k == 1 {
				cityArray[row][width/2] = "#"
				k--
			}

			if k == 0 {
				break
			}

			cityArray[row][width-1-col] = "#"
			k--

			if k == 1 {
				cityArray[row][width/2] = "#"
				k--
			}
		}
	}

	for rowKey, row := range cityArray {
		if rowKey == 0 || rowKey == 3 {
			continue
		}

		for colKey := range row {
			if colKey == 0 || colKey == width-1 {
				continue
			}

		}
	}

	return "YES", cityArray
}

func main() {
	var widthString string
	var countString string
	fmt.Scanln(&widthString, &countString)

	var width, _ = strconv.Atoi(widthString)
	var count, _ = strconv.Atoi(countString)

	var result, city = Process(width, count)

	fmt.Println(result)

	if result == "YES" {
		for _, row := range city {
			for _, col := range row {
				fmt.Print(col)
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
	"strconv"
)

func Process(width int, k int) (string, [4][]string) {
	var cityArray = [4][]string{}

	for i := 0; i < 4; i++ {
		cityArray[i] = make([]string, width)

		for key := range cityArray[i] {
			cityArray[i][key] = "."
		}
	}

	if k == 0 {
		return "YES", cityArray
	}

	var space = 2 * (width - 2)

	if k > space {
		return "NO", cityArray
	}

	for row := 0; row < 4; row++ {
		if k == 0 {
			break
		}

		if row == 0 || row == 3 {
			continue
		}

		if k%2 == 1 || width == 3 {
			cityArray[row][width/2] = "#"
			k--
		}

		for col := 0; col < width/2; col++ {
			if k == 0 {
				break
			}

			if col == 0 || col == width-1 {
				continue
			}

			cityArray[row][col] = "#"
			k--

			if k == 0 {
				break
			}

			if col == width/2 {
				continue
			}

			cityArray[row][width-1-col] = "#"
			k--
		}
	}

	for rowKey, row := range cityArray {
		if rowKey == 0 || rowKey == 3 {
			continue
		}

		for colKey := range row {
			if colKey == 0 || colKey == width-1 {
				continue
			}

		}
	}

	return "YES", cityArray
}

func main() {
	var widthString string
	var countString string
	fmt.Scanln(&widthString, &countString)

	var width, _ = strconv.Atoi(widthString)
	var count, _ = strconv.Atoi(countString)

	var result, city = Process(width, count)

	fmt.Println(result)

	if result == "YES" {
		for _, row := range city {
			for _, col := range row {
				fmt.Print(col)
			}
			fmt.Println()
		}
	}
}

package main

import "fmt"

func main() {

	var n, k int
	const length = 4
	fmt.Scan(&n, &k)

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

	counter := 0
	for i := 1; i < int(n/2) && counter < k-1; i++ {
		cityMap[1][i], cityMap[1][n-1-i] = 1, 1
		counter += 2
	}

	if k % 2 == 1 {
		fmt.Println("ADDED")
		cityMap[1][n/2] = 1
		counter++
	}

	if counter < k {
		for i := 1; i < int(n/2) && counter < k; i++ {
			cityMap[2][i], cityMap[2][n-1-i] = 1, 1
			counter += 2
		}
	}

	if k == 2 * (n-2) {
		cityMap[1][n/2], cityMap[2][n/2] = 1, 1
	}

	fmt.Println("YES")

	for i := 0; i < length; i++ {
		for j := 0; j < n; j++ {
			if cityMap[i][j] == 0 {
				fmt.Print(".")
			} else {
				fmt.Print("#")
			}
		}
		fmt.Println()
	}
}


Little Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.

The first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.

Output one integer — minimum number of steps required to achieve the goal.

package main

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

func abs(x int) int64 {
	if x > 0 {
		return int64(x)
	} else {
		return int64(-x)
	}
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewReader(bs)
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]int, n)
	b := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d ", &a[i])
		b[i] = a[i]
	}
	sort.Ints(b)
	var dp [2][]int64
	dp[0] = make([]int64, n)
	dp[1] = make([]int64, n)

	dp[0][0] = abs(a[0] - b[0])
	for i := 1; i < n; i++ {
		dp[0][i] = abs(a[0] - b[i])
		if dp[0][i] > dp[0][i-1] {
			dp[0][i] = dp[0][i-1]
		}
	}
	prev, cur := 0, 1
	for i := 1; i < n; i++ {
		dp[cur][0] = dp[prev][0] + abs(a[i]-b[0])
		for j := 1; j < n; j++ {
			if dp[prev][j]+abs(a[i]-b[j]) > dp[cur][j-1] {
				dp[cur][j] = dp[cur][j-1]
			} else {
				dp[cur][j] = dp[prev][j] + abs(a[i]-b[j])
			}
		}
		prev, cur = cur, prev
	}
	fmt.Printf("%d", dp[prev][n-1])
}

package main

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

var scanner *bufio.Scanner

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

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

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

  n := getI()
  values := make([]int64, n)
  ceilings := make([]int64, n)
  for i := range values {
    values[i] = getI64()
    ceilings[i] = values[i]
  }
  sort.Sort(sliceInt64(ceilings))

  cost := make([]int64, n)
  for _, x := range values {
    pos := 0
    for ; pos < n && ceilings[pos] < x; pos++ {
      cost[pos] += x - ceilings[pos]
    }
    best := cost[pos]
    for ; pos < n; pos++ {
      attempt := cost[pos] + ceilings[pos] - x
      if attempt < best {
        best = attempt
      }
      cost[pos] = best
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", cost[n - 1]))
}

package main

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

var scanner *bufio.Scanner

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

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

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

  n := getI()
  values := make([]int64, n)
  ceilings := make([]int64, n)
  for i := range values {
    values[i] = getI64()
    ceilings[i] = values[i]
  }
  sort.Sort(sliceInt64(ceilings))

  cost := make([]int64, n)
  for _, x := range values {
    pos := 0
    for ; pos < n && ceilings[pos] < x; pos++ {
      cost[pos] += x - ceilings[pos]
    }
    pos += 1
    for ; pos < n; pos++ {
      cost[pos] += ceilings[pos] - x
      if cost[pos - 1] < cost[pos] {
        cost[pos] = cost[pos - 1]
      }
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", cost[n - 1]))
}

package main

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

var scanner *bufio.Scanner

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

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

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

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

  n := getI()
  values := make([]int64, n)
  ceilings := make([]int64, n)
  for i := range values {
    values[i] = getI64()
    ceilings[i] = values[i]
  }
  sort.Sort(sliceInt64(ceilings))

  cost := make([]int64, n)
  for _, x := range values {
    pos := 0
    for ; pos < n && ceilings[pos] < x; pos++ {
      cost[pos] += x - ceilings[pos]
    }
    pos += 1
    for ; pos < n; pos++ {
      cost[pos] = min(cost[pos - 1], cost[pos] + ceilings[pos] - x)
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", cost[n - 1]))
}

// https://codeforces.com/contest/13/problem/C
package main

import (
	"fmt"
	"sort"
)

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

func main() {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	fmt.Scan(&n)
	a := make([]int64, n)
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
		b[i] = a[i]
	}
	sort.Slice(b, func (i, j int) bool {return b[i] < b[j]})
	m := 0
	for i := 1; i < n; i++ {
		if b[m] != b[i] {
			m++
			b[m] = b[i]
		}
	}

	f := make([]int64, m + 1)
	f[0] = abs(a[0] - b[0])
	for k := 1; k <= m; k++ {
		f[k] = min(abs(a[0] - b[k]), f[k - 1])
	}

	for i := 1; i < n; i++ {
		g := make([]int64, m + 1)
		for k := 0; k <= m; k++ {
			if k > 0 {
				g[k] = min(g[k - 1], abs(a[i] - b[k]) + f[k])
			} else {
				g[k] = abs(a[i] - b[k]) + f[k]
			}
		}
		f = g
	}

	fmt.Println(f[m])
}

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

	return b
}

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

package main

import (
	"bufio"
	"container/heap"
	. "fmt"
	"io"
	"os"
	"sort"
)

type hp struct{ sort.IntSlice }

func (h hp) Less(i, j int) bool  { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() interface{}   { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }

// github.com/EndlessCheng/codeforces-go
func CF13C(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, v int
	Fscan(in, &n)
	ans := int64(0)
	for h := (hp{}); n > 0; n-- {
		Fscan(in, &v)
		heap.Push(&h, v)
		if d := h.IntSlice[0] - v; d > 0 {
			ans += int64(d)
			h.IntSlice[0] = v
			heap.Fix(&h, 0)
		}
	}
	Fprint(out, ans)
}

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

package main

import (
	"bufio"
	"container/heap"
	. "fmt"
	"io"
	"os"
	"sort"
)

type hp struct{ sort.IntSlice }

func (h hp) Less(i, j int) bool  { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() interface{}   { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }

// github.com/EndlessCheng/codeforces-go
func CF13C(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, v int
	Fscan(in, &n)
	ans := int64(0)
	for h := (hp{}); n > 0; n-- {
		Fscan(in, &v)
		heap.Push(&h, v)
		if d := h.IntSlice[0] - v; d > 0 {
			ans += int64(0)
			h.IntSlice[0] = v
			heap.Fix(&h, 0)
		}
	}
	Fprint(out, ans)
}

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

package main

import (
	"bufio"
	"container/heap"
	. "fmt"
	"io"
	"os"
	"sort"
)

type hp struct{ sort.IntSlice }

func (h hp) Less(i, j int) bool  { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() interface{}   { a := h.IntSlice; v := a[len(a)-1]; h.IntSlice = a[:len(a)-1]; return v }

// github.com/EndlessCheng/codeforces-go
func CF13C(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, v, ans int
	Fscan(in, &n)
	for h := (hp{}); n > 0; n-- {
		Fscan(in, &v)
		heap.Push(&h, v)
		if d := h.IntSlice[0] - v; d > 0 {
			ans += d
			h.IntSlice[0] = v
			heap.Fix(&h, 0)
		}
	}
	Fprint(out, ans)
}

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


Treeland is a country in which there are n towns connected by n - 1 two-way road such that it's possible to get from any town to any other town. In Treeland there are 2k universities which are located in different towns. Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done! To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in k pairs should be as large as possible. Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1.

The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ n / 2) — the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to n.  The second line contains 2k distinct integers u1, u2, ..., u2k (1 ≤ ui ≤ n) — indices of towns in which universities are located.  The next n - 1 line contains the description of roads. Each line contains the pair of integers xj and yj (1 ≤ xj, yj ≤ n), which means that the j-th road connects towns xj and yj. All of them are two-way roads. You can move from any town to any other using only these roads.

Print the maximum possible sum of distances in the division of universities into k pairs.

NoteThe figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5 (marked in blue) by using the cable, the total distance will equal 6 which will be the maximum sum in this example.

package main

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

var in *bufio.Scanner
var out *bufio.Writer
var n, k, e, m, h int
var univ, adj, next, last []int
var res int64

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

func writeInt64(val int64) {
	out.WriteString(strconv.FormatInt(val, 10))
}

func addEdge(x int, y int) {
	adj[e] = y
	next[e] = last[x]
	last[x] = e
	e++
}

func dfs(x int, par int) int {
	xc := univ[x]
	for e := last[x]; e != -1; e = next[e] {
		y := adj[e]
		if y != par {
			yc := dfs(y, x)
			zc := h - yc
			xc += yc
			if yc < zc {
				res += int64(yc)
			} else {
				res += int64(zc)
			}
		}
	}
	return xc
}

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

	in.Split(bufio.ScanWords)
	defer out.Flush()

	n = readInt()
	k = readInt()

	e = 0
	m = 2 * n
	h = 2 * k

	univ = make([]int, n)
	adj = make([]int, m)
	next = make([]int, m)
	last = make([]int, n)

	for i := 0; i < n; i++ {
		univ[i] = 0
		last[i] = -1
	}

	for i := 0; i < 2*k; i++ {
		u := readInt() - 1
		univ[u]++
	}

	for i := 0; i < n-1; i++ {
		x := readInt() - 1
		y := readInt() - 1
		addEdge(x, y)
		addEdge(y, x)
	}

	res = 0
	dfs(0, 0)
	writeInt64(res)
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF700B(_r io.Reader, out io.Writer) {
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}
	in := bufio.NewReader(_r)
	var n, k, v, w int
	Fscan(in, &n, &k)
	k *= 2
	size := make([]int, n)
	for i := k; i > 0; i-- {
		Fscan(in, &v)
		size[v-1] = 1
	}
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	ans := int64(0)
	var f func(v, fa int) int
	f = func(v, fa int) int {
		sz := size[v]
		for _, w := range g[v] {
			if w != fa {
				s := f(w, v)
				ans += int64(min(s, k-s))
				sz += s
			}
		}
		return sz
	}
	f(0, -1)
	Fprint(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF700B(_r io.Reader, out io.Writer) {
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			_r.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	n, k := r(), r()*2
	has := make([]bool, n)
	for i := k; i > 0; i-- {
		has[r()-1] = true
	}
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		v, w := r()-1, r()-1
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	ans := int64(0)
	var f func(v, fa int) int
	f = func(v, fa int) (sz int) {
		if has[v] {
			sz = 1
		}
		for _, w := range g[v] {
			if w != fa {
				s := f(w, v)
				ans += int64(min(s, k-s))
				sz += s
			}
		}
		return
	}
	f(0, -1)
	Fprint(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF700B(_r io.Reader, out io.Writer) {
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}
	in := bufio.NewReader(_r)
	var n, k, v, w int
	Fscan(in, &n, &k)
	k *= 2
	has := make([]bool, n)
	for i := k; i > 0; i-- {
		Fscan(in, &v)
		has[v-1] = true
	}
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	ans := int64(0)
	var f func(v, fa int) int
	f = func(v, fa int) (sz int) {
		if has[v] {
			sz = 1
		}
		for _, w := range g[v] {
			if w != fa {
				s := f(w, v)
				ans += int64(min(s, k-s))
				sz += s
			}
		}
		return
	}
	f(0, -1)
	Fprint(out, ans)
}

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

package main

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

type FastIO struct {
	in  *bufio.Scanner
	out *bufio.Writer
}

func NewFastIO() *FastIO {
	f := FastIO{
		in:  bufio.NewScanner(os.Stdin),
		out: bufio.NewWriter(os.Stdout),
	}

	f.in.Split(bufio.ScanWords)
	return &f
}

func (f *FastIO) Flush() {
	f.out.Flush()
}

func (f *FastIO) ReadInt() int {
	f.in.Scan()
	val, _ := strconv.Atoi(f.in.Text())
	return val
}

func (f *FastIO) WriteInt64(val int64) {
	f.out.WriteString(strconv.FormatInt(val, 10))
}

var n, k, e, m, h int
var univ, adj, next, last []int
var res int64

func AddEdge(x int, y int) {
	adj[e] = y
	next[e] = last[x]
	last[x] = e
	e++
}

func dfs(x int, par int) int {
	cntX := univ[x]

	for e := last[x]; e != -1; e = next[e] {
		y := adj[e]
		if y != par {
			cntY := dfs(y, x)
			cntZ := h - cntY
			if cntY < cntZ {
				res += int64(cntY)
			} else {
				res += int64(cntZ)
			}
			cntX += cntY
		}
	}

	return cntX
}

func main() {
	f := NewFastIO()
	defer f.Flush()

	n = f.ReadInt()
	k = f.ReadInt()

	e = 0
	m = 2 * n
	h = 2 * k

	univ = make([]int, n)
	adj = make([]int, m)
	next = make([]int, m)
	last = make([]int, n)

	for i := 0; i < n; i++ {
		univ[i] = 0
		last[i] = -1
	}

	for i := 0; i < 2*k; i++ {
		u := f.ReadInt() - 1
		univ[u]++
	}

	for i := 0; i < n-1; i++ {
		x := f.ReadInt() - 1
		y := f.ReadInt() - 1
		AddEdge(x, y)
		AddEdge(y, x)
	}

	res = 0
	dfs(0, 0)
	f.WriteInt64(res)
}

package main

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

type FastIO struct {
	in  *bufio.Scanner
	out *bufio.Writer
}

func NewFastIO() *FastIO {
	f := FastIO{
		in:  bufio.NewScanner(os.Stdin),
		out: bufio.NewWriter(os.Stdout),
	}

	f.in.Split(bufio.ScanWords)
	return &f
}

func (f *FastIO) Flush() {
	f.out.Flush()
}

func (f *FastIO) ReadInt() int {
	f.in.Scan()
	val, _ := strconv.Atoi(f.in.Text())
	return val
}

func (f *FastIO) WriteInt64(val int64) {
	f.out.WriteString(strconv.FormatInt(val, 10))
}

type Graph struct {
	e    int
	adj  []int
	next []int
	last []int
}

func NewGraph(n int, m int) *Graph {
	g := Graph{
		e:    0,
		adj:  make([]int, m),
		next: make([]int, m),
		last: make([]int, n),
	}
	for i := 0; i < n; i++ {
		g.last[i] = -1
	}
	return &g
}

func (g *Graph) AddEdge(x int, y int) {
	g.adj[g.e] = y
	g.next[g.e] = g.last[x]
	g.last[x] = g.e
	g.e++
}

var n, k int
var univ []bool
var g *Graph
var cnt []int

func dfs(x int) {
	if univ[x] {
		cnt[x] = 1
	} else {
		cnt[x] = 0
	}
	for e := g.last[x]; e != -1; e = g.next[e] {
		y := g.adj[e]
		if cnt[y] == -1 {
			dfs(y)
			cnt[x] += cnt[y]
		}
	}
}

func main() {
	f := NewFastIO()
	defer f.Flush()

	n = f.ReadInt()
	k = f.ReadInt()

	univ = make([]bool, n)
	for i := 0; i < n; i++ {
		univ[i] = false
	}

	for i := 0; i < 2*k; i++ {
		u := f.ReadInt() - 1
		univ[u] = true
	}

	g = NewGraph(n, 2*n)
	for i := 0; i < n-1; i++ {
		x := f.ReadInt() - 1
		y := f.ReadInt() - 1
		g.AddEdge(x, y)
		g.AddEdge(y, x)
	}

	cnt = make([]int, n)
	for i := 0; i < n; i++ {
		cnt[i] = -1
	}
	dfs(0)

	res := int64(0)
	for y := 1; y < n; y++ {
		a := int64(cnt[y])
		b := int64(2*k) - a
		if a < b {
			res += a
		} else {
			res += b
		}
	}

	f.WriteInt64(res)
}

package main

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

type FastIO struct {
	in  *bufio.Scanner
	out *bufio.Writer
}

func NewFastIO() *FastIO {
	f := FastIO{
		in:  bufio.NewScanner(os.Stdin),
		out: bufio.NewWriter(os.Stdout),
	}

	f.in.Split(bufio.ScanWords)
	return &f
}

func (f *FastIO) Flush() {
	f.out.Flush()
}

func (f *FastIO) ReadInt() int {
	f.in.Scan()
	val, _ := strconv.Atoi(f.in.Text())
	return val
}

func (f *FastIO) WriteInt(val int) {
	f.out.WriteString(strconv.Itoa(val))
}

type Graph struct {
	e    int
	adj  []int
	next []int
	last []int
}

func NewGraph(n int, m int) *Graph {
	g := Graph{
		e:    0,
		adj:  make([]int, m),
		next: make([]int, m),
		last: make([]int, n),
	}
	for i := 0; i < n; i++ {
		g.last[i] = -1
	}
	return &g
}

func (g *Graph) AddEdge(x int, y int) {
	g.adj[g.e] = y
	g.next[g.e] = g.last[x]
	g.last[x] = g.e
	g.e++
}

var n, k int
var univ []bool
var g *Graph
var cnt []int

func dfs(x int) {
	if univ[x] {
		cnt[x] = 1
	} else {
		cnt[x] = 0
	}
	for e := g.last[x]; e != -1; e = g.next[e] {
		y := g.adj[e]
		if cnt[y] == -1 {
			dfs(y)
			cnt[x] += cnt[y]
		}
	}
}

func main() {
	f := NewFastIO()
	defer f.Flush()

	n = f.ReadInt()
	k = f.ReadInt()

	univ = make([]bool, n)
	for i := 0; i < n; i++ {
		univ[i] = false
	}

	for i := 0; i < 2*k; i++ {
		u := f.ReadInt() - 1
		univ[u] = true
	}

	g = NewGraph(n, 2*n)
	for i := 0; i < n-1; i++ {
		x := f.ReadInt() - 1
		y := f.ReadInt() - 1
		g.AddEdge(x, y)
		g.AddEdge(y, x)
	}

	cnt = make([]int, n)
	for i := 0; i < n; i++ {
		cnt[i] = -1
	}
	dfs(0)

	res := 0
	for y := 1; y < n; y++ {
		a := cnt[y]
		b := 2*k - a
		if a < b {
			res += a
		} else {
			res += b
		}
	}

	f.WriteInt(res)
}


Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:   the graph contains exactly 2n + p edges;  the graph doesn't contain self-loops and multiple edges;  for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices.

The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; ) — the number of vertices in the graph and the interest value for the appropriate test.  It is guaranteed that the required graph exists.

For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.  Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.

package main

import "os"
import "bufio"
import "strconv"

func main(){
	var t int
	var n, p int
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	t, _ = strconv.Atoi(r.Text())
	x := 0
	for i:=0; i<t; i++ {
		r.Scan()
		n, _ = strconv.Atoi(r.Text())
		r.Scan()
		p, _ = strconv.Atoi(r.Text())
		for j:=1; j<n; j++ {
			for k:=j+1; k<=n; k++ {
				x += 1
				w.WriteString(strconv.Itoa(j)+" "+strconv.Itoa(k)+"\n")
				if x == 2 * n + p {
					x = 0
					k = n
					j = n
				}
			}
		}
		w.Flush()
	}

}

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

func main() {
	var t,n,p,e,a,b int
	out:=bufio.NewWriter(os.Stdout)
	fmt.Scan(&t)
	for t=t;t>0;t-- {
		fmt.Scan(&n,&p)
		e=2*n+p
		a=1
		b=1
		for e=e;e>0;e-- {
			b++
			if b>n {
				a++
				b=a+1
			}
			out.WriteString(strconv.Itoa(a)+" "+strconv.Itoa(b)+"\n")
		}
	}
	out.Flush()
}

package main

import "fmt"

func main() {
    var t,n,p int
    fmt.Scan(&t)
    for ; t > 0; t-- {
        fmt.Scan(&n,&p)
        for e,a,b := 2*n+p,1,2; e > 0; e-- {
            fmt.Println(a,b)
            b++
            if b > n {
                a++
                b = a+1
            }
        }
    }
}

package main

import "fmt"

func main() {
    var t,n,p int // variabel t, n, p adalah integer
    fmt.Scan(&t) // meminta input t
    for ; t > 0; t-- { // lakukan selama kondisi ini
        fmt.Scan(&n,&p) //meminta input n dan p
        for e,a,b := 2*n+p,1,2; e > 0; e-- { // lakukan selama kondisi ini
            fmt.Println(a,b) // mencetak output
            b++ // lakukan terus selama kondisi berlaku
            if b > n { // kondisi
                a++ // lakukan terus selama kondisi berlaku
                b = a+1 // a+1 dimasukan kedalam b
            }
        }
    }
}

// 402C
package main

import (
	"fmt"
)

func main() {
	var N, K, i, j, n, m, p int
	fmt.Scan(&N)
	for K = 1; K <= N; K++ {
		fmt.Scan(&n, &p)
		m = 0
		for i = 1; i <= n; i++ {
			for j = i + 1; j <= n; j++ {
				fmt.Printf("%d %d\n", i, j)
				m++
				if m == 2*n+p {
					break
				}
			}
			if m == 2*n+p {
				break
			}
		}
	}
}

// 402C-mic
package main

import (
	"fmt"
)

func main() {
	var t int
	var a []int
	fmt.Scan(&t)
	for pi := 0; pi < t; pi++ {
		var n, p, e, x int
		x = 1
		fmt.Scan(&n, &p)
		for e < (2*n)+p {
			i := x + 1
			for e < (2*n)+p && i <= n {
				a = append(a, x)
				a = append(a, i)
				e++
				i++
			}
			x++
		}

	}
	for i := 0; i < len(a); i += 2 {
		fmt.Println(a[i], a[i+1])
	}
}

package main

import (
    "fmt"
)

const maxn = 100

var c [][]int

var n, p int

func PrintEdge(x int, y int) {
    x, y = x%n, y%n
    c[x][y], c[y][x] = 1, 1
    fmt.Printf("%d %d\n", x+1, y+1)
}

func main() {
    var cas int
    fmt.Scanf("%d\n", &cas)
    for cas != 0 {
        cas--
        fmt.Scanf("%d %d\n", &n, &p)
        c = make([][]int, n)
        for i := 0; i < n; i++ {
            c[i] = make([]int, n)
            for j := 0; j < n; j++ {
                c[i][j] = 0
            }
        }
        for i := 0; i < n; i++ {
            PrintEdge(i, i+1)
            PrintEdge(i, i+2)
        }
        for i := 0; i < n; i++ {
            for j := 0; j < n; j++ {
                if i != j && c[i][j] == 0 && p != 0 {
                    PrintEdge(i, j)
                    p--
                }
            }
        }
    }
}

/*********************************************************************************
*     File Name           :     C.go
*     Created By          :     YIMMON, yimmon.zhuang@gmail.com
*     Creation Date       :     [2014-03-17 00:20]
*     Last Modified       :     [2014-03-17 00:27]
*     Description         :
**********************************************************************************/

package main

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

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

    var t, n, p int
    t = scanner.NextInt()
    for i := 0; i < t; i++ {
        scanner.NextInts(&n, &p)
        tmp := n + n + p
    NEXT:
        for j := 1; j <= n; j++ {
            for k := j + 1; k <= n; k++ {
                fmt.Println(j, k)
                tmp--
                if tmp == 0 {
                    break NEXT
                }
            }
        }
    }
}

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
}

func (self *Scanner) NextInts(arg ...*int) {
    for _, p := range arg {
        *p = self.NextInt()
    }
}

// 402C
package main

import (
	"fmt"
)

func main() {
	var a, n, m int
	fmt.Scan(&a)
	for ; ; a-- {
		fmt.Scan(&n, &m)
		x := 1
		y := 2
		e := 2*n + m
		for ; ; e-- {
			fmt.Println(x, y)
			y++
			if y > n {
				x++
			}
			y = x + 1
			return
		}
	}
}

// 402C-mic
package main

import (
    "fmt"
)

func main() {
    var t, n, p int
    a := 1
    fmt.Scan(&t)
    for ; t > 0; t-- {
        fmt.Scan(&n, &p)
        for i := 1; i <= n && a <= 2*n+p; i++ {
            for j := i + 1; j <= n && a <= 2*n+p; j++ {
                fmt.Println(i, j)
                a++
            }
        }
    }
}

// 402C-mic
package main

import (
	"fmt"
)

func main() {
	var t, n, p, a, i, j int32
	a = 1
	fmt.Scan(&t)
	for ; t > 0; t-- {
		fmt.Scan(&n, &p)
		for i = 1; i <= n && a <= 2*n+p; i++ {
			for j = i + 1; j <= n && a <= 2*n+p; j++ {
				fmt.Println(i, j)
				a++
			}
		}
	}
}


You are given a graph with $$$n$$$ nodes and $$$m$$$ directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is $$$3$$$. Your task is find a path whose value is the largest.

The first line contains two positive integers $$$n, m$$$ ($$$1 \leq n, m \leq 300\,000$$$), denoting that the graph has $$$n$$$ nodes and $$$m$$$ directed edges. The second line contains a string $$$s$$$ with only lowercase English letters. The $$$i$$$-th character is the letter assigned to the $$$i$$$-th node. Then $$$m$$$ lines follow. Each line contains two integers $$$x, y$$$ ($$$1 \leq x, y \leq n$$$), describing a directed edge from $$$x$$$ to $$$y$$$. Note that $$$x$$$ can be equal to $$$y$$$ and there can be multiple edges between $$$x$$$ and $$$y$$$. Also the graph can be not connected.

Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.

NoteIn the first sample, the path with largest value is $$$1 \to 3 \to 4 \to 5$$$. The value is $$$3$$$ because the letter 'a' appears $$$3$$$ times.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF919D(_r io.Reader, _w io.Writer) {
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			_r.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b || b > '9'; b = rc() {
		}
		for ; '0' <= b && b <= '9'; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	rs := func(n int) []byte {
		b := rc()
		for ; 'a' > b || b > 'z'; b = rc() {
		}
		s := make([]byte, 1, n)
		s[0] = b
		for i := 1; i < n; i++ {
			s = append(s, rc())
		}
		return s
	}
	n, m := r(), r()
	s := rs(n)
	g := make([][]int, n)
	d := make([]int, n)
	for ; m > 0; m-- {
		v, w := r()-1, r()-1
		g[v] = append(g[v], w)
		d[w]++
	}

	ans := 1
	dp := make([][26]int, n)
	q := []int{}
	for i, v := range d {
		if v == 0 {
			q = append(q, i)
			dp[i][s[i]-'a'] = 1
		}
	}
	c := 0
	for len(q) > 0 {
		v := q[0]
		q = q[1:]
		c++
		for _, w := range g[v] {
			for i, dv := range dp[w] {
				x := 0
				if byte(i) == s[w]-'a' {
					x = 1
				}
				if dv < dp[v][i]+x {
					dp[w][i] = dp[v][i] + x
					if dp[w][i] > ans {
						ans = dp[w][i]
					}
				}
			}
			d[w]--
			if d[w] == 0 {
				q = append(q, w)
			}
		}
	}
	if c < n {
		ans = -1
	}
	Fprint(_w, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF919D(_r io.Reader, _w io.Writer) {
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			_r.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b || b > '9'; b = rc() {
		}
		for ; '0' <= b && b <= '9'; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	rs := func(n int) []byte {
		b := rc()
		for ; 'a' > b || b > 'z'; b = rc() {
		}
		s := make([]byte, n)
		s[0] = b
		for i := 1; i < n; i++ {
			s[i] = rc()
		}
		return s
	}
	n, m := r(), r()
	s := rs(n)
	g := make([][]int, n)
	d := make([]int, n)
	for ; m > 0; m-- {
		v, w := r()-1, r()-1
		g[v] = append(g[v], w)
		d[w]++
	}

	ans := 1
	dp := make([][26]int, n)
	q := []int{}
	for i, v := range d {
		if v == 0 {
			q = append(q, i)
			dp[i][s[i]-'a'] = 1
		}
	}
	c := 0
	for len(q) > 0 {
		v := q[0]
		q = q[1:]
		c++
		for _, w := range g[v] {
			for i, dv := range dp[w] {
				x := 0
				if byte(i) == s[w]-'a' {
					x = 1
				}
				if dv < dp[v][i]+x {
					dp[w][i] = dp[v][i] + x
					if dp[w][i] > ans {
						ans = dp[w][i]
					}
				}
			}
			d[w]--
			if d[w] == 0 {
				q = append(q, w)
			}
		}
	}
	if c < n {
		ans = -1
	}
	Fprint(_w, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF919D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	var n, m, v, w, c int
	var s []byte
	Fscan(in, &n, &m, &s)
	g := make([][]int, n)
	d := make([]int, n)
	for ; m > 0; m-- {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		d[w]++
	}

	ans := 1
	dp := make([][26]int, n)
	q := []int{}
	for i, v := range d {
		if v == 0 {
			q = append(q, i)
			dp[i][s[i]-'a'] = 1
		}
	}
	for len(q) > 0 {
		v, q = q[0], q[1:]
		c++
		for _, w := range g[v] {
			for i, dv := range dp[w] {
				x := 0
				if byte(i) == s[w]-'a' {
					x = 1
				}
				if dv < dp[v][i]+x {
					dp[w][i] = dp[v][i] + x
					if dp[w][i] > ans {
						ans = dp[w][i]
					}
				}
			}
			d[w]--
			if d[w] == 0 {
				q = append(q, w)
			}
		}
	}
	if c < n {
		ans = -1
	}
	Fprint(_w, ans)
}

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

package main

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

var n, m int
var alpha string
var graph [][]int
var used []bool
var ok []bool
var counts [][26]int
var best int

func dfs(v int) {
	used[v] = true
	for _, g := range graph[v] {
		if !used[g] {
			dfs(g)
		}
		for j := 0; j < 26; j++ {
			if counts[v][j] < counts[g][j] {
				counts[v][j] = counts[g][j]
			}
		}
	}
	counts[v][alpha[v] - 'a']++
}

func cycle(v int) bool {
	used[v] = true
	c := false
	for _, vnext := range graph[v] {
		if used[vnext] {
			return true
		}
		if !ok[vnext] {
			c = cycle(vnext)
			if c {
				return c
			}
		}
	}
	used[v] = false
	ok[v] = true
	return false
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n%s\n", &n, &m, &alpha)
	graph = make([][]int, n)
	used = make([]bool, n)
	ok = make([]bool, n)
	counts = make([][26]int, n)
	for i := 0; i < m; i++ {
		var t1, t2 int
		fmt.Fscanf(buf, "%d %d\n", &t1, &t2)
		t1--
		t2--
		if t1 == t2 {
			fmt.Println(-1)
			return
		}

		graph[t1] = append(graph[t1], t2)
	}
	for i := 0; i < n; i++ {
		if !ok[i] && cycle(i) {
			fmt.Println("-1")
			return
		}
	}
	for i := 0; i < n; i++ {
		used[i] = false
	}
	for i := 0; i < n; i++ {
		if !used[i] {
			dfs(i)
		}
		for j := 0; j < 26; j++ {
			if counts[i][j] > best {
				best = counts[i][j]
			}
		}
	}
	fmt.Println(best)
}

package main

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

var n, m int
var alpha string
var graph [][]int
var used []bool
var ok []bool
var counts [][26]int
var best int

func dfs(v int) {
	used[v] = true
	for _, g := range graph[v] {
		if !used[g] {
			dfs(g)
			for j := 0; j < 26; j++ {
				if counts[v][j] < counts[g][j] {
					counts[v][j] = counts[g][j]
				}
			}
		}
	}
	counts[v][alpha[v] - 'a']++
}

func cycle(v int) bool {
	used[v] = true
	c := false
	for _, vnext := range graph[v] {
		if used[vnext] {
			return true
		}
		if !ok[vnext] {
			c = cycle(vnext)
			if c {
				return c
			}
		}
	}
	used[v] = false
	ok[v] = true
	return false
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n%s\n", &n, &m, &alpha)
	graph = make([][]int, n)
	used = make([]bool, n)
	ok = make([]bool, n)
	counts = make([][26]int, n)
	for i := 0; i < m; i++ {
		var t1, t2 int
		fmt.Fscanf(buf, "%d %d\n", &t1, &t2)
		t1--
		t2--
		if t1 == t2 {
			fmt.Println(-1)
			return
		}

		graph[t1] = append(graph[t1], t2)
	}
	for i := 0; i < n; i++ {
		if !ok[i] && cycle(i) {
			fmt.Println("-1")
			return
		}
	}
	for i := 0; i < n; i++ {
		used[i] = false
	}
	for i := 0; i < n; i++ {
		if !used[i] {
			dfs(i)
		}
		for j := 0; j < 26; j++ {
			if counts[i][j] > best {
				best = counts[i][j]
			}
		}
	}
	fmt.Println(best)
}

package main

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

var n, m int
var alpha string
var graph [][]int
var used []bool
var ok []bool
var counts [][26]int
var best int

func dfs(v int) {
	counts[v][alpha[v] - 'a']++
	used[v] = true
	for _, g := range graph[v] {
		if !used[g] {
			dfs(g)
			for j := 0; j < 26; j++ {
				counts[v][j] += counts[g][j]
			}
		}
	}
}

func cycle(v int) bool {
	used[v] = true
	c := false
	for _, vnext := range graph[v] {
		if !ok[vnext] {
			if used[vnext] {
				return true
			}
			c = c && cycle(vnext)
			if !c {
				return c
			}
		}
	}
	used[v] = false
	ok[v] = true
	return false
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d %d\n%s\n", &n, &m, &alpha)
	graph = make([][]int, n)
	used = make([]bool, n)
	ok = make([]bool, n)
	counts = make([][26]int, n)
	for i := 0; i < m; i++ {
		var t1, t2 int
		fmt.Fscanf(buf, "%d %d\n", &t1, &t2)
		t1--
		t2--
		graph[t1] = append(graph[t1], t2)
	}
	for i := 0; i < n; i++ {
		if !used[i] && cycle(i) {
			fmt.Println("-1")
			return
		}
	}
	for i := 0; i < n; i++ {
		used[i] = false
	}
	for i := 0; i < n; i++ {
		if !used[i] {
			dfs(i)
		}
		for j := 0; j < 26; j++ {
			if counts[i][j] > best {
				best = counts[i][j]
			}
		}
	}
	fmt.Println(best)
}