hdu 1711 KMP

刚学Sunday算法,都说Sunday比KMP快,于是我用Sunday打了半天,一直TLE,最后还是用KMP过了。不知道是不是我对Sunday算法的理解不正确,还是它只适合真正字符串的模式匹配。

/*
* hdu1711/linux.cpp
* Created on: 2011-8-20
* Author : ben
*/
#include
<stdio.h>
#include
<stdlib.h>
#include
<string.h>
#include
<math.h>

#define MAX_PAR_LEN 10005
#define MAX_TXT_LEN 1000005
int pattern[MAX_PAR_LEN], text[MAX_TXT_LEN];
int nextval[MAX_PAR_LEN], parlen, txtlen;

void get_nextval() {
int i = 0, j = -1;
nextval[
0] = -1;
while (i < parlen) {
if (j < 0 || pattern[i] == pattern[j]) {
i
++;
j
++;
if (pattern[i] != pattern[j]) {
nextval[i]
= j;
}
else {
nextval[i]
= nextval[j];
}
}
else {
j
= nextval[j];
}
}
}

int index_kmp() {
int i, j;
get_nextval();
i
= j = 0;
while (i < txtlen && j < parlen) {
if (j == -1 || text[i] == pattern[j]) {
i
++;
j
++;
}
else {
j
= nextval[j];
}
}
if (j == parlen) {
return i - j;
}
else {
return -2;
}
}

void work() {
int T, i;
scanf(
"%d", &T);
while (T--) {
scanf(
"%d%d", &txtlen, &parlen);
for (i = 0; i < txtlen; i++) {
scanf(
"%d", &text[i]);
}
for (i = 0; i < parlen; i++) {
scanf(
"%d", &pattern[i]);
}
printf(
"%d\n", index_kmp() + 1);
}
}

int main() {
#ifndef ONLINE_JUDGE
freopen(
"data.in", "r", stdin);
#endif
work();
return 0;
}
posted @ 2011-08-29 14:58  moonbay  阅读(204)  评论(0编辑  收藏  举报