Average duration (kmp)
Question: Give a string with a length of n and ask whether the prefix of the string is a periodic string. If it is a periodic string, the position of the last letter of the output prefix and the shortest cycle
Idea: the use of the Nature of kmp string matching.
For the first I character, if f [I] is not equal to zero, it indicates that part of the prefix of this string is [0, f [I] is the same as this part of [I-f [I], I. If the I character is a periodic string, the staggered part [f [I], I] is exactly a cyclic section. (In other words, if f [I] is not equal to zero & [f [I], and I] is the two points in the cyclic section, it can be said that the first I characters constitute a periodic string)
Code:
#include
#include
#includeusing namespace std;const int maxn = 1000005;int f[maxn];char s[maxn];int n;void kmp(char* p,int* f){ f[0] = 0; f[1] = 0; for(int i = 1; i < n; i++){ int j = f[i]; while(j && p[j]!=p[i]) j = f[j]; f[i+1] = p[i] == p[j] ? j+1 : 0; }}int main(){ int cas = 0; while(scanf("%d",&n)){ if(n == 0) break; scanf("%s",s); kmp(s,f); printf("Test case #%d\n",++cas); for(int i = 2; i <= n; i++){ if(f[i] != 0 && i%(i-f[i])==0){ printf("%d %d\n",i,i/(i-f[i])); } } printf("\n"); } return 0;}
Understanding kmp can improve the accuracy rate