Problem Link : http://lightoj.com/volume_showproblem.php?problem=1255
Solve :
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll int f[1000003];
void kmp_preprocess(string pattern)
{
ll int m=pattern.size();
f[0]=0;
ll int j=0;
for(ll int i=1;i<m;i++)
{
if(pattern[i]==pattern[j])
{
f[i]=j+1;
j++;
}
else
{
while(j!=0)
{
j=f[j-1];
if(pattern[i]==pattern[j])
{
f[i]=j+1;
j++;
break;
}
}
}
}
}
ll int kmp(string text,string pattern)
{
ll int j=0,cnt=0;
ll int n=text.size();
ll int m=pattern.size();
for(ll int i=0;i<n;i++)
{
if(text[i]==pattern[j])
{
j++;
if(j==m)
{
cnt++;
j=f[j-1];
}
}
else
{
while(j!=0)
{
j=f[j-1];
if(text[i]==pattern[j])
{
j++;
break;
}
}
}
}
return cnt;
}
int main()
{
string text,pattern;
ll int t,n=0;
scanf("%lld",&t);
for(ll int ca=1;ca<=t;ca++)
{
cin>>text>>pattern;
memset(f,0,sizeof(f));
kmp_preprocess(pattern);
n=kmp(text,pattern);
printf("Case %lld: %lld\n",ca,n);
}
}
No comments:
Post a Comment