Many Equal Substrings
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Problem Description
You are given a string tnk
Let’s define a substring of some string slrs[l…r]
Your task is to construct such string skis[i…i+n−1]=tskst
It is guaranteed that the answer is always unique.
Input
The first line of the input contains two integers nk1≤n,k≤50t
The second line of the input contains the string tn
Output
Print such string skst
It is guaranteed that the answer is always unique.
Examples
input
3 4
aba
output
ababababa
input
3 2
cat
output
catcat
题目描述:
题目大意时输入长度为n的字符串,让输出k次。此串可能时最大公公前后缀不为0的循环串,在每次重复输出的时候就可以部分输出。本题用到KMP算法中的核心:nxt [ ] 数组的计算。只要可以计算出每个字符的nxt [ ] ,寻找规律进行输出即可。
观察 a b a 的nxt[ ] 数组为:0 0 1,我们发现nxt [n - 1]是1。
c a t 的nxt[ ] 数组为:0 0 0,nxt[ n - 1]是0 。
我的思路时这样的:计算出 p串 的nxt [ ] 数组,不管原字符串是不是可循环的,先输出一次 串 p ,那么剩下的 k - 1 次就要用到nxt [n - 1] 代表的值。如果nxt [n - 1] 不为0,说明存在公共前后缀,那么就将从nxt [n - 1] 到n - 1的字符输出k - 1遍;如果nxt [n - 1] == 0,说明不存在公共前后缀,那么就将串 p 输出k - 1遍。
AC代码如下:
#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;
char t[2000];
char p[2000];
int nxt[2000];
//建立公共前后缀表, /*****next[j] = k 代表p[j] 之前的模式串子串中,有长度为k 的相同前缀和后缀*****/
void GetNext(char p[], int nxt[]){ //
int i, j;
int m = strlen(p);
nxt[0] = 0;
for(j = 1, i = 0; j < m; j++){ //前缀 i,从0开始 后缀j,从1开始
while(i > 0 && p[j] != p[i])
i = nxt[i-1];
if(p[j] == p[i]){ //前后匹配时,next就加一
i++;
}
nxt[j] = i; //①p[j] != p[i] && i == 0,赋值0
//②p[j] == p[i] && i == 0,i已经加一(i在原匹配串上增加)
} //③p[j] == p[i] && i != 0,回溯过后,给值为第一次匹配的后一位
}
int main(){
int n, m, k;
scanf("%d %d", &n, &k);
scanf("%s", p);
GetNext(p, nxt);
printf("%s",p);
if(nxt[n-1] != 0){
for(int t = 0; t < k-1; t++)
for(int i = nxt[n-1]; i < n; i++)
printf("%c", p[i]);
return 0;
}
else{
for(int t = 0; t < k-1; t++)
printf("%s", p);
}
return 0;
}