题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3746
题解:将所给的字符串变成多个完整的循环(至少两个),然后给出最少需要添加的字符数。见算法KMP.
#include <stdio.h> #include <string.h> #define MAXN 100001 char text[MAXN]; int next[MAXN]; void getNext() { int i=0,j=-1; next[0]=-1; while(text[i]!='\0') { if(j==-1||text[i]==text[j]) { i++; j++; next[i]=j; } else j=next[j]; } } int main() { int len,test,ans,i; scanf("%d",&test); while(test--) { scanf("%s",text); len=strlen(text); getNext(); /*for(i=0;i<=len;++i) printf("next[%d]=%d\n",i,next[i]);*/ ans=len-next[len];//循环节的长度 if(ans!=len&&len%ans==0) //循环多次 printf("0\n"); else//要加的字符个数 = 循环长度-(字符串长度-循环个数*循环长度) printf("%d\n",ans-next[len]%ans); } return 0; }