Input
The first line contains T, the number of test cases (T ≤ 200). Most of the test cases are relatively
small. T lines follow, each contains a string of only small latin letters ’a’ - ’z’, whose length N is less
than 1000, without any leading or trailing whitespaces.
Output
For each test case, output a single line, which should begin with the case number counting from 1,
followed by N integers. The X-th (1-based) of them should be the maximum length of the substring
which can be written as a concatenation of X same strings. If that substring doesn’t exist, output 0
instead. See the sample for more format details.
Hint: For the second sample, the longest substring which can be written as a concatenation of 2 same
strings is “noonnoon”, “oonnoonn”, “onnoonno”, “nnoonnoo”, any of those has length 8; the longest
substring which can be written as a concatenation of 3 same strings is the string itself. As a result, the
second integer in the answer is 8 and the third integer in the answer is 12.
Sample Input
2
arisetocrat
noonnoonnoon
Sample Output
Case #1: 11 0 0 0 0 0 0 0 0 0 0
Case #2: 12 8 12 0 0 0 0 0 0 0 0 0
题意:如果有一段字符串是由某一子串连续x次重复组成的,那么这段字符串的长度记做L1,L2……Ln,第x项表示L中最大的数。(x=1,2,3……len)
思路:首先想到用kmp的next数组求循环节,但是有个问题,这道题中循环出现的子串不一定是从s[0]开始的,有可能是中间某一段有循环节,所以用一个for(i=0;i<=len-1;i++)的大循环,每次对s+i进行kmp
然后先来纪念一下自己的错误代码
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
char s[1005];
int nextt[1005];
int a[1005];
void getnextt(char s[])
{
int j, k;
int len=strlen(s);
j = 0; k = -1; nextt[0] = -1;
while(j < len)
if(k == -1 || s[j] == s[k])
{
nextt[++j] = ++k;
}
else
k = nextt[k];
}
int main()
{
int T,Case=1;
scanf("%d",&T);
while(T--)
{
scanf("%s",s);
memset(a,0,sizeof(a));
int LEN=strlen(s);
a[1]=LEN;
for(int i=0;i<LEN;i++)
{
memset(nextt,0,sizeof(nextt));
getnextt(s+i);
int len=strlen(s+i);
for(int j=2;j<=len;j++)
//从这里开始都是凭感觉写的……例如abababab求出最小循环节是2,循环次数是4,那么a[4]=2,但是怎么继续去推出a[2]=4,难到了我……
if(j%(j-nextt[j])==0&&nextt[j]!=0)
{
int x=j/(j-nextt[j]);
int y=j-nextt[j];
while(x)
{
a[x]=max(a[x],y*x);
x/=2;
y*=2;
}
}
}
printf("Case #%d:",Case++);
for(int k=1;k<=LEN;k++)
printf(" %d",a[k]);
printf("\n");
}
return 0;
}
然后就是正确代码
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
char s[1005];
int nextt[1005];
int a[1005];
void getnextt(char s[])
{
int j, k;
int len=strlen(s);
j = 0; k = -1; nextt[0] = -1;
while(j < len)
if(k == -1 || s[j] == s[k])
{
nextt[++j] = ++k;
}
else
k = nextt[k];
}
int main()
{
int T,Case=1;
scanf("%d",&T);
while(T--)
{
scanf("%s",s);
memset(a,0,sizeof(a));
int LEN=strlen(s);
a[1]=LEN;
for(int i=0;i<LEN;i++)
{
memset(nextt,0,sizeof(nextt));
getnextt(s+i);
int len=strlen(s+i);
for(int j=2;j<=len;j++)
{
int tmp=j;
while(tmp)
{
tmp=nextt[tmp];
if(j%(j-tmp)==0)
{
int x=j/(j-tmp);
a[x]=max(a[x],j);
}
}
}
}
printf("Case #%d:",Case++);
for(int k=1;k<=LEN;k++)
printf(" %d",a[k]);
printf("\n");
}
return 0;
}