This is the hard version of the problem. The only difference is the constraints on $$$n$$$ and $$$k$$$. You can make hacks only if all versions of the problem are solved.You have a string $$$s$$$, and you can do two types of operations on it:   Delete the last character of the string.  Duplicate the string: $$$s:=s+s$$$, where $$$+$$$ denotes concatenation. You can use each operation any number of times (possibly none).Your task is to find the lexicographically smallest string of length exactly $$$k$$$ that can be obtained by doing these operations on string $$$s$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:  $$$a$$$ is a prefix of $$$b$$$, but $$$a\ne b$$$;  In the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first line contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 5\cdot 10^5$$$) — the length of the original string $$$s$$$ and the length of the desired string. The second line contains the string $$$s$$$, consisting of $$$n$$$ lowercase English letters.

Print the lexicographically smallest string of length $$$k$$$ that can be obtained by doing the operations on string $$$s$$$.

NoteIn the first test, it is optimal to make one duplication: "dbcadabc" $$$\to$$$ "dbcadabcdbcadabc".In the second test it is optimal to delete the last $$$3$$$ characters, then duplicate the string $$$3$$$ times, then delete the last $$$3$$$ characters to make the string have length $$$k$$$."abcd" $$$\to$$$ "abc" $$$\to$$$ "ab" $$$\to$$$ "a" $$$\to$$$ "aa" $$$\to$$$ "aaaa" $$$\to$$$ "aaaaaaaa" $$$\to$$$ "aaaaaaa" $$$\to$$$ "aaaaaa" $$$\to$$$ "aaaaa".

package main

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

const (
	MOD int = 1e9+7
	NL byte = byte('\n')
	SP byte = byte(' ')
)

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

	n, k int
	s string
	res int
)

func main() {
	initBuffer()
	var t int = 1
	// t = getInt()
	for i := 0; i < t; i++ {
		solve()
	}
	// test()
	out.Flush()
}

func solve() {
	initialize()
	input()
	count()
	output()
}

func initialize() {

}

func input() {
	n = getInt()
	k = getInt()
	s = getString()
}

func count() {
	var arr []int = make([]int, n)
	for i := 1; i < n; i++ {
		if arr[i] > arr[0] {
			res = i
			return
		}
		arr[i] = arr[i-1]
		for arr[i] > 0 && s[i] != s[arr[i]%(i-arr[i])] {
			if s[i] < s[arr[i]%(i-arr[i])] {
				arr[i] = arr[arr[i]-1]
			} else {
				break
			}
		}
		if s[i] == s[arr[i]%(i-arr[i])] {
			arr[i]++
		} else if s[i] > s[arr[i]%(i-arr[i])] {
			res = i - arr[i]
			return
		}
	}
	res = n - arr[n-1]
	for i := 0; i < n; i++ {
		if s[i%res] < s[(res+i)%n] {
			return
		}
	}
	res = n
}

func output() {
	for i := 0; i < k / res; i++ {
		out.WriteString(s[:res])
	}
	out.WriteString(s[:k%res])
}

func test() {
	fmt.Print()
}

func initBuffer() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer([]byte{}, 4 * 1024 * 1024)
	in.Split(scanWords)
	out = bufio.NewWriter(os.Stdout)
}

func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	i := bytes.IndexByte(data, '\n')
	j := bytes.IndexByte(data, ' ')
	ind := min(i, j)
	if ind < 0 {
		ind = max(i, j)
	}
	if ind >= 0 {
		return ind + 1, dropCR(data[0:ind]), nil
	}
	if atEOF {
		return len(data), dropCR(data), nil
	}
	return 0, nil, nil
}

func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[:len(data)-1]
	}
	return data
}

func getFloat() float64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res1 int64
	for i := 0; i < len(b); i++ {
		if b[i] == '.' {
			b = b[i+1:]
			break
		}
		res1 *= 10
		res1 += int64(b[i]) - 48
		if i == len(b) - 1 {
			b = b[:0]
		}
	}
	var res2 float64
	for i := len(b); i > 0; i-- {
		res2 += float64(b[i-1]) - 48
		res2 /= 10
	}
	if isNeg {
		res1 *= -1
		res2 *= -1
	}
	return float64(res1) + res2
}

func getInt() int {
	return int(getInt64())
}

func getInt64() int64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res int64
	for i := 0; i < len(b); i++ {
		res *= 10
		res += int64(b[i]) - 48
	}
	if isNeg {
		res *= -1
	}
	return res
}

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

func intToBytes(n int) []byte {
	return int64ToBytes(int64(n))
}

func int64ToBytes(n int64) []byte {
	var res [65]byte
	var isNeg bool
	if n < 0 {
		isNeg = true
		n = -n
	}
	var l int = 65
	for n > 0 {
		l--
		res[l] = byte(n % 10 + 48)
		n /= 10
	}
	if l == 65 {
		l--
		res[l] = byte(48)
	}
	if isNeg {
		l--
		res[l] = byte(45)
	}
	return res[l:]
}

