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

Re:完全胡闹,故作高深。只需要把KMP深入理解,哪有什么技巧~

Posted by Liuzhaoliang at 2014-01-22 12:05:56 on Problem 3461
In Reply To:Re:完全胡闹,故作高深。只需要把KMP深入理解,哪有什么技巧~ Posted by:xuruoxin at 2013-11-02 10:34:48
> +1 理解getNext怎么来的就行了
就是标准的KMP?
每次匹配够了就记录一次。然后继续去匹配
#include<iostream>
#include<stdio.h>


char W[10010],T[1000010];
int N;
int next[10010];


//match W again T, return the occurence
int kmp()
{
    //compute next of W
    int n=strlen(W+1);
    int m=strlen(T+1);
    next[1]=0;
    int i,j=0;
    for(i=2;i<=n;i++)
    {
        while(j>0 && W[j+1]!=W[i]) j=next[j];
        if(W[j+1]==W[i]) j++;
        next[i]=j;
    }
    //for(int i=1;i<=n;i++)
    //  printf("fail %d->%d\n",i,next[i]);
    int cnt = 0;
    j=0;
    for(i=1;i<=m;i++)
    {
        while(j>0 && W[j+1]!=T[i]) j=next[j];
        if(W[j+1]==T[i]) j++;
        if(j==n) cnt++;//,printf("found %d\n",i);
        
    }
    return cnt;
}
int main()
{
    scanf("%d",&N);
    while(N--){
        scanf("%s",W+1);
        scanf("%s",T+1);
        printf("%d\n",kmp());
    }
    return 0;
}

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