• 主页
• 问答

# kmp

fx397993401 2010-07-26 07:43:55

//if( pat[j] > 0) return -2;
//else return i-j;
return ((j==b)?(i-b) :-2);

# include<stdio.h>
# include<string.h>
int fail[10000+1];
long a,b;
int kmp(int* str, int* pat){
int i, j, k;
memset(fail, -1, sizeof(fail));
//fail[0] = 0;
for (i = 1; i<b; ++i) {
for (k=fail[i-1]; k>=0 && pat[i]!=pat[k+1];k=fail[k]);
if (pat[k + 1] == pat[i]) fail[i] = k + 1;
//if(k == 0) fail[i] = k + 1;
}
i = j = 0;
while( i< a && j < b ){ // By Fandywang
if( pat[j] == str[i] ) ++i, ++j;
else if(j == 0)++i;//第一个字符匹配失败，从str下个字符开始
else j = fail[j-1]+1; }
//if( pat[j] > 0) return -2;
//else return i-j;
return ((j==b)?(i-b) :-2);
}
int src[1000000+1];
int dest[10000+1];
int main()
{
int T,i;

//freopen("1284.txt","r",stdin);
scanf("%d",&T);
while(T--)
{
scanf("%ld%ld\n",&a,&b);
for(i = 0; i < a; i ++)
scanf("%d",&src[i]);
// src[i] = '\0';
for(i = 0; i < b; i ++)
scanf("%d",&dest[i]);
// dest[i] = '\0';
printf("%d\n",kmp(src,dest)+1);

}
return 0;
}
...全文
76 点赞 收藏 5

5 条回复

cliffbaby 2010-07-30
kmp 是不是 做个 next 数组 更方便？

fx397993401 2010-07-30
[Quote=引用 3 楼 cliffbaby 的回复:]

kmp 是不是 做个 next 数组 更方便？
[/Quote]

failure 数组 就是next

fx397993401 2010-07-30
[Quote=引用 2 楼 oraclewu 的回复:]

[/Quote]

oraclewu 2010-07-27

fx397993401 2010-07-26

//if( pat[j] > 0) return -2;
//else return i-j;
return ((j==b)?(i-b) :-2);

3.2w+