func bsLower(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsLower64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsUpper(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func bsUpper64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func max(n1, n2 int) int {
	return int(max64(int64(n1), int64(n2)))
}

func max64(n1, n2 int64) int64 {
	if n1 > n2 {
		return n1
	}
	return n2
}

func min(n1, n2 int) int {
	return int(min64(int64(n1), int64(n2)))
}

func min64(n1, n2 int64) int64 {
	if n1 < n2 {
		return n1
	}
	return n2
}

func yes(res, isUpperCase bool) bool {
	var arr [4]string = [4]string{"No", "Yes", "NO", "YES"}
	var ind int
	if res == true {
		ind = 1
	}
	if isUpperCase == true {
		ind += 2
	}
	out.WriteString(arr[ind])
	out.WriteByte(NL)
	return res
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1537E2(in io.Reader, out io.Writer) {
	var n, k int
	var s string
	Fscan(bufio.NewReader(in), &n, &k, &s)
	sz := 1
	for i := range s {
		if s[i] > s[i%sz] {
			break
		}
		if s[i] < s[i%sz] {
			sz = i + 1
		}
	}
	Fprint(out, strings.Repeat(s[:sz], k/sz+1)[:k])
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1537E2(in io.Reader, out io.Writer) {
	var n, k int
	var s string
	Fscan(bufio.NewReader(in), &n, &k, &s)
	sz := 1
	for i := range s {
		if s[i] > s[i%sz] {
			break
		}
		if s[i] < s[i%sz] {
			sz = i + 1
		}
	}
	Fprint(out, strings.Repeat(s[:sz], k/sz+1)[:k])
}

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

package main

import (
	"bufio"
	"bytes"
	. "fmt"
	"index/suffixarray"
	"io"
	"math/bits"
	"os"
	"reflect"
	"unsafe"
)

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
//time2.Sleep(time2.Hour)
	var n, k int
	var s []byte
	Fscan(in, &n, &k, &s)
	if k < n {
		s = s[:k]
		n = k
	}
	s = append(s, s...)
	sa := *(*[]int32)(unsafe.Pointer(reflect.ValueOf(suffixarray.New(s)).Elem().FieldByName("sa").Field(0).UnsafeAddr()))

	oriN := n
	n = len(s)

	rank := make([]int, n)
	for i := range rank {
		rank[sa[i]] = i
	}

	height := make([]int, n)
	h := 0
	for i, rk := range rank {
		if h > 0 {
			h--
		}
		if rk > 0 {
			for j := int(sa[rk-1]); i+h < n && j+h < n && s[i+h] == s[j+h]; h++ {
			}
		}
		height[rk] = h
	}

	const mx = 20
	st := make([][mx]int, n)
	for i, v := range height {
		st[i][0] = v
	}
	for j := 1; 1<<j <= n; j++ {
		for i := 0; i+1<<j <= n; i++ {
			st[i][j] = min(st[i][j-1], st[i+1<<(j-1)][j-1])
		}
	}
	_q := func(l, r int) int { k := bits.Len(uint(r-l)) - 1; return min(st[l][k], st[r-1<<k][k]) }
	lcp := func(i, j int) int {
		if i == j {
			return n - i
		}
		ri, rj := rank[i], rank[j]
		if ri > rj {
			ri, rj = rj, ri
		}
		return _q(ri+1, rj+1)
	}

	compareSub2 := func(l1, r1, l2, r2 int) int {
		len1, len2 := r1-l1, r2-l2
		l := lcp(l1, l2)
		if len1 == len2 && l == len1 {
			return 0
		}
		if l >= len1 || l >= len2 {
			if len1 < len2 {
				return -1
			}
			return 1
		}
		if rank[l1] < rank[l2] {
			return -1
		}
		return 1
	}
	ansI := oriN
o:
	for r1 := 1; r1 < oriN; r1++ {
		for l2 := r1; l2 < oriN; l2 += r1 {
			r2 := l2 + r1
			res := compareSub2(0, r1, l2, r2)
			if res > 0 {
				continue o
			}
			if res < 0 {
				ansI = r1
				break o
			}
		}
	}
	time := (k-1)/ansI + 1
	ans := bytes.Repeat(s[:ansI], time)
	if len(ans) > k {
		ans = ans[:k]
	}
	Fprintf(out, "%s", ans)
}

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

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

package main

import (
	"bufio"
	"bytes"
	. "fmt"
	"index/suffixarray"
	"io"
	"math/bits"
	"os"
	"reflect"
	"unsafe"
)

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

	var n, k int
	var s []byte
	Fscan(in, &n, &k, &s)
	if k < n {
		s = s[:k]
		n = k
	}
	s = append(s, s...)
	sa := *(*[]int32)(unsafe.Pointer(reflect.ValueOf(suffixarray.New(s)).Elem().FieldByName("sa").Field(0).UnsafeAddr()))

	oriN := n
	n = len(s)

	rank := make([]int, n)
	for i := range rank {
		rank[sa[i]] = i
	}

	height := make([]int, n)
	h := 0
	for i, rk := range rank {
		if h > 0 {
			h--
		}
		if rk > 0 {
			for j := int(sa[rk-1]); i+h < n && j+h < n && s[i+h] == s[j+h]; h++ {
			}
		}
		height[rk] = h
	}

	const mx = 20
	st := make([][mx]int, n)
	for i, v := range height {
		st[i][0] = v
	}
	for j := 1; 1<<j <= n; j++ {
		for i := 0; i+1<<j <= n; i++ {
			st[i][j] = min(st[i][j-1], st[i+1<<(j-1)][j-1])
		}
	}
	_q := func(l, r int) int { k := bits.Len(uint(r-l)) - 1; return min(st[l][k], st[r-1<<k][k]) }
	lcp := func(i, j int) int {
		if i == j {
			return n - i
		}
		ri, rj := rank[i], rank[j]
		if ri > rj {
			ri, rj = rj, ri
		}
		return _q(ri+1, rj+1)
	}

	compareSub2 := func(l1, r1, l2, r2 int) int {
		len1, len2 := r1-l1, r2-l2
		l := lcp(l1, l2)
		if len1 == len2 && l == len1 {
			return 0
		}
		if l >= len1 || l >= len2 {
			if len1 < len2 {
				return -1
			}
			return 1
		}
		if rank[l1] < rank[l2] {
			return -1
		}
		return 1
	}
	ansI := oriN
o:
	for r1 := 1; r1 < oriN; r1++ {
		for l2 := r1; l2 < oriN; l2 += r1 {
			r2 := l2 + r1
			res := compareSub2(0, r1, l2, r2)
			if res > 0 {
				continue o
			}
			if res < 0 {
				ansI = r1
				break o
			}
		}
	}
	time := (k-1)/ansI + 1
	ans := bytes.Repeat(s[:ansI], time)
	if len(ans) > k {
		ans = ans[:k]
	}
	Fprintf(out, "%s", ans)
}

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

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

package main

import (
	"bufio"
	"bytes"
	. "fmt"
	"index/suffixarray"
	"io"
	"math/bits"
	"os"
	"reflect"
	"unsafe"
)

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

	var n, k int
	var s []byte
	Fscan(in, &n, &k, &s)
	if k < n {
		s = s[:k]
		n = k
	}
	s = append(s, s...)
	sa := *(*[]int32)(unsafe.Pointer(reflect.ValueOf(suffixarray.New(s)).Elem().FieldByName("sa").Field(0).UnsafeAddr()))

	oriN := n
	n = len(s)

	rank := make([]int, n)
	for i := range rank {
		rank[sa[i]] = i
	}

	height := make([]int, n)
	h := 0
	for i, rk := range rank {
		if h > 0 {
			h--
		}
		if rk > 0 {
			for j := int(sa[rk-1]); i+h < n && j+h < n && s[i+h] == s[j+h]; h++ {
			}
		}
		height[rk] = h
	}

	const mx = 20
	st := make([][mx]int, n)
	for i, v := range height {
		st[i][0] = v
	}
	for j := 1; 1<<j <= n; j++ {
		for i := 0; i+1<<j <= n; i++ {
			st[i][j] = min(st[i][j-1], st[i+1<<(j-1)][j-1])
		}
	}
	_q := func(l, r int) int { k := bits.Len(uint(r-l)) - 1; return min(st[l][k], st[r-1<<k][k]) }
	lcp := func(i, j int) int {
		if i == j {
			return n - i
		}
		ri, rj := rank[i], rank[j]
		if ri > rj {
			ri, rj = rj, ri
		}
		return _q(ri+1, rj+1)
	}

	// 比较两个子串 s[l1:r1] s[l2:r2]
	//compareSub := func(l1, r1, l2, r2 int) bool {
	//	len1, len2 := r1-l2, r2-l2
	//	if l := lcp(l1, l2); l >= len1 || l >= len2 { // 一个是另一个的前缀
	//		return len1 < len2
	//	}
	//	return rank[l1] < rank[l2] // 或者 s[l1+l] < s[l2+l]
	//}

	compareSub2 := func(l1, r1, l2, r2 int) int {
		len1, len2 := r1-l1, r2-l2
		l := lcp(l1, l2)
		if len1 == len2 && l == len1 {
			return 0
		}
		if l >= len1 || l >= len2 {
			if len1 < len2 {
				return -1
			}
			return 1
		}
		// s[l1+l] < s[l2+l]
		if rank[l1] < rank[l2] {
			return -1
		}
		return 1
	}
	ansI := oriN
o:
	for r1 := 1; r1 < oriN; r1++ {
		for l2 := r1; l2 < oriN; l2 += r1 {
			r2 := l2 + r1
			//if r2 <= n {
				res := compareSub2(0, r1, l2, r2)
				if res > 0 {
					continue o
				} else if res < 0 {
					ansI = r1
					break o
				}
			//} else {
			//	res := compareSub2(0, n-l2, l2, n)
			//	if res > 0 {
			//		continue o
			//	} else if res < 0 {
			//		ansI = r1
			//		break o
			//	}
			//}
		}
	}
	time := (k-1)/ansI + 1
	ans := bytes.Repeat(s[:ansI], time)
	if len(ans) > k {
		ans = ans[:k]
	}
	Fprintf(out, "%s", ans)
}

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

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

package main

import (
	"fmt"
	"strings"
)

/*
https://codeforces.com/problemset/problem/1537/E1
https://codeforces.com/problemset/problem/1537/E2

本题分为简单版本和困难版本，在困难版本中，n 和 k 不超过 5e5。

输入 n (≤5000) 和 k (≤5000)，以及一个长为 n 的字符串 s，由小写字母组成。

有如下两种操作，每种操作你都可以执行任意多次：
1. 删除 s 的最后一个字符；
2. 将 s 复制一份拼在后面，即 s = s + s。

输出你能得到的所有长为 k 的字符串中，字典序最小的字符串。
 */
func samllstr(n int, str string, k int) string{
	start := 0
	end := 1
	for ; end < n ;{
		if str[end] > str[start] {
			break
		}else if str[end] < str[start] {
			end++
			continue
		}else {
			flag := 0
			i,j := start+1, end+1
			for  ;i < end && j < n; i, j = i+1, j+1 {
				if str[i] < str[j] {
					flag = 1
					break//end-1为止
				}
				if str[i] > str[j] {
					flag = 2
					break
				}
			}
			if flag == 1  {
				break
			}
			if flag == 2 {
				end = j+1
			}else {
				if i == end {
					end = j
				}else {
					break
				}
			}
		}
	}/*
	5 10
	dcdcd
	Output
	dcdcddcdcd
	Answer
	dcdcdcdcdc
	Checker Log
	*/
	length := end-start
	return strings.Repeat(str[start:end], k/length) + str[:k%length]
}
/*
输入
8 16
dbcadabc
输出
dbcadabcdbcadabc
解释 复制一次

输入
4 5
abcd
输出
aaaaa

 */
func main() {
	var n, k int
	var str string
	fmt.Scan(&n, &k, &str)
	fmt.Printf("%v\n", samllstr(n,str, k))
}

package main

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

var _rbuf = bufio.NewReader(os.Stdin)
var _wbuf = bufio.NewWriter(os.Stdout)

func scan(a ...interface{})             { _wbuf.Flush(); fmt.Fscan(_rbuf, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(_wbuf, f, a...) }

func main() {
	defer _wbuf.Flush()

	var n, k int
	var str string

	scan(&n, &k)
	scan(&str)

	printf("%s\n", solve(n, k, str))
}

func solve(n, k int, str string) string {
	rnk := make([]int, n+n)
	oldRnk := make([]int, n+n)
	sa := make([]int, n)
	sa2 := make([]int, n)
	cnt := make([]int, n+26)

	for i := n; i < n+n; i++ {
		rnk[i] = n
	}
	for i := 0; i < n; i++ {
		rnk[i] = int(str[i] - 'a')
		cnt[rnk[i]]++
	}
	for i := 1; i <= 26; i++ {
		cnt[i] += cnt[i-1]
	}
	for i := n - 1; i >= 0; i-- {
		cnt[rnk[i]]--
		sa[cnt[rnk[i]]] = i
	}
	for b := 1; b < n; b += b {
		var rank int
		for i := 0; i < n; i++ {
			if sa[i] >= b {
				sa2[rank] = sa[i] - b
				rank++
			}
		}
		for i := n - b; i < n; i++ {
			sa2[rank] = i
			rank++
		}
		for i := 0; i <= n; i++ {
			cnt[i] = 0
		}
		for i := 0; i < n; i++ {
			cnt[rnk[sa2[i]]]++
		}
		for i := 1; i <= n; i++ {
			cnt[i] += cnt[i-1]
		}
		for i := n - 1; i >= 0; i-- {
			cnt[rnk[sa2[i]]]--
			sa[cnt[rnk[sa2[i]]]] = sa2[i]
		}
		copy(oldRnk, rnk)
		rank = 0
		for i := 0; i < n; i++ {
			if i > 0 &&
				(oldRnk[sa[i]] != oldRnk[sa[i-1]] || oldRnk[sa[i]+b] != oldRnk[sa[i-1]+b]) {
				rank++
			}
			rnk[sa[i]] = rank
		}
	}

	//for i := 0; i < n; i++ {
	//	println(str[sa[i]:])
	//}

	ret := str
	for i := 1; i < n; i++ {
		if rnk[i] > rnk[0] {
			ret = str[:i]
			break
		}
	}
	for len(ret) < k {
		ret += ret
	}
	return ret[:k]
}

package main

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

var _rbuf = bufio.NewReader(os.Stdin)
var _wbuf = bufio.NewWriter(os.Stdout)

func scan(a ...interface{})             { _wbuf.Flush(); fmt.Fscan(_rbuf, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(_wbuf, f, a...) }

func main() {
	defer _wbuf.Flush()

	var n, k int
	var str string

	scan(&n, &k)
	scan(&str)

	printf("%s\n", solve(n, k, str))
}

func solve(n, k int, str string) string {
	rnk := make([]int, n+n)
	oldRnk := make([]int, n+n)
	sa := make([]int, n)
	oldSa := make([]int, n)
	cnt := make([]int, n+26)

	for i := n; i < n+n; i++ {
		rnk[i] = n
	}
	for i := 0; i < n; i++ {
		rnk[i] = int(str[i] - 'a')
		cnt[rnk[i]]++
	}
	for i := 1; i <= 26; i++ {
		cnt[i] += cnt[i-1]
	}
	for i := n - 1; i >= 0; i-- {
		cnt[rnk[i]]--
		sa[cnt[rnk[i]]] = i
	}
	for b := 1; b < n; b += b {
		for i := 0; i <= n; i++ {
			cnt[i] = 0
		}
		copy(oldSa, sa)
		for i := 0; i < n; i++ {
			cnt[rnk[oldSa[i]+b]]++
		}
		for i := 1; i <= n; i++ {
			cnt[i] += cnt[i-1]
		}
		for i := n - 1; i >= 0; i-- {
			cnt[rnk[oldSa[i]+b]]--
			sa[cnt[rnk[oldSa[i]+b]]] = oldSa[i]
		}
		for i := 0; i <= n; i++ {
			cnt[i] = 0
		}
		copy(oldSa, sa)
		for i := 0; i < n; i++ {
			cnt[rnk[oldSa[i]]]++
		}
		for i := 1; i <= n; i++ {
			cnt[i] += cnt[i-1]
		}
		for i := n - 1; i >= 0; i-- {
			cnt[rnk[oldSa[i]]]--
			sa[cnt[rnk[oldSa[i]]]] = oldSa[i]
		}
		copy(oldRnk, rnk)
		var rank int
		for i := 0; i < n; i++ {
			if i > 0 &&
				(oldRnk[sa[i]] != oldRnk[sa[i-1]] || oldRnk[sa[i]+b] != oldRnk[sa[i-1]+b]) {
				rank++
			}
			rnk[sa[i]] = rank
		}
	}

	ret := str
	for i := 1; i < n; i++ {
		if rnk[i] > rnk[0] {
			ret = str[:i]
			break
		}
	}

	for len(ret) < k {
		ret += ret
	}
	return ret[:k]
}

package main

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

var (
	in   *bufio.Reader = bufio.NewReader(os.Stdin)
	n, k int
	s    string
)

func main() {
	fmt.Fscan(in, &n, &k, &s)
	sz := 1
	for i := range s {
		if s[i] > s[i%sz] {
			break
		}
		if s[i] < s[i%sz] {
			sz = i + 1
		}
	}
	ans := strings.Repeat(s[:sz], k/sz+1)[:k]
	fmt.Println(ans)
}

package main

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

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

func CF1537E(in io.Reader, out io.Writer) {
	r := bufio.NewReader(in)
	w := bufio.NewWriter(out)
	defer w.Flush()

	var n, k int
	var s string
	fmt.Fscan(r, &n, &k, &s)
	sz := 1
	for i := range s {
		if s[i] > s[i%sz] {
			break
		}
		if s[i] < s[i%sz] {
			sz = i + 1
		}
	}
	fmt.Fprint(w, strings.Repeat(s[:sz], k/sz+1)[:k])
}

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

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

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

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

package main

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

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

func NewIO(in io.Reader, out io.Writer) *IO {
	return &IO{in: bufio.NewReader(in), out: out}
}

func (io *IO) ReadInt() int {
	var res int
	fmt.Fscanf(io.in, "%d\n", &res)
	return res
}

func (io *IO) ReadPairInt() (int, int) {
	var a, b int
	fmt.Fscanf(io.in, "%d %d\n", &a, &b)
	return a, b
}

func (io *IO) ReadString() string {
	var res string
	fmt.Fscanf(io.in, "%s\n", &res)
	return res
}

func (io *IO) ReadIntSlice(n int) sort.IntSlice {
	var t int
	res := make(sort.IntSlice, 0, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(io.in, "%d", &t)
		res = append(res, t)
	}
	fmt.Fscanf(io.in, "\n")
	return res
}

func (io *IO) ReadByteSlice(n int) []byte {
	res := make([]byte, 0, n)
	fmt.Fscanf(io.in, "%s\n", &res)
	return res
}

func (io *IO) Println(v ...interface{}) {
	fmt.Fprintln(io.out, v...)
}

func (io *IO) Print(v ...interface{}) {
	fmt.Fprint(io.out, v...)
}

func (io *IO) Printf(format string, v ...interface{}) {
	fmt.Fprintf(io.out, format, v...)
}

func (io *IO) PrintIntSlice(s sort.IntSlice) {
	for _, v := range s {
		io.Printf("%d ", v)
	}
}

func (io *IO) PrintlnIntSlice(s sort.IntSlice) {
	io.PrintIntSlice(s)
	io.Printf("\n")
}

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

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

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

func zFunction(a []byte) []int {
	res := make([]int, len(a))
	l, r := 0, 0

	for i := 1; i < len(a); i++ {
		if i <= r {
			res[i] = min(r-i+1, res[i-l])
		}
		for i+res[i] < len(a) && a[res[i]] == a[i+res[i]] {
			res[i]++
		}
		if i+res[i]-1 > r {
			l = i
			r = i + res[i] - 1
		}
	}

	return res
}

func concatBytes (a ...[]byte) []byte {
	size := 0
	for _, v := range a {
		size += len(v)
	}

	res := make([]byte, size)

	size = 0
	for _, v := range a {
		size += copy(res[size:], v)
	}

	return res
}

//func findMinString(a, b []byte, mn int) []byte {
//	uh := concatBytes(b, []byte{'|'}, a, b)
//	z := zFunction(uh)
//	size := len(a)
//
//	for i := mn; i < size; i++ {
//		if a[i] > b[0] {
//			return concatBytes(a[:i], b[:i])
//		} else if a[i] < b[0] {
//			continue
//		} else {
//			k := z[size + 1 + i]
//			if k >= i - 2 {
//				return concatBytes(a[:i], b[:i])
//			} else if uh[size + 1 + i + k] < uh[k] {
//				return concatBytes(a, b)
//			} else if uh[size + 1 + i + k] > uh[k] {
//				return concatBytes(a[:i], b[:i])
//			}
//		}
//	}
//
//	return concatBytes(a, b)
//}

func getAns(a []byte, k int) []byte {
	mp := k / len(a)
	if k % len(a) != 0 {
		mp++
	}
	res := make([]byte, len(a) * mp)
	for i := 0; i < mp; i++ {
		copy(res[i * len(a):], a)
	}
	return res[:k]
}

func main() {
	io := NewIO(os.Stdin, os.Stdout)

	n, k := io.ReadPairInt()
	a := io.ReadByteSlice(n)

	uh := concatBytes(a, []byte{'|'}, a, a)
	z := zFunction(uh)

	for i := 1; i < len(a); i++ {
		//fmt.Println(i)
		if a[i] > a[0] {
			a = a[:i]
			break
		} else if a[i] < a[0] {
			continue
		} else {
			zz := z[len(a) + 1 + i]
			if zz == len(a) {
				break
			}
			if a[zz] < uh[len(a) + 1 + i + zz] {
				a = a[:i]
				break
			} else {
				continue
			}
		}
	}
	a = getAns(a, k)

	io.Println(string(a))
}

package main

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

const (
	MOD int = 1e9+7
	NL byte = byte('\n')
	SP byte = byte(' ')
)

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

	n, k int
	s string
	res int
)

func main() {
	initBuffer()
	var t int = 1
	// t = getInt()
	for i := 0; i < t; i++ {
		solve()
	}
	// test()
	out.Flush()
}

func solve() {
	initialize()
	input()
	count()
	output()
}

func initialize() {

}

func input() {
	n = getInt()
	k = getInt()
	s = getString()
}

func count() {
	var arr []int = make([]int, n)
	for i := 1; i < n; i++ {
		if arr[i] > arr[0] {
			res = i
			return
		}
		arr[i] = arr[i-1]
		for arr[i] > 0 && s[i] != s[arr[i]%(i-arr[i])] {
			if s[i] < s[arr[i]%(i-arr[i])] {
				arr[i] = arr[arr[i]-1]
			} else {
				break
			}
		}
		if s[i] == s[arr[i]%(i-arr[i])] {
			arr[i]++
		} else if s[i] > s[arr[i]%(i-arr[i])] {
			res = i - arr[i]
			return
		}
	}
	res = n - arr[n-1]
	for i := 0; i < res; i++ {
		if s[i%res] < s[(res+i)%n] {
			return
		}
	}
	res = n
}

func output() {
	for i := 0; i < k / res; i++ {
		out.WriteString(s[:res])
	}
	out.WriteString(s[:k%res])
}

func test() {
	fmt.Print()
}

func initBuffer() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer([]byte{}, 4 * 1024 * 1024)
	in.Split(scanWords)
	out = bufio.NewWriter(os.Stdout)
}

func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	i := bytes.IndexByte(data, '\n')
	j := bytes.IndexByte(data, ' ')
	ind := min(i, j)
	if ind < 0 {
		ind = max(i, j)
	}
	if ind >= 0 {
		return ind + 1, dropCR(data[0:ind]), nil
	}
	if atEOF {
		return len(data), dropCR(data), nil
	}
	return 0, nil, nil
}

