题意
求串W在串T中出现的次数,可重叠。
题解
kMP模板。
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;
int t;
int Next[10001];
void kmp_pre(string x)
{
int i, j;
j = Next[0] = -1;
i = 0;
while(i < (int)x.length())
{
while(-1 != j && x[i] != x[j]) j = Next[j];
Next[++i] = ++j;
}
}
void preKMP(string& x)
{
int i, j;
j = Next[0] = -1;
i = 0;
while(i < (int)x.length())
{
while(-1 != j && x[i] != x[j]) j = Next[j];
if(x[++i] == x[++j]) Next[i] = Next[j];
else Next[i] = j;
}
}
int KMP(string W, string T)
{
//kmp_pre(W); //125MS
preKMP(W); //94MS
int ans = 0;
int i = 0, j = 0;
while(i < (int)T.length())
{
while(-1 != j && T[i] != W[j]) j = Next[j];
i++, j++;
if(j >= (int)W.length())
{
ans++;
j = Next[j];
}
}
return ans;
}
int main()
{
#ifdef LOCAL
fstream cin("data.in");
#endif // LOCAL
ios::sync_with_stdio(0);
cin.tie(0);
string W, T;
for(cin >> t; t--; )
{
cin >> W >> T;
cout << KMP(W, T) << endl;
}
return 0;
}