【CF 1029A】Many Equal Substrings 字符串KMP

                                 A. Many Equal Substrings

You are given a string tt consisting of nn lowercase Latin letters and an integer number kk.

Let’s define a substring of some string ss with indices from ll to rr as s[l…r]s[l…r].

Your task is to construct such string ss of minimum possible length that there are exactly kk positions ii such that s[i…i+n−1]=ts[i…i+n−1]=t. In other words, your task is to construct such string ss of minimum possible length that there are exactly kk substrings of ss equal to tt.

It is guaranteed that the answer is always unique.

Input

The first line of the input contains two integers nn and kk (1≤n,k≤501≤n,k≤50) — the length of the string tt and the number of substrings.

The second line of the input contains the string tt consisting of exactly nn lowercase Latin letters.

Output

Print such string ss of minimum possible length that there are exactly kk substrings of ss equal to tt.

It is guaranteed that the answer is always unique.

Examples

input

3 4
aba

output

ababababa

input

3 2
cat

output

catcat

 

题意:给出长度为n的字符串,将其循环输出k次,其中首尾相同的部分可以重叠,例如两个aba合在一起可以由aba aba变成ababa。求循环后的最小字符串长度。

数据较小,暴力应该就能过,不过最近在写KMP,刚好用上,也挺方便的。

思路就是把最小循环节输出k次,然后补上循环节后面的字符串。

KMP算法详解推荐博文:超详细理解:kmp算法next数组求解过程和回溯的含义

之后自己也写一个QAQ

代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<cmath>
#include<set>
#include<map>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a))
#define closeio std::ios::sync_with_stdio(false)

int next[55];
char s[55];
void kmp(char *s,int *next,int len) {
	next[0]=-1;
	int k=-1;
	for(int q=1; q<len; q++) {
		while(k>-1&&s[k+1]!=s[q])
			k=next[k];
		if(s[k+1]==s[q])
			k++;
		next[q]=k;
	}
}
int main() 
{
	int n,m,i,j,len;
	closeio;
	cin>>n>>m;
	cin>>s;
	kmp(s,next,n);
	/*for(i=0;i<n;i++)
	cout<<next[i]<<endl;*/
	len=n-next[n-1]-1;                //len即为最小循环节长度
	//cout<<n<<" "<<len<<endl;
	for(i=0;i<m;i++)
	{
		for(j=0;j<len;j++)
		cout<<s[j];
	}
	for(i=len;i<n;i++)
	cout<<s[i];
	return 0;
}

 

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/Xylon_/article/details/82047879
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