func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[:len(data)-1]
	}
	return data
}

func getFloat() float64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res1 int64
	for i := 0; i < len(b); i++ {
		if b[i] == '.' {
			b = b[i+1:]
			break
		}
		res1 *= 10
		res1 += int64(b[i]) - 48
		if i == len(b) - 1 {
			b = b[:0]
		}
	}
	var res2 float64
	for i := len(b); i > 0; i-- {
		res2 += float64(b[i-1]) - 48
		res2 /= 10
	}
	if isNeg {
		res1 *= -1
		res2 *= -1
	}
	return float64(res1) + res2
}

func getInt() int {
	return int(getInt64())
}

func getInt64() int64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res int64
	for i := 0; i < len(b); i++ {
		res *= 10
		res += int64(b[i]) - 48
	}
	if isNeg {
		res *= -1
	}
	return res
}

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

func intToBytes(n int) []byte {
	return int64ToBytes(int64(n))
}

func int64ToBytes(n int64) []byte {
	var res [65]byte
	var isNeg bool
	if n < 0 {
		isNeg = true
		n = -n
	}
	var l int = 65
	for n > 0 {
		l--
		res[l] = byte(n % 10 + 48)
		n /= 10
	}
	if l == 65 {
		l--
		res[l] = byte(48)
	}
	if isNeg {
		l--
		res[l] = byte(45)
	}
	return res[l:]
}

