625B - War of the Corporations
分析:KMP,找出模式串在主串中出现的位置,然后总的个数减去重叠的个数就行
#include <iostream>
#include <cstring>
using namespace std;
const int N = 100002;
int next[33];
char S[N], T[33];
int slen, tlen;
int a[N],cnt;
void getNext()
{
int j, k;
j = 0; k = -1; next[0] = -1;
while(j < tlen)
if(k == -1 || T[j] == T[k])
next[++j] = ++k;
else
k = next[k];
}
void KMP_Index()
{
int i = 0, j = 0;
getNext();
while(1){
while(i < slen && j < tlen)
{
if(j == -1 || S[i] == T[j])
{
i++; j++;
}
else
j = next[j];
}
if(j == tlen)
a[cnt++]=i-tlen,j=0;
if(i>=slen)break;
}
}
int main()
{
int TT;
int i, cc;
cin>>S>>T;
slen = strlen(S);
tlen = strlen(T);
cnt=0;
KMP_Index();
int ans=0;
for( i=0;i<cnt;){
int k=a[i]+tlen-1;
i++;
while(i<cnt&&a[i]<=k)i++,ans++;
}
cout<<cnt-ans<<endl;
return 0;
}