首页 > 其他 > 详细

[板子]KMP

时间:2017-11-08 17:10:12      阅读:350      评论:0      收藏:0      [点我收藏+]

KMP板子,你甚至可以用这个板子A掉luogu的3375

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<queue>
 6 using namespace std;
 7 
 8 char a[1000001],b[1001];
 9 int nexta[1001];
10 
11 int main()
12 {
13     int na,nb,i,j,k,w,e,s;
14     
15     scanf("%s%s",a,b);
16     na=strlen(a);
17     nb=strlen(b);
18     
19     for(i=1;i<nb;i++)
20     {
21         j=nexta[i];
22         while(j!=0&&b[i]!=b[j])
23         {
24             j=nexta[j];
25         }
26         if(b[i]==b[j])
27         {
28             nexta[i+1]=j+1;
29         }
30         else
31         {
32             nexta[i+1]=0;
33         }
34     }
35     j=0;
36     for(i=0;i<na;i++)
37     {
38         while(j!=0&&a[i]!=b[j])
39         {
40             j=nexta[j];
41         }
42         if(a[i]==b[j])
43         {
44             j++;
45         }
46         if(j==nb)
47         {
48             printf("%d\n",i-nb+2);
49         }
50     }
51     
52     for(j=1;j<=nb;j++)
53     {
54         printf("%d ",nexta[j]);
55     }
56     return 0;
57 }

 

[板子]KMP

原文:http://www.cnblogs.com/Fylsea/p/7804377.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!