HDU 3336 Count the string KMP

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=3336


如果你是ACMer,那么请点击看下


题意:求每一个的前缀在母串中出现次数的总和。


AC代码:

 

#include <iostream>

#include <cstdio>

#include <cstdlib>

#include <cmath>

#include <cstring>

#include <string>

#include <vector>

#include <list>

#include <deque>

#include <queue>

#include <iterator>

#include <stack>

#include <map>

#include <set>

#include <algorithm>

#include <cctype>

using namespace std;



typedef long long LL;

const int N=200005;

const LL II=100000000;

const int INF=0x3f3f3f3f;

const double PI=acos(-1.0);



int next[N],c[N],ans,len;

char str[N];



void getNext(char *p)

{

    memset(c,0,sizeof(c));

    int j=0,k=-1;

    next[0]=-1;ans=0;

    while(j<len)//len是p的长度

    {

        if(k==-1||p[j]==p[k])

        {

            if(k!=-1)

            {

                c[j]=c[k]+1;

                ans+=c[j];

            }

            j++;

            k++;

            next[j]=k;

        }

        else

            k=next[k];

    }

}



int main()

{

    int i,j,T;

    cin>>T;

    while(T--)

    {

        scanf("%d%s",&len,str);

        getNext(str);

        printf("%d\n",(ans+len)%10007);

    }

    return 0;

}


 

 

你可能感兴趣的:(String)