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>
#include <boost/range/algorithm.hpp>
#include <boost/range/numeric.hpp>
#define FOR(i,k,n)  for(int i = (k);i < (n);++i)
#define REP(i,n)    FOR(i,0,n)

using namespace std;
using ll = int64_t;
using vecint = vector<int>;
using vecll = vector<ll>;

int pw2(int i, int n) {
  if (i == 0) return 1;
  if ((i%2) == 1) return min(n, 2*pw2(i-1, n));
  int h = pw2(i/2, n);
  return min(n, h*h);
}

int main()
{
  int n,k;
  cin>>n>>k;
  string s;
  cin>>s;
  char mn = *boost::min_element(s);
  int cnt = 0;
  string t = s;
  boost::reverse(t);
  string st = s + t;
  int mxlen = 0;
  vecint starts;
  REP(i,2*n) {
    if(st[i] == mn) {
      ++cnt;
    } else {
      if (cnt > mxlen) starts.clear();
      if (cnt >= mxlen) {
        starts.push_back(i-cnt);
        mxlen = cnt;
      }
      cnt = 0;
    }
  }
  if (k == 1) {
    string res(n, mn+1);
    REP(i,n) {
      res = min(res, st.substr(i, n));
    }
    cout<<res<<endl;
    return 0;
  }
  int len = min(n, mxlen * pw2(k-1, n));
  if (len == n) {
    cout<<string(n, mn)<<endl;
    return 0;
  }
  int rem = n-len;
  string res(n, mn+1);
  string prefix(len, mn);
  for (int stt : starts) {
    if (stt + mxlen < n) continue;
    auto tmp = st.substr(stt-rem, rem) + prefix;
    boost::reverse(tmp);
    res = min(res, tmp);
  }
  cout<<res<<endl;
  return 0;
}