Description
You are given a string t t t consisting of n n n lowercase Latin letters and an integer number k k k.
Let’s define a substring of some string s s s with indices from l l l to r r r as s [ l … r ] s[l…r] s[l…r].
Your task is to construct such string s s s of minimum possible length that there are exactly k k k positions i i i such that s [ i … i + n − 1 ] = t 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 k substrings of s s s equal to t t t.
It is guaranteed that the answer is always unique.
Input
The first line of the input contains two integers n n n and k k k ( 1 ≤ n , k ≤ 50 ) (1≤n,k≤50) (1≤n,k≤50) — the length of the string t t t and the number of substrings.
The second line of the input contains the string t t t consisting of exactly n n n lowercase Latin letters.
Output
Print such string s s s of minimum possible length that there are exactly k k k substrings of s s s equal to t 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 KMP 算法,我们求出一个最长的相同前缀后缀长度,即 n e x t next next 数组,然后输出 k − 1 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[i],i∈[0,s.size()−next[n−1]],最后再输出 S 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;
}
总结
字符串算法没怎么写过题,很生疏。