codeforces 149E Martian Strings(KMP)

题目链接:http://codeforces.com/problemset/problem/149/E

题意:给定一个串S和一个串T,在S找出四个位置a,b,c,d(a<=b<c<=d),使得S[a,b]+S[c,d]=T?

思路:S和T匹配一次,记录T的位置i能匹配到S的最小位置;翻转S和T再匹配一次。





char s1[N],s2[N],p1[N],p2[N];

int n,Next1[N],Next2[N];



void reverse(char *s,int len)

{

    int L=0,R=len-1;

    while(L<R) swap(s[L++],s[R--]);

}



void getNext(char s[],int len,int next[])

{

    next[0]=-1;

    int i=0,j=-1;

    while(i<len)

    {

        if(j==-1||s[i]==s[j]) next[++i]=++j;

        else j=next[j];

    }

}





int pos[2][N];



void match(char s[],int sLen,char p[],int pLen,int next[],int pos[])

{

    int i=0,j=0;

    while(i<sLen)

    {

        if(j==-1||s[i]==p[j])

        {

            i++;j++;

            pos[j]=min(pos[j],i);

        }

        else j=next[j];

        if(j==pLen) j=next[j];

    }

}



int main()

{

    RD(s1);

    int len=strlen(s1);

    strcpy(s2,s1); reverse(s2,len);

    int ans=0,i,j,L;

    RD(n);

    while(n--)

    {

        RD(p1); strcpy(p2,p1); L=strlen(p1); reverse(p2,L);

        if(L<=1) continue;

        FOR1(i,L) pos[0][i]=pos[1][i]=INF;

        getNext(p1,L,Next1);

        match(s1,len,p1,L,Next1,pos[0]);



        getNext(p2,L,Next2);

        match(s2,len,p2,L,Next2,pos[1]);

        FOR1(i,L) if(pos[0][i]+pos[1][L-i]<=len)

        {

            ans++;

            break;

        }

    }

    PR(ans);

    return 0;

}

  

你可能感兴趣的:(codeforces)