Problem:
Score : 1300 points

Problem Statement

Takahashi has a string S of length N consisting of lowercase English letters.
On this string, he will perform the following operation K times:

Let T be the string obtained by reversing S, and U be the string obtained by concatenating S and T in this order.

Let S' be some contiguous substring of U with length N, and replace S with S'.

Among the strings that can be the string S after the K operations, find the lexicographically smallest possible one.

Constraints

1 \leq N \leq 5000

1 \leq K \leq 10^9

|S|=N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the lexicographically smallest possible string that can be the string S after the K operations.

Sample Input 1

5 1
bacba

Sample Output 1

aabca

When S=bacba, T=abcab, U=bacbaabcab, and the optimal choice of S' is S'=aabca.

Sample Input 2

10 2
bbaabbbaab

Sample Output 2

aaaabbaabb

Solution in C++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include <bits/stdc++.h>

using namespace std;

const int N = 10005;
int n, k, minn, len, maxlen, q[N];
string s, ans;

inline string reverse(string a)
{
	string ret = a;
	for (int i = 0; i < a.length(); i++) ret[i] = a[a.length() - i - 1];
	return ret;
}

inline string get(int x)
{
	string ret = s + reverse(s);
	if (x == n - 1) x += len;
	ret = ret.substr(n - x + maxlen - 1, n - maxlen);
	return reverse(ret);
}

int main()
{
	cin >> n >> k >> s;
	minn = 30;
	for (int i = 0; i < n; i++) minn = min(minn, s[i] - 'a');
	int now = 0;
	for (int i = 0; i < n; i++)
	{
		if (s[i] - 'a' == minn) now++;
		else
		{
			if (now == 0 || now < len) continue;
			if (now > len)
			{
				len = now;
				q[0] = 0;
			}
			q[++q[0]] = i - 1;
			now = 0;
		}
	}
	if (now) now *= 2;
	if (now > len)
	{
		len = now;
		q[0] = 0;
	}
	if (now == len) q[++q[0]] = n - 1;
	maxlen = len;
	if (maxlen >= n)
		{
			char c = minn + 'a';
			for (int i = 1; i <= n; i++) cout << c;
			cout << endl;
			return 0;
		}
	for (int i = 1; i < k; i++)
	{
		maxlen *= 2;
		if (maxlen >= n)
		{
			char c = minn + 'a';
			for (int i = 1; i <= n; i++) cout << c;
			cout << endl;
			return 0;
		}
	}
	ans = get(q[1]);
	for (int i = 2; i <= q[0]; i++) ans = min(ans, get(q[i]));
	char c = minn + 'a';
	for (int i = 1; i <= maxlen; i++) cout << c;
	cout << ans << endl;
	return 0;
}