HDU 1711 Number Sequence(模板题)

#include <cstdio>

const int MAXN = 1000010;
const int MAXL = 10010;

int N, M;

int textS[MAXN];
int tarS[MAXL];
int next[MAXL];

void GetNextVal( int* s, int* nextval, int len )
{
    int i = 0, j = -1;
    nextval[0] = -1;
    while ( i < len )
    {
        if ( j == -1 || s[i] == s[j] )
        {
            ++i, ++j;
            nextval[i] = j;
        }
        else j = nextval[j];
    }
    return;
}

int KMP( int *t, int lent, int *s, int lens )
{
    GetNextVal( t, next, lent );
    int i = 0, j = 0;
    while ( j < lens )
    {
        if ( i == -1 || s[j] == t[i] )
        {
            ++i, ++j;
            if ( i == lent ) return j;
        }
        else i = next[i];
    }
    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", &textS[i] );
        for ( int i = 0; i < M; ++i ) scanf( "%d", &tarS[i] );

        int ans = KMP( tarS, M, textS, N );
        if ( ans < 0 ) printf( "%d\n", ans );
        else printf("%d\n", ans - M + 1 );
    }
    return 0;
}
View Code

相关文章:

  • 2021-12-16
  • 2021-11-19
  • 2022-12-23
  • 2021-07-03
  • 2021-10-20
  • 2022-12-23
  • 2021-05-20
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-20
相关资源
相似解决方案