kmp Writings on the Wall Virtual Judge5876

来源:互联网 发布:北斗卫星定位软件 编辑:程序博客网 时间:2024/06/02 05:10
#include <algorithm>#include <cstring>#include <cstdio>char str[2][50005];int next[50005];void getnext( char *str ){    int i, j;    int len=strlen( str );    i=0, j=-1;    next[0]=-1;    while( i<len )    {        if( j==-1 || str[i]==str[j] )        {            i++;j++;            next[i]=j;        }        else            j=next[j];    }}int kmp(){    int i=0, j=0, ans=0;    int sublen=strlen( str[1] );    int len=strlen( str[0] );    while( i<len )    {        if( str[1][j]==str[0][i] || j==-1 )        {            i++;j++;        }        else            j=next[j];    }    while( j )    {        j=next[j];        ans++;    }    return ans;}int main(){    int t;    scanf( "%d", &t );    while( t-- )    {        scanf( "%s%s", str[0], str[1] );        getnext( str[1] );        printf( "%d\n", kmp()+1 );    }    return 0;}

0 0
原创粉丝点击