SOJ 2652: Oulipo

题目链接:http://cstest.scu.edu.cn/soj/problem.action?id=2652

 

题目大意:

给出一个母串和一个子串。

求子串在母串出现的次数。

 

算法:

字符串匹配模板题,可用KMP或BM算法。

我用的是KMP算法。

好吧。。我是不会承认我学ACM这么久但是现在才学KMP呢 >_<

 

代码如下:

#include <cstdio>
#include <cstring>

const int maxn = 1100000;
char a[maxn], b[maxn];
int next[maxn];

void getnext()
{
    int len = strlen(a);
    for (int j = next[0] = -1, i = 0; i <= len; )
    {
        if(j == -1 || a[i] == a[j])
        {
            i ++;
            j ++;
            next[i] = j;
        }
        else
        {
            j = next[j];
        }
    }
}

int solve()
{
    int cot = 0;
    for (int i = 0, j = 0; b[i]; )
    {
        if(j == -1 || a[j] == b[i])
        {
            i ++;
            j ++;
            if(a[j] == '\0')
            {
                cot ++;
                j = next[j];
            }
        }
        else
        {
            j = next[j];
        }
    }
    return cot;
}

int main()
{
    int cas;
    scanf("%d", &cas);
    while (cas --)
    {
        scanf("%s %s", a, b);
        getnext();
        printf("%d\n", solve());
    }
    return 0;
}


 

你可能感兴趣的:(SOJ 2652: Oulipo)