func bsLower(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsLower64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsUpper(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func bsUpper64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func max(n1, n2 int) int {
	return int(max64(int64(n1), int64(n2)))
}

func max64(n1, n2 int64) int64 {
	if n1 > n2 {
		return n1
	}
	return n2
}

func min(n1, n2 int) int {
	return int(min64(int64(n1), int64(n2)))
}

func min64(n1, n2 int64) int64 {
	if n1 < n2 {
		return n1
	}
	return n2
}

func yes(res, isUpperCase bool) bool {
	var arr [4]string = [4]string{"No", "Yes", "NO", "YES"}
	var ind int
	if res == true {
		ind = 1
	}
	if isUpperCase == true {
		ind += 2
	}
	out.WriteString(arr[ind])
	out.WriteByte(NL)
	return res
}

package main

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

const (
	MOD int = 1e9+7
	NL byte = byte('\n')
	SP byte = byte(' ')
)

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

	n, k int
	s string
	res int
)

func main() {
	initBuffer()
	var t int = 1
	// t = getInt()
	for i := 0; i < t; i++ {
		solve()
	}
	// test()
	out.Flush()
}

func solve() {
	initialize()
	input()
	count()
	output()
}

func initialize() {

}

func input() {
	n = getInt()
	k = getInt()
	s = getString()
}

func count() {
	var arr []int = make([]int, n)
	for i := 1; i < n; i++ {
		if arr[i] > arr[0] {
			res = i
			return
		}
		arr[i] = arr[i-1]
		for arr[i] > 0 && s[i] != s[arr[i]%(i-arr[i])] {
			if s[i] < s[arr[i]%(i-arr[i])] {
				arr[i] = arr[arr[i]-1]
			} else {
				break
			}
		}
		if s[i] == s[arr[i]%(i-arr[i])] {
			arr[i]++
		} else if s[i] > s[arr[i]%(i-arr[i])] {
			res = i - arr[i]
			return
		}
	}
	res = n - arr[n-1]
	if res < n && s[0] < s[res] {
		return
	}
	res = n
}

func output() {
	for i := 0; i < k / res; i++ {
		out.WriteString(s[:res])
	}
	out.WriteString(s[:k%res])
}

func test() {
	fmt.Print()
}

func initBuffer() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer([]byte{}, 4 * 1024 * 1024)
	in.Split(scanWords)
	out = bufio.NewWriter(os.Stdout)
}

func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	i := bytes.IndexByte(data, '\n')
	j := bytes.IndexByte(data, ' ')
	ind := min(i, j)
	if ind < 0 {
		ind = max(i, j)
	}
	if ind >= 0 {
		return ind + 1, dropCR(data[0:ind]), nil
	}
	if atEOF {
		return len(data), dropCR(data), nil
	}
	return 0, nil, nil
}

func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[:len(data)-1]
	}
	return data
}

func getFloat() float64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res1 int64
	for i := 0; i < len(b); i++ {
		if b[i] == '.' {
			b = b[i+1:]
			break
		}
		res1 *= 10
		res1 += int64(b[i]) - 48
		if i == len(b) - 1 {
			b = b[:0]
		}
	}
	var res2 float64
	for i := len(b); i > 0; i-- {
		res2 += float64(b[i-1]) - 48
		res2 /= 10
	}
	if isNeg {
		res1 *= -1
		res2 *= -1
	}
	return float64(res1) + res2
}

func getInt() int {
	return int(getInt64())
}

func getInt64() int64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res int64
	for i := 0; i < len(b); i++ {
		res *= 10
		res += int64(b[i]) - 48
	}
	if isNeg {
		res *= -1
	}
	return res
}

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

func intToBytes(n int) []byte {
	return int64ToBytes(int64(n))
}

func int64ToBytes(n int64) []byte {
	var res [65]byte
	var isNeg bool
	if n < 0 {
		isNeg = true
		n = -n
	}
	var l int = 65
	for n > 0 {
		l--
		res[l] = byte(n % 10 + 48)
		n /= 10
	}
	if l == 65 {
		l--
		res[l] = byte(48)
	}
	if isNeg {
		l--
		res[l] = byte(45)
	}
	return res[l:]
}

func bsLower(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsLower64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsUpper(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func bsUpper64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func max(n1, n2 int) int {
	return int(max64(int64(n1), int64(n2)))
}

func max64(n1, n2 int64) int64 {
	if n1 > n2 {
		return n1
	}
	return n2
}

func min(n1, n2 int) int {
	return int(min64(int64(n1), int64(n2)))
}

func min64(n1, n2 int64) int64 {
	if n1 < n2 {
		return n1
	}
	return n2
}

func yes(res, isUpperCase bool) bool {
	var arr [4]string = [4]string{"No", "Yes", "NO", "YES"}
	var ind int
	if res == true {
		ind = 1
	}
	if isUpperCase == true {
		ind += 2
	}
	out.WriteString(arr[ind])
	out.WriteByte(NL)
	return res
}

package main

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

const (
	MOD int = 1e9+7
	NL byte = byte('\n')
	SP byte = byte(' ')
)

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

	n, k int
	s string
	res int
)

func main() {
	initBuffer()
	var t int = 1
	// t = getInt()
	for i := 0; i < t; i++ {
		solve()
	}
	// test()
	out.Flush()
}

func solve() {
	initialize()
	input()
	count()
	output()
}

func initialize() {

}

func input() {
	n = getInt()
	k = getInt()
	s = getString()
}

func count() {
	var arr []int = make([]int, n)
	for i := 1; i < n; i++ {
		if arr[i] > arr[0] {
			res = i
			return
		}
		arr[i] = arr[i-1]
		for arr[i] > 0 && s[i] != s[arr[i]%(i-arr[i])] {
			if s[i] < s[arr[i]%(i-arr[i])] {
				arr[i] = arr[arr[i]]
			} else {
				break
			}
		}
		if s[i] == s[arr[i]%(i-arr[i])] {
			arr[i]++
		} else if s[i] > s[arr[i]%(i-arr[i])] {
			res = i
			return
		}
	}
	res = n - arr[n-1]
	if res < n && s[0] < s[res] {
		return
	}
	res = n
}

func output() {
	for i := 0; i < k / res; i++ {
		out.WriteString(s[:res])
	}
	out.WriteString(s[:k%res])
}

func test() {
	fmt.Print()
}

func initBuffer() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer([]byte{}, 4 * 1024 * 1024)
	in.Split(scanWords)
	out = bufio.NewWriter(os.Stdout)
}

func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	i := bytes.IndexByte(data, '\n')
	j := bytes.IndexByte(data, ' ')
	ind := min(i, j)
	if ind < 0 {
		ind = max(i, j)
	}
	if ind >= 0 {
		return ind + 1, dropCR(data[0:ind]), nil
	}
	if atEOF {
		return len(data), dropCR(data), nil
	}
	return 0, nil, nil
}

func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[:len(data)-1]
	}
	return data
}

func getFloat() float64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res1 int64
	for i := 0; i < len(b); i++ {
		if b[i] == '.' {
			b = b[i+1:]
			break
		}
		res1 *= 10
		res1 += int64(b[i]) - 48
		if i == len(b) - 1 {
			b = b[:0]
		}
	}
	var res2 float64
	for i := len(b); i > 0; i-- {
		res2 += float64(b[i-1]) - 48
		res2 /= 10
	}
	if isNeg {
		res1 *= -1
		res2 *= -1
	}
	return float64(res1) + res2
}

func getInt() int {
	return int(getInt64())
}

func getInt64() int64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res int64
	for i := 0; i < len(b); i++ {
		res *= 10
		res += int64(b[i]) - 48
	}
	if isNeg {
		res *= -1
	}
	return res
}

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

func intToBytes(n int) []byte {
	return int64ToBytes(int64(n))
}

func int64ToBytes(n int64) []byte {
	var res [65]byte
	var isNeg bool
	if n < 0 {
		isNeg = true
		n = -n
	}
	var l int = 65
	for n > 0 {
		l--
		res[l] = byte(n % 10 + 48)
		n /= 10
	}
	if l == 65 {
		l--
		res[l] = byte(48)
	}
	if isNeg {
		l--
		res[l] = byte(45)
	}
	return res[l:]
}

func bsLower(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsLower64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsUpper(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func bsUpper64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func max(n1, n2 int) int {
	return int(max64(int64(n1), int64(n2)))
}

func max64(n1, n2 int64) int64 {
	if n1 > n2 {
		return n1
	}
	return n2
}

func min(n1, n2 int) int {
	return int(min64(int64(n1), int64(n2)))
}

func min64(n1, n2 int64) int64 {
	if n1 < n2 {
		return n1
	}
	return n2
}

func yes(res, isUpperCase bool) bool {
	var arr [4]string = [4]string{"No", "Yes", "NO", "YES"}
	var ind int
	if res == true {
		ind = 1
	}
	if isUpperCase == true {
		ind += 2
	}
	out.WriteString(arr[ind])
	out.WriteByte(NL)
	return res
}

package main

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

const (
	MOD int = 1e9+7
	NL byte = byte('\n')
	SP byte = byte(' ')
)

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

	n, k int
	s string
	res int
)

func main() {
	initBuffer()
	var t int = 1
	// t = getInt()
	for i := 0; i < t; i++ {
		solve()
	}
	// test()
	out.Flush()
}

func solve() {
	initialize()
	input()
	count()
	output()
}

func initialize() {

}

func input() {
	n = getInt()
	k = getInt()
	s = getString()
}

func count() {
	var arr []int = make([]int, n)
	for i := 1; i < n; i++ {
		arr[i] = arr[i-1]
		for arr[i] > 0 && s[i] != s[arr[i]%(i-arr[i])] {
			if s[i] < s[arr[i]%(i-arr[i])] {
				arr[i] = arr[arr[i]]
			} else {
				break
			}
		}
		if s[i] == s[arr[i]%(i-arr[i])] {
			arr[i]++
		} else if s[i] > s[arr[i]%(i-arr[i])] {
			res = i
			return
		}
	}
	res = n - arr[n-1]
	if res < n && s[0] < s[res] {
		return
	}
	res = n
}

func output() {
	for i := 0; i < k / res; i++ {
		out.WriteString(s[:res])
	}
	out.WriteString(s[:k%res])
}

func test() {
	fmt.Print()
}

func initBuffer() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer([]byte{}, 4 * 1024 * 1024)
	in.Split(scanWords)
	out = bufio.NewWriter(os.Stdout)
}

func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	i := bytes.IndexByte(data, '\n')
	j := bytes.IndexByte(data, ' ')
	ind := min(i, j)
	if ind < 0 {
		ind = max(i, j)
	}
	if ind >= 0 {
		return ind + 1, dropCR(data[0:ind]), nil
	}
	if atEOF {
		return len(data), dropCR(data), nil
	}
	return 0, nil, nil
}

func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[:len(data)-1]
	}
	return data
}

func getFloat() float64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res1 int64
	for i := 0; i < len(b); i++ {
		if b[i] == '.' {
			b = b[i+1:]
			break
		}
		res1 *= 10
		res1 += int64(b[i]) - 48
		if i == len(b) - 1 {
			b = b[:0]
		}
	}
	var res2 float64
	for i := len(b); i > 0; i-- {
		res2 += float64(b[i-1]) - 48
		res2 /= 10
	}
	if isNeg {
		res1 *= -1
		res2 *= -1
	}
	return float64(res1) + res2
}

