【題解】codeforces1029A[Codeforces Round #506 (Div. 3)]A.Many Equal Substrings KMP
Description
You are given a string consisting of lowercase Latin letters and an integer number .
Let’s define a substring of some string with indices from to as .
Your task is to construct such string of minimum possible length that there are exactly positions such that . In other words, your task is to construct such string s of minimum possible length that there are exactly substrings of equal to .
It is guaranteed that the answer is always unique.
Input
The first line of the input contains two integers and — the length of the string and the number of substrings.
The second line of the input contains the string consisting of exactly lowercase Latin letters.
Output
Print such string of minimum possible length that there are exactly substrings of equal to .
It is guaranteed that the answer is always unique.
Examples
jnput
3 4 aba
Output
ababababa
Input
3 2 cat
Output
catcat
類似 演算法,我們求出一個最長的相同字首字尾長度,即 陣列,然後輸出 個 ,最後再輸出 。
#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;
}
總結
字串演算法沒怎麼寫過題,很生疏。