Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

poj 3461 kmp

$
0
0
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=1e6+9;
int next[maxn];
char a[maxn],b[maxn];
int main()
{
//    freopen("in.txt","r",stdin);
    int tcase;
    scanf("%d",&tcase);
    while(tcase--)
    {
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        scanf("%s %s",&a[1],&b[1]);
        next[1]=0;
        int n=strlen(&a[1]);
        int m=strlen(&b[1]);
        for(int i=2;i<=n;i++)
        {
            int t=i-1;
            while(t&&a[i]!=a[next[t]+1])
            t=next[t];
            next[i]=next[t]+(a[i]==a[next[t]+1]);
        }
        int ans=0;
        for(int i=1,j=1;i<=m;i++)
        {
            while(j>1&&a[j]!=b[i])
            j=next[j-1]+1;
            if(a[j]==b[i])
            {
                if(j==n)
                {
                    ans++;
                    j=next[j]+1;
                }
                else
                j++;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}


作者:yrleep 发表于2013-6-6 1:11:11 原文链接
阅读:48 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>