func getInt() int {
	return int(getInt64())
}

func getInt64() int64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res int64
	for i := 0; i < len(b); i++ {
		res *= 10
		res += int64(b[i]) - 48
	}
	if isNeg {
		res *= -1
	}
	return res
}

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

func intToBytes(n int) []byte {
	return int64ToBytes(int64(n))
}

func int64ToBytes(n int64) []byte {
	var res [65]byte
	var isNeg bool
	if n < 0 {
		isNeg = true
		n = -n
	}
	var l int = 65
	for n > 0 {
		l--
		res[l] = byte(n % 10 + 48)
		n /= 10
	}
	if l == 65 {
		l--
		res[l] = byte(48)
	}
	if isNeg {
		l--
		res[l] = byte(45)
	}
	return res[l:]
}

func bsLower(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsLower64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsUpper(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func bsUpper64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func max(n1, n2 int) int {
	return int(max64(int64(n1), int64(n2)))
}

func max64(n1, n2 int64) int64 {
	if n1 > n2 {
		return n1
	}
	return n2
}

func min(n1, n2 int) int {
	return int(min64(int64(n1), int64(n2)))
}

func min64(n1, n2 int64) int64 {
	if n1 < n2 {
		return n1
	}
	return n2
}

func yes(res, isUpperCase bool) bool {
	var arr [4]string = [4]string{"No", "Yes", "NO", "YES"}
	var ind int
	if res == true {
		ind = 1
	}
	if isUpperCase == true {
		ind += 2
	}
	out.WriteString(arr[ind])
	out.WriteByte(NL)
	return res
}

package main

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

const (
	MOD int = 1e9+7
	NL byte = byte('\n')
	SP byte = byte(' ')
)

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

	n, k int
	s string
	res int
)

func main() {
	initBuffer()
	var t int = 1
	// t = getInt()
	for i := 0; i < t; i++ {
		solve()
	}
	// test()
	out.Flush()
}

func solve() {
	initialize()
	input()
	count()
	output()
}

func initialize() {

}

func input() {
	n = getInt()
	k = getInt()
	s = getString()
}

func count() {
	var arr []int = make([]int, n)
	for i := 1; i < n; i++ {
		arr[i] = arr[i-1]
		for arr[i] > 0 && s[i] != s[arr[i]%(i-arr[i])] {
			if s[i] < s[arr[i]%(i-arr[i])] {
				arr[i] = arr[arr[i]]
			} else {
				res = i
				return
			}
		}
		if s[i] == s[arr[i]%(i-arr[i])] {
			arr[i]++
		}
	}
	res = n - arr[n-1]
	if res < n && s[0] < s[res] {
		return
	}
	res = n
}

func output() {
	for i := 0; i < k / res; i++ {
		out.WriteString(s[:res])
	}
	out.WriteString(s[:k%res])
}

func test() {
	fmt.Print()
}

func initBuffer() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer([]byte{}, 4 * 1024 * 1024)
	in.Split(scanWords)
	out = bufio.NewWriter(os.Stdout)
}

func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	i := bytes.IndexByte(data, '\n')
	j := bytes.IndexByte(data, ' ')
	ind := min(i, j)
	if ind < 0 {
		ind = max(i, j)
	}
	if ind >= 0 {
		return ind + 1, dropCR(data[0:ind]), nil
	}
	if atEOF {
		return len(data), dropCR(data), nil
	}
	return 0, nil, nil
}

func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[:len(data)-1]
	}
	return data
}

func getFloat() float64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res1 int64
	for i := 0; i < len(b); i++ {
		if b[i] == '.' {
			b = b[i+1:]
			break
		}
		res1 *= 10
		res1 += int64(b[i]) - 48
		if i == len(b) - 1 {
			b = b[:0]
		}
	}
	var res2 float64
	for i := len(b); i > 0; i-- {
		res2 += float64(b[i-1]) - 48
		res2 /= 10
	}
	if isNeg {
		res1 *= -1
		res2 *= -1
	}
	return float64(res1) + res2
}

func getInt() int {
	return int(getInt64())
}

func getInt64() int64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res int64
	for i := 0; i < len(b); i++ {
		res *= 10
		res += int64(b[i]) - 48
	}
	if isNeg {
		res *= -1
	}
	return res
}

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

func intToBytes(n int) []byte {
	return int64ToBytes(int64(n))
}

func int64ToBytes(n int64) []byte {
	var res [65]byte
	var isNeg bool
	if n < 0 {
		isNeg = true
		n = -n
	}
	var l int = 65
	for n > 0 {
		l--
		res[l] = byte(n % 10 + 48)
		n /= 10
	}
	if l == 65 {
		l--
		res[l] = byte(48)
	}
	if isNeg {
		l--
		res[l] = byte(45)
	}
	return res[l:]
}

func bsLower(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsLower64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsUpper(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func bsUpper64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func max(n1, n2 int) int {
	return int(max64(int64(n1), int64(n2)))
}

func max64(n1, n2 int64) int64 {
	if n1 > n2 {
		return n1
	}
	return n2
}

func min(n1, n2 int) int {
	return int(min64(int64(n1), int64(n2)))
}

func min64(n1, n2 int64) int64 {
	if n1 < n2 {
		return n1
	}
	return n2
}

func yes(res, isUpperCase bool) bool {
	var arr [4]string = [4]string{"No", "Yes", "NO", "YES"}
	var ind int
	if res == true {
		ind = 1
	}
	if isUpperCase == true {
		ind += 2
	}
	out.WriteString(arr[ind])
	out.WriteByte(NL)
	return res
}

package main

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

const (
	MOD int = 1e9+7
	NL byte = byte('\n')
	SP byte = byte(' ')
)

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

	n, k int
	s string
	res int
)

func main() {
	initBuffer()
	var t int = 1
	// t = getInt()
	for i := 0; i < t; i++ {
		solve()
	}
	// test()
	out.Flush()
}

func solve() {
	initialize()
	input()
	count()
	output()
}

func initialize() {

}

func input() {
	n = getInt()
	k = getInt()
	s = getString()
}

func count() {
	var arr []int = make([]int, n)
	for i := 1; i < n; i++ {
		if s[i] >= s[0] {
			arr[i] = 1
			for j := i + 1; j < n; j++ {
				if s[j] >= s[arr[j-1]%i] {
					arr[j] = arr[j-1] + 1
				} else {
					break
				}
			}
			if arr[n-1] > 0 {
				break
			}
		}
	}
	res = n - arr[n-1]
}

func output() {
	for i := 0; i < k / res; i++ {
		out.WriteString(s[:res])
	}
	out.WriteString(s[:k%res])
}

func test() {
	fmt.Print()
}

func initBuffer() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer([]byte{}, 4 * 1024 * 1024)
	in.Split(scanWords)
	out = bufio.NewWriter(os.Stdout)
}

func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	i := bytes.IndexByte(data, '\n')
	j := bytes.IndexByte(data, ' ')
	ind := min(i, j)
	if ind < 0 {
		ind = max(i, j)
	}
	if ind >= 0 {
		return ind + 1, dropCR(data[0:ind]), nil
	}
	if atEOF {
		return len(data), dropCR(data), nil
	}
	return 0, nil, nil
}

func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[:len(data)-1]
	}
	return data
}

func getFloat() float64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res1 int64
	for i := 0; i < len(b); i++ {
		if b[i] == '.' {
			b = b[i+1:]
			break
		}
		res1 *= 10
		res1 += int64(b[i]) - 48
		if i == len(b) - 1 {
			b = b[:0]
		}
	}
	var res2 float64
	for i := len(b); i > 0; i-- {
		res2 += float64(b[i-1]) - 48
		res2 /= 10
	}
	if isNeg {
		res1 *= -1
		res2 *= -1
	}
	return float64(res1) + res2
}

func getInt() int {
	return int(getInt64())
}

func getInt64() int64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res int64
	for i := 0; i < len(b); i++ {
		res *= 10
		res += int64(b[i]) - 48
	}
	if isNeg {
		res *= -1
	}
	return res
}

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

func intToBytes(n int) []byte {
	return int64ToBytes(int64(n))
}

func int64ToBytes(n int64) []byte {
	var res [65]byte
	var isNeg bool
	if n < 0 {
		isNeg = true
		n = -n
	}
	var l int = 65
	for n > 0 {
		l--
		res[l] = byte(n % 10 + 48)
		n /= 10
	}
	if l == 65 {
		l--
		res[l] = byte(48)
	}
	if isNeg {
		l--
		res[l] = byte(45)
	}
	return res[l:]
}

func bsLower(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsLower64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsUpper(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func bsUpper64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func max(n1, n2 int) int {
	return int(max64(int64(n1), int64(n2)))
}

func max64(n1, n2 int64) int64 {
	if n1 > n2 {
		return n1
	}
	return n2
}

func min(n1, n2 int) int {
	return int(min64(int64(n1), int64(n2)))
}

func min64(n1, n2 int64) int64 {
	if n1 < n2 {
		return n1
	}
	return n2
}

func yes(res, isUpperCase bool) bool {
	var arr [4]string = [4]string{"No", "Yes", "NO", "YES"}
	var ind int
	if res == true {
		ind = 1
	}
	if isUpperCase == true {
		ind += 2
	}
	out.WriteString(arr[ind])
	out.WriteByte(NL)
	return res
}

package main

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

const (
	MOD int = 1e9+7
	NL byte = byte('\n')
	SP byte = byte(' ')
)

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

	n, k int
	s string
	res int
)

func main() {
	initBuffer()
	var t int = 1
	// t = getInt()
	for i := 0; i < t; i++ {
		solve()
	}
	// test()
	out.Flush()
}

func solve() {
	initialize()
	input()
	count()
	output()
}

func initialize() {

}

func input() {
	n = getInt()
	k = getInt()
	s = getString()
}

func count() {
	var arr []int = make([]int, n)
	for i := 1; i < n; i++ {
		if s[i] >= s[0] {
			arr[i] = 1
			for j := i + 1; j < n; j++ {
				if s[j] >= s[arr[j-1]] {
					arr[j] = arr[j-1] + 1
				}
			}
			if arr[n-1] > 0 {
				break
			}
		}
	}
	res = n - arr[n-1]
}

func output() {
	for i := 0; i < k / res; i++ {
		out.WriteString(s[:res])
	}
	out.WriteString(s[:k%res])
}

func test() {
	fmt.Print()
}

func initBuffer() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer([]byte{}, 4 * 1024 * 1024)
	in.Split(scanWords)
	out = bufio.NewWriter(os.Stdout)
}

