[kmp] doj 1045 Number Sequence

#include <iostream>
#include <cstdio>
using namespace std;
const int N = 1000005;
const int M = 10005;
 
int s[N], t[M];
int next[M];
void get_next(int len) {
    int i = 0, j = -1;
    next[0] = -1;
    while(i < len-1) {
        if(j == -1 || t[i] == t[j]) {
            ++i, ++j; next[i] = j;
        }
        else j = next[j];
    }
}
int kmp(int slen, int tlen) {
    int i = 0, j = 0;
    while(i < slen && j < tlen) {
        if(j == -1 || s[i] == t[j]) {
            ++i, ++j;
        }
        else j = next[j];
    }
    if(j == tlen) return i - j + 1;
    else return -1;
}
int main() {
    int T, n, m;
    cin >> T;
    while(T--) {
        cin >> n >> m;
        for(int i = 0; i < n; ++i) {
            cin >> s[i];
        }
        for(int i = 0; i < m; ++i) {
            cin >> t[i];
        }
        get_next(m);
        cout << kmp(n, m) << endl;
    }
    return 0;
}
 
/**************************************************************
    Problem: 1045
    User: robby
    Language: C++
    Result: Accepted
    Time:0 ms
    Memory:5664 kb
****************************************************************/

posted @ 2013-04-08 16:13  小尼人00  阅读(145)  评论(0编辑  收藏  举报