http://poj.org/problem?id=3461
题目很简单,就是寻找给定的模式串在目标串中出现了多少次,采用KMP算法。代码如下:
/*
ID: csuchenan
Algorithm: KMP
PROG: POJ 3461 Oulipo
LANG: C++
*/
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<string>
using namespace std ;
const int maxn = 10005 ;
int next[maxn] ;
char patt[maxn] ;
string term ;
void init() ;
void KMP_match() ;
int main()
{
int n ;
cin>>n ;
cin.ignore() ;
while(n--)
{
cin.getline(patt + 1 , sizeof(patt) - 1) ;
getline(cin , term) ;
memset(next , 0 , sizeof(next)) ;
init() ;
KMP_match() ;
}
return 0 ;
}
void init()
{
int i ;
int k ;
int len = strlen(patt + 1) ;
next[1] = 0 ;
k = 0 ;
for(i = 2 ; i <= len ; i ++)
{
while(k > 0 && patt[k + 1] != patt[i])
k = next[k] ;
if(patt[k+1] == patt[i])
k ++ ;
next[i] = k ;
}
}
void KMP_match()
{
int lenp = strlen(patt + 1) ;
int lent = term.size() ;
int i = 0 ;
int q ;
int ncount ;
ncount = 0 ;
q = 0 ;
for(i = 0 ; i < lent ; i ++)
{
while(q > 0 && patt[q+1] != term[i] )
q = next[q] ;
if(patt[q+1] == term[i])
q = q + 1 ;
if(q == lenp)
{
q = next[q] ;
ncount ++ ;
}
}
cout<<ncount<<endl ;
}