题目求P的前缀与S2的后缀相同的最长字符串,那么把P和S2连接起来,然后求next[n+m] 。

注意两种数据:

abcabcabc

abcabc

6

abc

abcabc

3

即需要讨论 next[n+m]>len(P) next=next[next[n + m]]  和   next[n+m]>len(S2) next=next[next[n + m]] 。

代码如下:

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<string>
 4 #include<string.h>
 5 #define N 50005
 6 using namespace std;
 7 char P[N*2];
 8 char S2[N];
 9 int m;
10 int next[N*2];
11  void Prefix_Func()
12  {
13      int i,k;
14      k=0;
15      next[1]=0;
16      for(i=2;i<=m;i++)
17      {
18         while(k>0 && P[k+1]!= P[i])
19             k=next[k];
20         if(P[k+1] == P[i])
21             k++;
22         next[i]=k;
23      }
24  }
25 int main()
26 {
27 
28     int n1,n2,k;
29     while(scanf("%s%s",P+1,S2+1)!=EOF)
30     {
31         n1=strlen(P+1);
32         n2=strlen(S2+1);
33         strcat(P+1,S2+1);
34         m=n1+n2;
35         Prefix_Func();
36         k=next[m];
37         while(k>n1 || k>n2)
38         {
39             k=next[k];
40         }
41         if(k)
42         {
43             for(int i=1;i<=k;i++)
44                 cout<<P[i];
45             cout<<" "<<k<<endl;
46         }
47         else
48             cout<<"0"<<endl;
49     }
50     return 0 ;
51 }