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 (GCC 5.4.1) (judge verdict: Time Limit Exceeded)

#include <stdio.h>
#include <malloc.h>
#include <string.h>

void reverse(char *in, char *out)
{
    int i, j = 0;
    int len = strlen(in);
    for (i = len - 1; i >= 0; i--)
    {
        out[j] = in[i];
        j++;
    }
    out[j] = 0;
}

void searchMin(char *in, char *out, int N)
{
    int i;
    char *sub = (char *)calloc(N + 1, sizeof(char));
    char *tmp = (char *)calloc(N + 1, sizeof(char));

    memcpy(sub, in, N);

    for (i = 1; i < N; i++)
    {
        if (sub[i] < *(in + i))
            continue;

        memcpy(tmp, in + i, N);
        if (strcmp(tmp, sub) < 0)
        {
            memcpy(sub, tmp, N);
        }
    }

    memcpy(out, sub, N);

    free(sub);
    free(tmp);
}

int main(void)
{
    int N;
    char *S, *U, *S_temp;
    int K;
    int count = 1;

    scanf("%d %d", &N, &K);
    S = (char *)calloc(N + 1, sizeof(char));
    S_temp = (char *)calloc(N + 1, sizeof(char));
    U = (char *)calloc(N * 2 + 1, sizeof(char));
    scanf("%s", S);

    reverse(S, S_temp);

    while (count < K)
    {
        // Uを作成
        memcpy(U, S, N);
        memcpy(U + N, S_temp, N);

        // 最小文字列を検索
        searchMin(U, S_temp, N);
        reverse(S_temp, S);

        count++;
    }

    // Uを作成
    memcpy(U, S, N);
    memcpy(U + N, S_temp, N);

    // 最小文字列を検索
    searchMin(U, S, N);

    printf("%s\n", S);

    free(S);
    free(S_temp);
    free(U);

    return 0;
}