Average duration (kmp)

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.