Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

第一次KMP,1A,贴代码

Posted by speedcell4 at 2011-10-15 16:38:50 on Problem 3461
#include<iostream>

using namespace std;

const int MAXN = 1000012;

#ifndef _KMP_
#define _KMP_
int tcase,next[MAXN];
char s[MAXN],p[MAXN];

int KMP(char s[],char p[]);
void SetNextArray(char p[],int next[]);
#endif

int main()
{
    scanf("%d",&tcase);getchar();while(tcase--)
    {
        gets(s),gets(p);
        printf("%d\n",KMP(p,s));
    }
    return 0;
}

int KMP(char s[],char p[])
{
    SetNextArray(p,next);
    int cnt=0;
    for(int i=0,j=0,ls=strlen(s),lp=strlen(p);ls-i>0;)
    {
        if(j==-1||s[i]==p[j])
        {
            i++;
            j++;
        }
        else j=next[j];
        if(j==lp) cnt++;
    }
    return cnt;
}
void SetNextArray(char p[],int next[])
{
    memset(next,0,sizeof(next)); next[0]=-1;
    for(int i=0,j=-1,l=strlen(p);l-i>0;)
    {
        if(j==-1||p[i]==p[j])
        {
            i++;
            j++;
            next[i]=j;
        }
        else j=next[j];
    }
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator