1. 程式人生 > >【題解】codeforces1029A[Codeforces Round #506 (Div. 3)]A.Many Equal Substrings KMP

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

題目連結

Description

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[lr]s[l…r].

Your task is to construct such string ss of minimum possible length that there are exactly k

k positions ii such that s[ii+n1]=ts[i…i+n−1]=t. In other words, your task is to construct such string s 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 n

n and kk (1n,k50)(1≤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 s

s equal to tt.

It is guaranteed that the answer is always unique.

Examples

jnput

3 4 aba

Output

ababababa

Input

3 2 cat

Output

catcat

類似 KMPKMP 演算法,我們求出一個最長的相同字首字尾長度,即 nextnext 陣列,然後輸出 k1k-1S[i],i[0,s.size()next[n1]]S[i],i∈\big[0,s.size()-next[n-1]\big],最後再輸出 SS

#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;
}

總結

字串演算法沒怎麼寫過題,很生疏。