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 PHP (5.6.30) (judge verdict: Wrong Answer)

#include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}

//INSERT ABOVE HERE
Int n,k;
string calc(string s){
  reverse(s.begin(),s.end());
  Int cnt=0;
  while(cnt<n&&s[0]==s[cnt]) cnt++;
  Int len=cnt<<k;
  if(len>=n) return string(n,s[0]);
  string res;
  for(Int i=cnt;i<n;i++)
    if(len+(Int)res.size()<n) res+=s[i];
  return string(len,s[0])+res;
}

signed main(){
  string s;
  cin>>n>>k>>s;
  chmin(k,20);
  k--;
  string ans=s;

  string t(s);
  reverse(t.begin(),t.end());
  string b=s+t;
  for(Int i=0;i<=n;i++){
    string c=b.substr(i,n);
    chmin(ans,calc(c));
  }
  cout<<ans<<endl;
  return 0;
}