原題連結:
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 1000002char 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);elseprintf("%d\n",len);}}return 0;}#endif