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 len = strlen(in);
    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 < len - N; i++)
    {
        memcpy(tmp, in + i, N);
        if (strcmp(tmp, sub) < 0)
        {
            memcpy(sub, tmp, N);
        }
    }

    strcpy(out, sub);

    free(sub);
    free(tmp);
}

int main(void)
{
    int N;
    char *S, *U, *MIN;
    char *S_temp, *U_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));
    U_temp = (char *)calloc(N * 2 + 1, sizeof(char));
    scanf("%s", S);

    //printf("N = %d, K = %d, S = %s\n", N, K, S);

    while (count < K)
    {
        // Uを作成
        reverse(S, S_temp);
        strcpy(U, S);
        strcat(U, S_temp);

        // Uの反転文字列を作成
        reverse(U, U_temp);

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

        count++;
    }

    // Uを作成
    reverse(S, S_temp);
    strcpy(U, S);
    strcat(U, S_temp);

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

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

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

    return 0;
}