题意:给出两个串w和t,求w在t中出现的次数,不同次数可以覆盖。
思路:可以做一次扩展KMP,求出以t的每一位作起点与w的匹配长度,然后扫一遍结果,达到w的长度就加一。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int mod = 1000000007;
const int maxn = 1000005;
int extend[maxn], nxt[10005];
void get_next(char str[]){
int i = 0, j, pos;
int len = strlen(str);
nxt[0] = len;
while(i + 1 < len && str[i] == str[i + 1]){
++i;
}
nxt[1] = i;
pos = 1;
for(i=2; i<len; ++i){
if(nxt[i - pos] < pos + nxt[pos] - i){
nxt[i] = nxt[i - pos];
} else {
j = nxt[pos] + pos - i;
if(j < 0){
j = 0;
}
while(i + j < len && str[i + j] == str[j]){
++j;
}
nxt[i] = j;
pos = i;
}
}
}
void EXKMP(char target[], char pattern[]){
int i = 0, j, pos;
get_next(pattern);
int len1 = strlen(target);
int len2 = strlen(pattern);
while(i < len1 && i < len2 && target[i] == pattern[i]){
++i;
}
extend[0] = i;
pos = 0;
for(i=1; i<len1; ++i){
if(nxt[i - pos] < pos + extend[pos] - i){
extend[i] = nxt[i - pos];
} else {
j = extend[pos] + pos - i;
if(j < 0){
j = 0;//从头匹配
}
while(i + j < len1 && j < len2 && target[i + j] == pattern[j]){
++j;
}
extend[i] = j;
pos = i;//更新pos
}
}
}
char w[10005], t[maxn];
int main(){
int T;
scanf("%d", &T);
while(T--){
scanf("%s%s", w, t);
EXKMP(t, w);
int ans = 0;
int l1 = strlen(t);
int l2 = strlen(w);
for(int i = 0; i < l1; ++i){
if(extend[i] == l2){
++ans;
}
}
printf("%d\n", ans);
}
return 0;
}