func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	i := bytes.IndexByte(data, '\n')
	j := bytes.IndexByte(data, ' ')
	ind := min(i, j)
	if ind < 0 {
		ind = max(i, j)
	}
	if ind >= 0 {
		return ind + 1, dropCR(data[0:ind]), nil
	}
	if atEOF {
		return len(data), dropCR(data), nil
	}
	return 0, nil, nil
}

func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[:len(data)-1]
	}
	return data
}

func getFloat() float64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res1 int64
	for i := 0; i < len(b); i++ {
		if b[i] == '.' {
			b = b[i+1:]
			break
		}
		res1 *= 10
		res1 += int64(b[i]) - 48
		if i == len(b) - 1 {
			b = b[:0]
		}
	}
	var res2 float64
	for i := len(b); i > 0; i-- {
		res2 += float64(b[i-1]) - 48
		res2 /= 10
	}
	if isNeg {
		res1 *= -1
		res2 *= -1
	}
	return float64(res1) + res2
}

func getInt() int {
	return int(getInt64())
}

func getInt64() int64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res int64
	for i := 0; i < len(b); i++ {
		res *= 10
		res += int64(b[i]) - 48
	}
	if isNeg {
		res *= -1
	}
	return res
}

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

func intToBytes(n int) []byte {
	return int64ToBytes(int64(n))
}

func int64ToBytes(n int64) []byte {
	var res [65]byte
	var isNeg bool
	if n < 0 {
		isNeg = true
		n = -n
	}
	var l int = 65
	for n > 0 {
		l--
		res[l] = byte(n % 10 + 48)
		n /= 10
	}
	if l == 65 {
		l--
		res[l] = byte(48)
	}
	if isNeg {
		l--
		res[l] = byte(45)
	}
	return res[l:]
}

func bsLower(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsLower64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsUpper(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func bsUpper64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func max(n1, n2 int) int {
	return int(max64(int64(n1), int64(n2)))
}

func max64(n1, n2 int64) int64 {
	if n1 > n2 {
		return n1
	}
	return n2
}

func min(n1, n2 int) int {
	return int(min64(int64(n1), int64(n2)))
}

func min64(n1, n2 int64) int64 {
	if n1 < n2 {
		return n1
	}
	return n2
}

func yes(res, isUpperCase bool) bool {
	var arr [4]string = [4]string{"No", "Yes", "NO", "YES"}
	var ind int
	if res == true {
		ind = 1
	}
	if isUpperCase == true {
		ind += 2
	}
	out.WriteString(arr[ind])
	out.WriteByte(NL)
	return res
}

package main

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

const (
	MOD int = 1e9+7
	NL byte = byte('\n')
	SP byte = byte(' ')
)

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

	n, k int
	s string
	res int
)

func main() {
	initBuffer()
	var t int = 1
	// t = getInt()
	for i := 0; i < t; i++ {
		solve()
	}
	// test()
	out.Flush()
}

func solve() {
	initialize()
	input()
	count()
	output()
}

func initialize() {

}

func input() {
	n = getInt()
	k = getInt()
	s = getString()
}

func count() {
	var arr []int = make([]int, n)
	for i := 1; i < n; i++ {
		if s[i] > s[arr[i-1]] {
			arr[i] = arr[i-1] + 1
		}
	}
	res = n - arr[n-1]
}

func output() {
	for i := 0; i < k / res; i++ {
		out.WriteString(s[:res])
	}
	out.WriteString(s[:k%res])
}

func test() {
	fmt.Print()
}

func initBuffer() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer([]byte{}, 4 * 1024 * 1024)
	in.Split(scanWords)
	out = bufio.NewWriter(os.Stdout)
}

func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	i := bytes.IndexByte(data, '\n')
	j := bytes.IndexByte(data, ' ')
	ind := min(i, j)
	if ind < 0 {
		ind = max(i, j)
	}
	if ind >= 0 {
		return ind + 1, dropCR(data[0:ind]), nil
	}
	if atEOF {
		return len(data), dropCR(data), nil
	}
	return 0, nil, nil
}

func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[:len(data)-1]
	}
	return data
}

func getFloat() float64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res1 int64
	for i := 0; i < len(b); i++ {
		if b[i] == '.' {
			b = b[i+1:]
			break
		}
		res1 *= 10
		res1 += int64(b[i]) - 48
		if i == len(b) - 1 {
			b = b[:0]
		}
	}
	var res2 float64
	for i := len(b); i > 0; i-- {
		res2 += float64(b[i-1]) - 48
		res2 /= 10
	}
	if isNeg {
		res1 *= -1
		res2 *= -1
	}
	return float64(res1) + res2
}

func getInt() int {
	return int(getInt64())
}

func getInt64() int64 {
	in.Scan()
	b := in.Bytes()
	var isNeg bool
	if b[0] == '-' {
		isNeg = true
		b = b[1:]
	}
	var res int64
	for i := 0; i < len(b); i++ {
		res *= 10
		res += int64(b[i]) - 48
	}
	if isNeg {
		res *= -1
	}
	return res
}

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

func intToBytes(n int) []byte {
	return int64ToBytes(int64(n))
}

func int64ToBytes(n int64) []byte {
	var res [65]byte
	var isNeg bool
	if n < 0 {
		isNeg = true
		n = -n
	}
	var l int = 65
	for n > 0 {
		l--
		res[l] = byte(n % 10 + 48)
		n /= 10
	}
	if l == 65 {
		l--
		res[l] = byte(48)
	}
	if isNeg {
		l--
		res[l] = byte(45)
	}
	return res[l:]
}

func bsLower(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsLower64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] < n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] >= n {
		return minN
	}
	return maxN
}

func bsUpper(arr []int, n int) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func bsUpper64(arr []int64, n int64) int {
	var minN, midN, maxN int
	maxN = len(arr)
	for maxN - 1 > minN {
		midN = (minN + maxN) / 2
		if arr[midN] <= n {
			minN = midN
		} else {
			maxN = midN
		}
	}
	if arr[minN] > n {
		return minN
	}
	return maxN
}

func max(n1, n2 int) int {
	return int(max64(int64(n1), int64(n2)))
}

func max64(n1, n2 int64) int64 {
	if n1 > n2 {
		return n1
	}
	return n2
}

func min(n1, n2 int) int {
	return int(min64(int64(n1), int64(n2)))
}

func min64(n1, n2 int64) int64 {
	if n1 < n2 {
		return n1
	}
	return n2
}

func yes(res, isUpperCase bool) bool {
	var arr [4]string = [4]string{"No", "Yes", "NO", "YES"}
	var ind int
	if res == true {
		ind = 1
	}
	if isUpperCase == true {
		ind += 2
	}
	out.WriteString(arr[ind])
	out.WriteByte(NL)
	return res
}

package main

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

var _rbuf = bufio.NewReader(os.Stdin)
var _wbuf = bufio.NewWriter(os.Stdout)

func scan(a ...interface{})             { _wbuf.Flush(); fmt.Fscan(_rbuf, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(_wbuf, f, a...) }

func main() {
	defer _wbuf.Flush()

	var n, k int
	var str string

	scan(&n, &k)
	scan(&str)

	printf("%s\n", solve(n, k, str))
}

func solve(n, k int, str string) string {
	rnk := make([]int, n+n)
	oldRnk := make([]int, n+n)
	sa := make([]int, n)
	oldSa := make([]int, n)
	cnt := make([]int, n+26)

	for i := n; i < n+n; i++ {
		rnk[i] = n
	}
	for i := 0; i < n; i++ {
		rnk[i] = int(str[i] - 'a')
		cnt[rnk[i]]++
	}
	for i := 1; i <= 26; i++ {
		cnt[i] += cnt[i-1]
	}
	for i := n - 1; i >= 0; i-- {
		cnt[rnk[i]]--
		sa[cnt[rnk[i]]] = i
	}
	for b := 1; b < n; b += b {
		for i := 0; i <= n; i++ {
			cnt[i] = 0
		}
		copy(oldSa, sa)
		for i := 0; i < n; i++ {
			cnt[rnk[oldSa[i]+b]]++
		}
		for i := 1; i <= n; i++ {
			cnt[i] += cnt[i-1]
		}
		for i := n - 1; i >= 0; i-- {
			cnt[rnk[oldSa[i]+b]]--
			sa[cnt[rnk[oldSa[i]+b]]] = oldSa[i]
		}
		for i := 0; i <= n; i++ {
			cnt[i] = 0
		}
		copy(oldSa, sa)
		for i := 0; i < n; i++ {
			cnt[rnk[oldSa[i]]]++
		}
		for i := 1; i <= n; i++ {
			cnt[i] += cnt[i-1]
		}
		for i := n - 1; i >= 0; i-- {
			cnt[rnk[oldSa[i]]]--
			sa[cnt[rnk[oldSa[i]]]] = oldSa[i]
		}
		copy(oldRnk, rnk)
		var rank int
		for i := 0; i < n; i++ {
			if i > 0 &&
				(oldRnk[sa[i]] != oldRnk[sa[i-1]] || oldRnk[sa[i]+b] != oldRnk[sa[i-1]+b]) {
				rank++
			}
			rnk[sa[i]] = rank
		}
	}

	ret := str
	for i := 0; i < n; i++ {
		if sa[i] == 0 && i < n-1 {
			ret = ret[:sa[i+1]]
		}
	}

	for len(ret) < k {
		ret += ret
	}
	return ret[:k]
}


Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n × n matrix W, consisting of integers, and you should find two n × n matrices A and B, all the following conditions must hold:   Aij = Aji, for all i, j (1 ≤ i, j ≤ n);  Bij =  - Bji, for all i, j (1 ≤ i, j ≤ n);  Wij = Aij + Bij, for all i, j (1 ≤ i, j ≤ n). Can you solve the problem?

The first line contains an integer n (1 ≤ n ≤ 170). Each of the following n lines contains n integers. The j-th integer in the i-th line is Wij (0 ≤ |Wij| < 1717).

The first n lines must contain matrix A. The next n lines must contain matrix B. Print the matrices in the format equal to format of matrix W in input. It is guaranteed that the answer exists. If there are multiple answers, you are allowed to print any of them. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 4.

package main

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

var w, a, b [170][170]float64

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	for i := 0; i < n; i++ {
		for j := 0; j < n-1; j++ {
			fmt.Fscanf(reader, "%f ", &w[i][j])
		}
		fmt.Fscanf(reader, "%f\n", &w[i][n-1])
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if i == j {
				a[i][j] = w[i][j]
			} else {
				a[i][j] = (w[i][j] + w[j][i]) / 2
				b[i][j] = w[i][j] - a[i][j]
			}
		}
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Printf("%f ", a[i][j])
		}
		fmt.Printf("\n")
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Printf("%f ", b[i][j])
		}
		fmt.Printf("\n")
	}
}

