hdu 1711(kmp)

来源:互联网 发布:达观数据公司简介 编辑:程序博客网 时间:2024/06/05 02:12

题意:给出模式串和目标串,如果模式串有在目标串出现,输出出现的位置(最小),否则输出-1.

题解:kmp模板题。

#include <stdio.h>#include <string.h>const int N = 1000005;int p[N], t[N], len1, len2, next[N];void getnext() {int pp = -1, k = 0;next[0] = -1;while (k < len2) {if (pp == -1 || p[pp] == p[k]) {k++;pp++;next[k] = pp;}elsepp = next[pp];}}int kmp() {int pp = 0, tt = 0;while (pp < len2 && tt < len1) {if (pp == -1 || t[tt] == p[pp]) {pp++;tt++;}elsepp = next[pp];}if (pp == len2)return tt - len2;elsereturn -1;}int main() {int cases;scanf("%d", &cases);while (cases--) {scanf("%d%d", &len1, &len2);for (int i = 0; i < len1; i++)scanf("%d", &t[i]);for (int i = 0; i < len2; i++)scanf("%d", &p[i]);getnext();int ans = kmp();if (ans != -1)printf("%d\n", ans + 1);elseprintf("%d\n", ans);}return 0;}


0 0
原创粉丝点击