【题解】codeforces1029A[Codeforces Round #506 (Div. 3)]A.Many Equal Substrings KMP

题目链接

Description

You are given a string t t consisting of n n lowercase Latin letters and an integer number k k .

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

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

It is guaranteed that the answer is always unique.

Input

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

The second line of the input contains the string t t consisting of exactly n n lowercase Latin letters.

Output

Print such string s s of minimum possible length that there are exactly k k substrings of s s equal to t t .

It is guaranteed that the answer is always unique.

Examples

jnput

3 4
aba

Output

ababababa

Input

3 2
cat

Output

catcat


类似 K M P KMP 算法,我们求出一个最长的相同前缀后缀长度,即 n e x t next 数组,然后输出 k 1 k-1 S [ i ] , i [ 0 , s . s i z e ( ) n e x t [ n 1 ] ] S[i],i∈\big[0,s.size()-next[n-1]\big] ,最后再输出 S S

#include<cstdio>
#include<iostream>
using namespace std;
int nx[110];
int main()
{
	//freopen("in.txt","r",stdin);
	int n,k;
	string s;
	cin>>n>>k>>s;
	for(int i=1,j=0;i<s.size();i++)
	{
		while(j&&s[i]!=s[j])j=nx[j-1];
		if(s[i]==s[j])j++;
		nx[i]=j;
	}
	int len=s.size()-nx[n-1];
	for(int i=1;i<k;i++)
	    cout<<s.substr(0,len);
	cout<<s;
	return 0;
}

总结

字符串算法没怎么写过题,很生疏。

猜你喜欢

转载自blog.csdn.net/qq_41958841/article/details/82829180