package main

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

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

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

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

func main() {
	// defer func(start time.Time) {
	// 	fmt.Println(time.Since(start))
	// }(time.Now())

	defer writer.Flush()
	scanner.Split(bufio.ScanWords)
	n := nextInt()

	w := make([][]int, n)
	// a := make([][]float32, n)
	// b := make([][]float32, n)

	for i := range w {
		// a[i] = make([]float32, n)
		// b[i] = make([]float32, n)
		w[i] = make([]int, n)

		for j := range w[i] {
			w[i][j] = nextInt()
		}
	}

	// Method 1 fast
	// for i:=0; i<n; i++ {
	// 	for j:=0; j<i; j++ {
	// 		a[j][i] = float32(w[j][i] + w[i][j])/2
	// 		a[i][j] = a[j][i]
	// 		b[j][i] = float32(w[j][i]) - a[j][i]
	// 		b[i][j] = -b[j][i]
	// 	}
	// 	a[i][i] = float32(w[i][i])
	// 	b[i][i] = 0
	// }

	// for i:=0; i<n; i++ {
	// 	for j:=0; j<n; j++ {
	// 		fmt.Fprint(writer, a[i][j], " ")
	// 	}
	// 	fmt.Fprintln(writer)
	// }

	// for i:=0; i<n; i++ {
	// 	for j:=0; j<n; j++ {
	// 		fmt.Fprint(writer, b[i][j], " ")
	// 	}
	// 	fmt.Fprintln(writer)
	// }

	// Method 2 slow
	// for i:=0; i<n; i++ {
	// 	for j:=0; j<n; j++ {
	// 		fmt.Fprint(writer, float32(w[j][i] + w[i][j])/2, " " )
	// 	}
	// 	fmt.Fprintln(writer)
	// }

	// for i := 0; i < n; i++ {
	// 	for j := 0; j < n; j++ {
	// 		fmt.Fprint(writer, float32(w[i][j] - w[j][i])/2, " ")
	// 	}
	// 	fmt.Fprintln(writer)
	// }

	// Method 3 fast
	iface := make([]interface{}, n)

	for i:=0; i<n; i++ {
		for j:=0; j<n; j++ {
			iface[j] = interface{}(float32(w[j][i] + w[i][j])/2)
		}
		fmt.Fprintln(writer, iface...)
	}

	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			iface[j] = interface{}(float32(w[i][j] - w[j][i])/2)
		}
		fmt.Fprintln(writer, iface...)
	}
}

package main

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

var scanner *bufio.Scanner

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

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

  n := getI()
  w := make([][]int, n)
  a := make([][]float64, n)
  b := make([][]float64, n)
  for r := 0; r < n; r++ {
    w[r] = make([]int, n)
    a[r] = make([]float64, n)
    b[r] = make([]float64, n)
    for c := 0; c < n; c++ {
      w[r][c] = getI()
    }
  }
  for r := 0; r < n; r++ {
    a[r][r] = float64(w[r][r])
    for c := r+1; c < n; c++ {
      x, y := float64(w[r][c]), float64(w[c][r])
      mean := (x+y)/2
      diff := (x-y)
      a[r][c], a[c][r] = mean, mean
      b[r][c], b[c][r] = diff/2, -diff/2
    }
  }
  for r := 0; r < n; r++ {
    writer.WriteString(fmt.Sprintf("%.1f", a[r][0]))
    for c := 1; c < n; c++ {
      writer.WriteString(fmt.Sprintf(" %.1f", a[r][c]))
    }
    writer.WriteString("\n")
  }
  for r := 0; r < n; r++ {
    writer.WriteString(fmt.Sprintf("%.1f", b[r][0]))
    for c := 1; c < n; c++ {
      writer.WriteString(fmt.Sprintf(" %.1f", b[r][c]))
    }
    writer.WriteString("\n")
  }
}

// wa on test 4
package main

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

func main() {

	var (
		W       [200][200]int16
		n, i, j int32
		olv     *bufio.Reader
		ir      *bufio.Writer
	)

	olv = bufio.NewReader(os.Stdin)
	ir = bufio.NewWriter(os.Stdout)

	fmt.Scan(&n)
	for i = 0; i < n; i++ {
		for j = 0; j < n; j++ {
			fmt.Fscan(olv, &W[i][j])
		}
	}

	// A kiirasa
	for i = 0; i < n; i++ {
		for j = 0; j < n; j++ {
			if i == j {
				fmt.Fprintf(ir, "%.8f ", float64(W[i][i]))
			} else {
				fmt.Fprintf(ir, "%.8f ", 0.5*float64(W[i][j]+W[j][i]))
			}
		}
		fmt.Fprintln(ir)
	}

	for i = 0; i < n; i++ {
		for j = 0; j < n; j++ {
			if i == j {
				fmt.Fprint(ir, "0.00000000 ")
			} else {
				fmt.Fprintf(ir, "%.8f ",
					float64(W[i][j])-0.5*float64(W[i][j]+W[j][i]))
			}
		}
		fmt.Fprintln(ir)
	}

	ir.Flush()
}

package main

import(
	"fmt"

)

func main() {
	var n int
	var mat [][]int
	var a [][]float64
	var b [][]float64

	fmt.Scanf("%d", &n)
	fmt.Scanf(" ")
	// fmt.Scanf("\n")
	mat = make([][]int, n)
	a = make([][]float64, n)
	b = make([][]float64, n)
	for i := 0; i < n; i++ {

		mat[i] = make([]int, n)
		a[i] = make([]float64, n)
		b[i] = make([]float64, n)
		for j := 0; j < n; j++ {
			fmt.Scanf("%d", &mat[i][j])
		}
		if i < n -1 {
			fmt.Scanf(" ")
		}
		// fmt.Scanf("\n")
	}
	var aItem float64
	var bItem float64
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if i == j {
				bItem = 0.0
				aItem = float64(mat[i][j])
				a[i][j] = aItem
				b[i][j] = bItem
			}else{
				aItem = (float64(mat[i][j]) + float64(mat[j][i])) / 2.0
				bItem = float64(mat[i][j]) - aItem
				a[i][j] = aItem
				a[j][i] = aItem
				b[i][j] = bItem
				b[j][i] = bItem * -1
			}

		}
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Printf("%f ", a[i][j])
		}
		fmt.Println()
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Printf("%f ", b[i][j])
		}
		fmt.Println()
	}
}

package main

import(
	"fmt"

)

func main() {
	var n int
	var mat [][]int
	var a [][]float64
	var b [][]float64

	fmt.Scanf("%d", &n)
	mat = make([][]int, n)
	a = make([][]float64, n)
	b = make([][]float64, n)
	for i := 0; i < n; i++ {
		mat[i] = make([]int, n)
		a[i] = make([]float64, n)
		b[i] = make([]float64, n)
		for j := 0; j < n; j++ {
			fmt.Scanf("%d", &mat[i][j])
		}
	}
	var aItem float64
	var bItem float64
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if i == j {
				bItem = 0
				aItem = float64(mat[i][j])
			}else{
				aItem = (float64(mat[i][j]) + float64(mat[j][i])) / 2.0
				bItem = float64(mat[i][j]) - aItem
			}
			a[i][j] = aItem
			a[j][i] = aItem
			b[i][j] = bItem
			b[j][i] = bItem * -1

		}
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Print(" ", a[i][j])
		}
		fmt.Println()
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Print(" ", b[i][j])
		}
		fmt.Println()
	}
}

package main

import(
	"fmt"

)

func main() {
	var n int
	var mat [][]int
	var a [][]float64
	var b [][]float64

	fmt.Scanf("%d", &n)
	fmt.Scanf(" ")
	// fmt.Scanf("\n")
	mat = make([][]int, n)
	a = make([][]float64, n)
	b = make([][]float64, n)
	for i := 0; i < n; i++ {

		mat[i] = make([]int, n)
		a[i] = make([]float64, n)
		b[i] = make([]float64, n)
		for j := 0; j < n; j++ {
			fmt.Scanf("%d", &mat[i][j])
		}
		if i < n -1 {
			fmt.Scanf(" ")
		}
		// fmt.Scanf("\n")
	}
	fmt.Println(mat)
	var aItem float64
	var bItem float64
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if i == j {
				bItem = 0
				aItem = float64(mat[i][j])
			}else{
				aItem = (float64(mat[i][j]) + float64(mat[j][i])) / 2.0
				bItem = float64(mat[i][j]) - aItem
			}
			a[i][j] = aItem
			a[j][i] = aItem
			b[i][j] = bItem
			b[j][i] = bItem * -1

		}
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Print(" ", a[i][j])
		}
		fmt.Println()
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Print(" ", b[i][j])
		}
		fmt.Println()
	}
}


Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть n точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x1 километров вдоль улицы, второй — в точке x2 и так далее, n-й велопрокат находится в точке xn. Школа Аркадия находится в точке x1 (то есть там же, где и первый велопрокат), а дом — в точке xn (то есть там же, где и n-й велопрокат). Известно, что xi < xi + 1 для всех 1 ≤ i < n.Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы. Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.

В первой строке следуют два целых числа n и k (2 ≤ n ≤ 1 000, 1 ≤ k ≤ 100 000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде. В следующей строке следует последовательность целых чисел x1, x2, ..., xn (0 ≤ x1 < x2 < ... < xn ≤ 100 000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания.

Если Аркадий не сможет добраться от школы до дома только на велосипедах, выведите -1. В противном случае, выведите минимальное количество велосипедов, которые Аркадию нужно взять в точках проката.

ПримечаниеВ первом примере Аркадий должен взять первый велосипед в первом велопрокате и доехать на нём до второго велопроката. Во втором велопрокате он должен взять новый велосипед, на котором он сможет добраться до четвертого велопроката, рядом с которым и находится его дом. Поэтому Аркадию нужно всего два велосипеда, чтобы добраться от школы до дома.Во втором примере всего два велопроката, расстояние между которыми 10. Но максимальное расстояние, которое можно проехать на одном велосипеде, равно 9. Поэтому Аркадий не сможет добраться от школы до дома только на велосипедах.

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	scanner.Scan()
	k, _ := strconv.Atoi(scanner.Text())

	x := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		x[i], _ = strconv.Atoi(scanner.Text())
	}

	for i := 0; i < n-1; i++ {
		if x[i+1]-x[i] > k {
			fmt.Println(-1)
			return
		}
	}

	counter := 1
	lastTake := x[0]
	for i := 1; i < n; i++ {
		if x[i]-lastTake > k {
			counter++
			lastTake = x[i-1]
		}
	}
	fmt.Println(counter)
}

