hdu 1711 Number Sequence (kmp)

http://acm.hdu.edu.cn/showproblem.php?pid=1711
kmp 템 플 릿
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
using namespace std;

typedef long long LL;
#define N 1100000
#define INF 0x3f3f3f3f
#define met(a, b) memset (a, b, sizeof(a))

int n, m, a[N], b[N], Next[N];

void Get_Next ()
{
    int i = 0, j = -1;
    Next[i] = j;

    while (i<m)
    {
        if (j==-1 || b[i]==b[j])
            Next[++i] = ++j;
        else j = Next[j];
    }
    return;
}

int kmp ()
{
    int i = 0, j = 0;
    Get_Next ();
    while (i<n && j<m)
    {
        if (j==-1 || a[i]==b[j])
            i++, j++;
        else j = Next[j];

        if (j==m) return i-m+1;
    }
    return -1;
}

int main ()
{
    int t;
    scanf ("%d", &t);

    while (t--)
    {
        scanf ("%d %d", &n, &m);
        for (int i=0; i<n; i++)
            scanf ("%d", &a[i]);
        for (int i=0; i<m; i++)
            scanf ("%d", &b[i]);

        printf ("%d
", kmp()); } }

좋은 웹페이지 즐겨찾기