原题链接:
http://acm.hust.edu.cn/thx/problem.php?id=1010
这道题理解起来不难,一般来说第一种解决方案就是暴力求解,但对于ACM题来说,暴力求解往往会得到TLE,也就是超时。
该题实际上在考察KMP算法。KMP算法的介绍详见:http://baike.baidu.com/view/659777.htm
KMP算法是字符串匹配的经典算法,它通过给每个字符串定义一个特有的特征向量来逐个匹配字符,使得算法的复杂度由一般的O(m*n)变成了O(m+n),大大缩短了匹配时间。此题关键在于寻找特征向量的规律性,从而快速得到答案。
该题源码如下:
#define HUST_1010
#ifdef HUST_1010
#include <iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
#define N 1000002
char B[N];
int nextx[N];
void getnext(int next[],char s[],int l)
{
int i=1,j=0;
next[1]=0;
while(i<l)
{
if(j==0 || s[i]==s[j])
{
i++;j++;
next[i]=j;
}
else
{
j=next[j];
}
}
}
int main()
{
//freopen("TEST\\1010-input.txt","r",stdin);
//freopen("TEST\\1010-output.txt","w",stdout);
int len;
int sum;
while(scanf("%s",B+1)!=EOF)
{
sum = 0;
len = strlen(B+1);
if(len == 1) printf("1\n");
else
{
getnext(nextx,B,len);
sum = len - nextx[len];
if( (B[len] == B[len%sum]) || (len%sum == 0 && (B[len] == B[sum]) ) )
printf("%d\n",sum);
else
printf("%d\n",len);
}
}
return 0;
}
#endif