package main

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

func main() {
	var cnt, dist int
	fmt.Scanln(&cnt, &dist)

	reader := bufio.NewScanner(os.Stdin)
	reader.Scan()
	line := strings.Split(reader.Text(), " ")

	points := make([]int, cnt)
	for i := range line {
		points[i], _ = strconv.Atoi(line[i])
	}

	per := 1
	ost := dist + points[0] - points[1]
	if points[1] - points[0] > dist {
		fmt.Println("-1")
		return
	}
	for i := 1; i < cnt - 1; i++ {
		r := points[i + 1] - points[i]

		if ost >= r {
			ost -= r
			continue
		}

		if r > dist {
			fmt.Println("-1")
			return
		}

		per++
		ost = dist - r
	}

	fmt.Println(per)
}


'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2. The finals will have n questions, m of them are auction questions and n - m of them are regular questions. Each question has a price. The price of the i-th question is ai points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100; m ≤ min(n, 30)) — the total number of questions and the number of auction questions, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the prices of the questions. The third line contains m distinct integers bi (1 ≤ bi ≤ n) — the numbers of auction questions. Assume that the questions are numbered from 1 to n.

In the single line, print the answer to the problem — the maximum points the R2 company can get if it plays optimally well. It is guaranteed that the answer fits into the integer 64-bit signed type.

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 (slice SliceInt64) Len() int {
  return len(slice)
}
func (slice SliceInt64) Swap(i, j int) {
  slice[i], slice[j] = slice[j], slice[i]
}
func (slice SliceInt64) Less(i, j int) bool {
  return slice[i]-slice[j] < 0
}

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

  n, m := getI(), getI()
  values := make([]int64, n)
  score := int64(0)
  for i := range values {
    values[i] = getI64()
    score += values[i]
  }
  auction := make([]int64, m)
  for i := range auction {
    auction[i] = values[getI()-1]
    score -= auction[i]
  }
  sort.Sort(SliceInt64(auction))
  alternative := score + auction[len(auction)-1]
  for i := 1; i < m; i++ {
    alternative *= 2
  }
  left, right := 0, len(auction)-1
  for left <= right {
    if score < auction[left] {
      score += auction[right]
      right--
    } else {
      score *= 2
      left++
    }
  }
  if alternative > score {
    score = alternative
  }
  writer.WriteString(fmt.Sprintf("%d\n", score))
}

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 (slice SliceInt64) Len() int {
  return len(slice)
}
func (slice SliceInt64) Swap(i, j int) {
  slice[i], slice[j] = slice[j], slice[i]
}
func (slice SliceInt64) Less(i, j int) bool {
  return slice[i]-slice[j] < 0
}

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

  n, m := getI(), getI()
  values := make([]int64, n)
  score := int64(0)
  for i := range values {
    values[i] = getI64()
    score += values[i]
  }
  auction := make([]int64, m)
  for i := range auction {
    auction[i] = values[getI()-1]
    score -= auction[i]
  }
  sort.Sort(SliceInt64(auction))
  left, right := 0, len(auction)-1
  for left <= right {
    if score < auction[left] {
      score += auction[right]
      right--
    } else {
      score *= 2
      left++
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", score))
}


The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.

The first line contains four space-separated integers x0, y0, x1, y1 (1 ≤ x0, y0, x1, y1 ≤ 109), denoting the initial and the final positions of the king. The second line contains a single integer n (1 ≤ n ≤ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 ≤ ri, ai, bi ≤ 109, ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily. It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.

If there is no path between the initial and final position along allowed cells, print -1. Otherwise print a single integer — the minimum number of moves the king needs to get from the initial position to the final one.

//https://codeforces.com/problemset/problem/242/C
//http://bigocoder.com/courses/ORANGE03/ORANGE03_LEC01/ORANGE_L01P04/statement
package main

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

var (
	dx    = []int{-1, -1, -1, 0, 0, 1, 1, 1}
	dy    = []int{-1, 0, 1, 1, -1, 1, 0, -1}
	cache map[int][]rangeSegment
)

type rangeSegment struct {
	min int
	max int
}

type cell struct {
	x int
	y int
}

func bfs(start cell, end cell) int {
	visited := map[cell]bool{}
	queue := []cell{start}
	dist := map[cell]int{start: 0}
	visited[start] = true

	for len(queue) > 0 {
		cur := dequeue(&queue)
		for i := range dx {
			newMove := cell{cur.x + dx[i], cur.y + dy[i]}
			if !visited[newMove] && isAllowed(newMove) {
				visited[newMove] = true
				queue = append(queue, newMove)
				dist[newMove] = dist[cur] + 1
			}
		}
	}

	if _, exist := dist[end]; !exist {
		return -1
	}

	return dist[end]
}

func dequeue(q *[]cell) cell {
	r := (*q)[0]
	(*q) = (*q)[1:]

	return r
}

func isAllowed(move cell) bool {
	if _, exist := cache[move.x]; exist {
		for i := range cache[move.x] {
			allowedRange := cache[move.x][i]
			if allowedRange.min <= move.y && move.y <= allowedRange.max {
				return true
			}
		}
	}

	return false
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var x1, y1, x2, y2, n, r, a, b int
	fmt.Fscanf(reader, "%d %d %d %d\n", &x1, &y1, &x2, &y2)
	fmt.Fscanf(reader, "%d\n", &n)
	cache = make(map[int][]rangeSegment)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d %d\n", &r, &a, &b)
		cache[r] = append(cache[r], rangeSegment{a, b})
	}

	res := bfs(cell{x1, y1}, cell{x2, y2})
	fmt.Fprintf(os.Stdout, "%d\n", res)
}

//https://codeforces.com/problemset/problem/242/C
//http://bigocoder.com/courses/ORANGE03/ORANGE03_LEC01/ORANGE_L01P04/statement
package main

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

var (
	dx    = []int{-1, -1, -1, 0, 0, 1, 1, 1}
	dy    = []int{-1, 0, 1, 1, -1, 1, 0, -1}
	cache map[int][]rangeSegment
)

type rangeSegment struct {
	min int
	max int
}

type cell struct {
	x int
	y int
}

func bfs(start cell, end cell) int {
	visited := map[cell]bool{}
	queue := []cell{start}
	dist := map[cell]int{start: 0}
	visited[start] = true

	for len(queue) > 0 {
		cur := dequeue(&queue)
		if cur == end {
			return dist[cur]
		}
		for i := range dx {
			newMove := cell{cur.x + dx[i], cur.y + dy[i]}
			if !visited[newMove] && isAllowed(newMove) {
				visited[newMove] = true
				queue = append(queue, newMove)
				dist[newMove] = dist[cur] + 1
			}
		}
	}

	return -1
}

func dequeue(q *[]cell) cell {
	r := (*q)[0]
	(*q) = (*q)[1:]

	return r
}

func isAllowed(move cell) bool {
	if _, exist := cache[move.x]; exist {
		for i := range cache[move.x] {
			allowedRange := cache[move.x][i]
			if allowedRange.min <= move.y && move.y <= allowedRange.max {
				return true
			}
		}
	}

	return false
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var x1, y1, x2, y2, n, r, a, b int
	fmt.Fscanf(reader, "%d %d %d %d\n", &x1, &y1, &x2, &y2)
	fmt.Fscanf(reader, "%d\n", &n)
	cache = make(map[int][]rangeSegment)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d %d\n", &r, &a, &b)
		cache[r] = append(cache[r], rangeSegment{a, b})
	}

	res := bfs(cell{x1, y1}, cell{x2, y2})
	fmt.Fprintf(os.Stdout, "%d\n", res)
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF242C(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	type pair struct{ x, y int }
	type pd struct{ x, y, d int }
	dir8 := [...]pair{{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}}

	var sx, sy, tx, ty, n, i, l, r int
	g := map[int]map[int]bool{}
	vis := map[int]map[int]bool{}
	for Fscan(in, &sx, &sy, &tx, &ty, &n); n > 0; n-- {
		Fscan(in, &i, &l, &r)
		if g[i] == nil {
			g[i] = map[int]bool{}
			vis[i] = map[int]bool{}
		}
		for c := l; c <= r; c++ {
			g[i][c] = true
		}
	}
	q := []pd{{sx, sy, 0}}
	for len(q) > 0 {
		p := q[0]
		q = q[1:]
		if p.x == tx && p.y == ty {
			Fprint(out, p.d)
			return
		}
		for _, d := range dir8 {
			if x, y := p.x+d.x, p.y+d.y; g[x] != nil && g[x][y] && !vis[x][y] {
				vis[x][y] = true
				q = append(q, pd{x, y, p.d + 1})
			}
		}
	}
	Fprint(out, -1)
}

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

package main

import (
	. "fmt"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func main() {
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			os.Stdin.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	type pair struct{ x, y int }
	type pd struct{ x, y, d int }
	dir8 := [...]pair{{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}}

	sx, sy, tx, ty := r(), r(), r(), r()
	g := map[int]map[int]bool{}
	vis := map[int]map[int]bool{}
	for n := r(); n > 0; n-- {
		i, l, r := r(), r(), r()
		if g[i] == nil {
			g[i] = map[int]bool{}
			vis[i] = map[int]bool{}
		}
		for c := l; c <= r; c++ {
			g[i][c] = true
		}
	}
	q := []pd{{sx, sy, 0}}
	for len(q) > 0 {
		p := q[0]
		q = q[1:]
		if p.x == tx && p.y == ty {
			Print(p.d)
			return
		}
		for _, d := range dir8 {
			if x, y := p.x+d.x, p.y+d.y; g[x] != nil && g[x][y] && !vis[x][y] {
				vis[x][y] = true
				q = append(q, pd{x, y, p.d + 1})
			}
		}
	}
	Print(-1)
}