HDU-1711-Number Sequence(kmp模板)

這是一道kmp模板題。

#pragma warning(disable:4996)
#include <stdio.h>

int main(void)
{
    // freopen("q.txt", "r", stdin);

    int T, t, s, f;
    int strLen, featureLen;
    unsigned int *stri, *feature, *next;
    stri = new unsigned int[1000000];
    feature = new unsigned int[10000];
    next = new unsigned int[10000];

    scanf("%d", &T);

    next[0] = 0;
    next[1] = 0;

    for (t = 0; t < T; t++) {
        // input

        scanf("%d %d", &strLen, &featureLen);

        for (s = 0; s < strLen; s++)
            scanf("%d", &stri[s]);

        for (f = 0; f < featureLen; f++)
            scanf("%d", &feature[f]);

        // kmp

        // get next
        for (s = 1, f = 0; s < featureLen - 1;) {
            if (feature[s] == feature[f]) {
                next[s + 1] = f + 1;
                s++;
                f++;
            }
            else {
                if (f == 0) {
                    next[s + 1] = 0;
                    s++;
                }
                else {
                    f = next[f];
                }
            }
        }

        // search
        for (s = 0, f = 0; s < strLen;) {
            if (stri[s] == feature[f]) {
                s++;
                f++;
                if (f == featureLen)
                    break;
            }
            else {
                if (f == 0) {
                    s++;
                }
                else {
                    f = next[f];
                }
            }
        }

        if (f == featureLen)
            printf("%d\n", s - featureLen + 1);
        else
            printf("-1\n");
    }

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章