Test instructions: Give a string, Q: How many characters to fill to make it loop? such as ABC to fill 3 to become abcabc. If it has been looped, output 0.
Idea: KMP's next array is resolved. If the loop already appears, then the answer is 0. But not the loop? To be judged according to Next[len]. We have to use the fewest characters to make it loop, and all we know is to make the Loop section K=len-next[len] So long, that is, the beginning of the string is so long. As long as the string length is a multiple of k, at this time, K is the cyclic section.
In fact, the answer can be directly calculated, I use a loop to find it. The direct calculation should be len%k after the end of the small string length, fill k-len%k so many on the line, you can end not enough k to gather enough K.
Just pay special attention to the case of Len%len-next[len] 0, there may not even be a cycle festival! Double the string, then.
1#include <bits/stdc++.h>2 #defineLL Long Long3 #definePII pair<int,int>4 #defineINF 0x7f7f7f7f5 using namespacestd;6 Const intn=100010;7 CharStr[n];8 int_next[n];9 Ten voidGet_next (intlen) One { A_next[0]=-1; - intI=0, j=-1;//Pattern String - while(i<len) the { - if(j==-1|| Str[j]==str[i]) _next[++i]=++J; - Elsej=_next[j]; - } + } - + intMain () A { atFreopen ("Input.txt","R", stdin); - intT, len=0; -Cin>>T; - while(t--) - { -scanf"%s", str); inGet_next (len=strlen (str)); - if(_next[len]==0) printf ("%d\n", Len);//This is the case without a cyclic section. to Else if(len% (Len-_next[len]) = =0) puts ("0");//there's a loop. + Else //the whole string does not loop, the complement character loops - { the intI=1; * while(I<len && (len+i)% (Len-_next[len])! =0) i++;//try adding a matching character at a later time, without exceeding Len $printf"%d\n", i);Panax Notoginseng } - } the return 0; +}
AC Code
HDU 3746 Cyclic nacklace ring Necklace (KMP, follow link)