poj 1961 Period (KMP)

题目:http://poj.org/problem?id=1961

题意:跟2406 差不多,算是2406的升级版。就是每一个字符都要加一个判断。。

next匹配

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 char t[1000005];
 7 int len_t,ne[1000005];
 8 void get_next()
 9 {
10     int i=0,j=-1,x;
11     ne[0]=-1;
12     while(i<len_t)
13     {
14         if(j==-1||t[i]==t[j])
15         {
16         ++i; ++j;
17         ne[i]=j;
18 
19         x=i-j;
20         if(i%x==0&&i/x>=2)
21         cout<<i<<" "<<i/x<<endl;
22         }
23         else
24         j=ne[j];
25     }
26 }
27 int main()
28 {
29     int x=1;
30     while(~scanf("%d",&len_t)&&len_t)
31     {
32         scanf("%s",t);
33         printf("Test case #%d
",x++);
34         get_next();
35         cout<<endl;
36     }
37     return 0;
38 }

next_val匹配

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 char t[1000005];
 7 int len_t,ne[1000005];
 8 void get_next()
 9 {
10     int i=0,j=-1,x;
11     ne[0]=-1;
12     while(i<len_t)
13     {
14         if(j==-1||t[i]==t[j])
15         {
16         ++i; ++j;
17         if(t[i]!=t[j])
18         ne[i]=j;
19         else
20         ne[i]=ne[j];
21 
22         x=i-j;
23         if(i%x==0&&i/x>=2)
24         cout<<i<<" "<<i/x<<endl;
25         }
26         else
27         j=ne[j];
28     }
29 }
30 int main()
31 {
32     int x=1;
33     while(~scanf("%d",&len_t)&&len_t)
34     {
35         scanf("%s",t);
36         printf("Test case #%d
",x++);
37         get_next();
38         cout<<endl;
39     }
40     return 0;
41 }
原文地址:https://www.cnblogs.com/bfshm/p/3495330.html