hdoj1711-- Number Sequence(KMP模板)

题目大意:KMP模板题

思路:可百度到视频

代码:

#include <cstdio>
#include <cstring>
using namespace std;

const int maxn = 1000000+5;
const int maxm = 10000+5;

int n, m, kase;
int s[maxn], t[maxm], next[maxm];

void get_next() {
    next[0] = -1;
    int i = 0, j = -1;
    while(i < m) {
        if(j == -1 || t[i] == t[j]) {
            i++, j++;
            next[i] = j;
        }
        else j = next[j];
    }
}

int kmp() {
    int i = 0, j = 0;
    while(i < n && j < m) {
        if(j == -1 || s[i] == t[j])
            i++, j++;
        else j = next[j];
    }
    if(j == m) return i-m+1;
    else return -1;
}

int main() {
    scanf("%d", &kase);
    while(kase--) {
        scanf("%d%d", &n, &m);
        memset(s, 0, sizeof(s));
        memset(t, 0, sizeof(t));
        memset(next, 0, sizeof(next));
        for(int i = 0; i < n; i++)
            scanf("%d", &s[i]);
        for(int i = 0; i < m; i++)
            scanf("%d", &t[i]);
        get_next();
        printf("%d\n", kmp());
    }
    return 0;
}

你可能感兴趣的:(字符串,hdoj)