HDU 3746 Cyclic Nacklace【KMP】
题意: 给你一个字符串,要求将字符串的全部字符最少循环2次需要添加的字符数。
分析: next 数组的巧用。
View Code
#include<stdio.h> #include<string.h> int next[100005]; char b[100005]; int len; void get() { int i=0,j=-1; next[0]=-1; while(i<len) { if(j==-1||b[i]==b[j]) next[++i]=++j; else j=next[j]; } } int main() { int t,k,i; scanf("%d",&t); while(t--) { scanf("%s",b); len=strlen(b); get(); k=len-next[len]; if(k!=len&&len%k==0) printf("0\n"); else printf("%d\n",k-next[len]%k); } return 0; }