hiho1015(kmp+统计出现次数)

时间:2023-03-09 19:09:36
hiho1015(kmp+统计出现次数)

http://hihocoder.com/problemset/problem/1015

时隔多天再次温习了一下KMP

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int Next[]; //小写回编译错误
void kmp_pre(char x[], int m)
{
int i,k;
Next[] = -;
k = -;
i = ;
while(i < m)
{
while(- != k && x[i] != x[k])
k = Next[k] ;
if(x[i + ] == x[k + ])
Next[++i] = Next[++k];
else
Next[++i] = ++k;
}
}
int kmp_Count(char x[], int m, char y[],int n)
{
int i,j;
int ans = ;
kmp_pre(x,m);
i = j = ;
while(i < n)
{
while(- != j && y[i] != x[j])
j = Next[j];
i++;
j++;
if(j >= m)
{
ans++;
j = Next[j];
}
}
return ans;
}
int main()
{
int n;
char t[ + ],p[ + ];
scanf("%d", &n);
while(n--)
{
scanf("%s%s", t,p);
int m = strlen(t);
int n = strlen(p);
printf("%d\n",kmp_Count(t,m,p,n));
}
return ;
}

KMP讲解

http://www.cnblogs.com/tangzhengyue/p/4315393.html