poj 3461 Oulipo(KMP)

题目链接:http://poj.org/problem?id=3461

思路分析:字符串匹配问题,使用KMP算法解决。

 

代码如下:

#include <stdio.h>

char T[1000005], W[10005];
int Next[10005];
int Len_T, Len_W;

void GetNext( )
{
    int i = 0, j = -1;

    Next[0] = -1;
    if ( W[0] == '\0' )
        return;

    while ( i < Len_W )
    {
        if ( j == -1 || W[i] == W[j] )
        {
            ++i;
            ++j;
            Next[i] = j;
        }
        else
            j = Next[j];
    }
}

int Matcher( )
{
    int i = 0, j = 0, Count = 0;

    while ( i < Len_T )
    {
        if ( j == -1 || T[i] == W[j] )
        {
            ++i;
            ++j;
        }
        else
            j = Next[j];

        if( j == Len_W )
            Count++;
    }

    return Count;
}


int main( )
{
    int n;

    scanf( "%d\n", &n );
    while ( n-- )
    {
        int ans;
        char Tmp;
        Len_T = Len_W = 0;

        while ( ( Tmp = getchar( ) ) != '\n' )
            W[Len_W++] = Tmp;
        W[Len_W] = '\0';

        while ( ( Tmp = getchar( ) ) != '\n' )
            T[Len_T++] = Tmp;
        T[Len_T] = '\0';

        GetNext( );        
        ans = Matcher( );
        printf( "%d\n", ans );
    }

    return 0;
}

 

你可能感兴趣的:(poj)