POJ 3461 Oulipo

 

链接:http://poj.org/problem?id=3461
 
题意:求模式串在主串中匹配的次数。(题目太啰嗦,直接看输入输出示例...)
 
分析:KMP的简单转化。

 

Source Code:

#include<stdio.h>
#include<string.h>
#define maxn 1000000

int next[maxn],len1,len2,cas;
char s[maxn],t[maxn];

void GetNext(){
    int i=0,j=-1;
    next[0]=-1;
    while(i<len2){
        if(j==-1||t[i]==t[j]){
            i++;j++;
            if(t[i]!=t[j]) next[i]=j;
            else           next[i]=next[j];
        }
        else j=next[j];
    }
}

int KMP(){
    int i=0,j=0,sum=0;
    GetNext();
    while(i<len1){
        if(j==-1||s[i]==t[j]){
            i++;j++;
            if(j>=len2){
                sum++;
                j=next[j];//注意这里的转化
            }
        }
        else j=next[j];
    }
    return sum;
}

int main()
{
    scanf("%d",&cas);
    while(cas--){
        scanf("%s %s",t,s);
        len1=strlen(s);
        len2=strlen(t);
        printf("%d\n",KMP());
    }
    return 0;
}


 

你可能感兴趣的:(POJ 3461 Oulipo)