-
KMP-Codeforces 1029A-Many Equal Substrings
-
题目链接:
-
题目基础:
-
思路:
题目大意:
给一个长度为n的字符串t,求一个最短长度串,使得有k个位置,满足s[i…i+n−1]=ts[i…i+n−1]=t
题解:
其实就是求最长后缀,最长后缀:Len-Next[Len]
然后把字符串t的前一部分(去除后缀)输出k-1次,然后再输出一次t
-
代码:
#include <iostream>
#include<cstring>
using namespace std;
int Next[60];
void KMP(char Str[])
{
int i = 0, k = -1;
Next[0] = -1;
int len=strlen(Str);
while (i < len)
{
if (k == -1 || Str[i] == Str[k])
{
++i;
++k;
Next[i] = k;
}
else
k = Next[k];
}
}
int main()
{
char Str[60];
int n,k;
while(cin>>n>>k)
{
cin>>Str;
KMP(Str);
int Pre_Len=n-Next[n];
char Again_str[60];
strncpy(Again_str,Str,Pre_Len);
Again_str[Pre_Len]='\0';
for(int i=1;i<=k-1;i++)
cout<<Again_str;
cout<<Str<<endl;
}
return 0;
}