Qiuqiqiu  
不管道路多么崎岖坎坷,我永远不停下追逐梦想的脚步!

http://acm.hdu.edu.cn/showproblem.php?pid=1711

KMP

View Code
 1 #include <cstdio>
2 #include <cstring>
3 using namespace std;
4
5 const int M=10010,N=1000010;
6 int a[N],b[M];
7 int fail[M];
8 void kmp(const int *s,int l)
9 {
10 fail[0]=-1;
11 int i,j=-1;
12 for (i=1;i<l;i++)
13 {
14 while (j!=-1 && s[i]!=s[j+1]) j=fail[j];
15 if (s[i]==s[j+1]) j++;
16 fail[i]=j;
17 }
18 }
19 int match(const int *sa,const int *sb,int la,int lb)
20 {
21 int i,j=0;
22 for (i=0;i<la;i++)
23 {
24 while (j && sa[i]!=sb[j]) j=fail[j-1]+1;
25 if (sa[i]==sb[j]) j++;
26 if (j==lb) return i-lb+2;
27 }
28 return -1;
29 }
30 int main()
31 {
32 int T;
33 scanf("%d",&T);
34 int n,m,i;
35 while (T--)
36 {
37 scanf("%d%d",&n,&m);
38 for (i=0;i<n;i++) scanf("%d",&a[i]);
39 for (i=0;i<m;i++) scanf("%d",&b[i]);
40 kmp(b,m);
41 int ans=match(a,b,n,m);
42 printf("%d\n",ans);
43 }
44 return 0;
45 }

 

posted on 2012-03-14 08:36  Qiuqiqiu  阅读(136)  评论(0编辑  收藏  举报