UVA5876 Writings on the Wall 扩展KMP

 扩展KMP的简单题。

#include<stdio.h>
#include<string.h>
#define maxn 51010
char s[maxn],t[maxn];
int extand[maxn],next[maxn];
void getnext(char *t)
{
    int i,k,j,len=strlen(t);
    next[0]=len;
    i=0;
    while(i<len-1&&t[i]==t[i+1])
    {
        i++;
    }
    next[1]=i;
    int a=1;
    for(k=2;k<len;k++)
    {
        int p=next[a]+a-1;
        int l=next[k-a];
        if(k-1+l>=p)
        {
            int j=p-k+1>0?p-k+1:0;
            while(k+j<len&&t[k+j]==t[j])
                j++;
            next[k]=j;
            a=k;
        }
        else next[k]=l;
    }
}
void ekmp(char *s,char *t)
{
    int i,j,slen=strlen(s),tlen=strlen(t),k;
    getnext(t);
    int minlen=slen<tlen?slen:tlen;
    int a=0;
    while(a<minlen&&s[a]==t[a])    a++;
    extand[0]=a;
    a=0;
    
    for(k=1;k<slen;k++)
    {
        int p=a+extand[a]-1;
        int l=next[k-a];
        if(k-1+l>=p)
        {
            int j=p-k+1>0?p-k+1:0;
            while(k+j<slen&&j<tlen&&s[k+j]==t[j])
                j++;
            extand[k]=j;
            a=k;
        }
        else extand[k]=l;
    }
}
int main()
{
    int i,j,tt;
    scanf("%d",&tt);
    while(tt--)
    {
        scanf("%s %s",s,t);
        ekmp(s,t);
        int len=strlen(s);
        int ans=0;
        for(i=0;i<len;i++)
        {
            //printf("%d %d\n",extand[i],len-i);
            if(extand[i]>=len-i)
                ans++;
        }
        printf("%d\n",ans+1);
    }
}

 

posted @ 2015-08-18 08:21  sweat123  阅读(160)  评论(0编辑  收藏  举报