Pagini recente » Cod sursa (job #2550524) | Cod sursa (job #2710325) | Cod sursa (job #753207) | Cod sursa (job #415498) | Cod sursa (job #2144387)
#include <iostream>
#include <cstring>
#include <fstream>
#include <vector>
using namespace std;
#define nmax 2000005
ifstream f("strmatch.in");
ofstream g("strmatch.out");
vector<int>stk;
char a[nmax],b[nmax];
int preKMP[nmax],value[nmax];
int len1,len2;
void read()
{
f.getline(a,nmax);
f.getline(b,nmax);
len1=strlen(a);
len2=strlen(b);
}
void prekmp()
{
int j=0;
for (int i=1; i<len1; ++i)
{
if (a[i]==a[j])
{
preKMP[i]=preKMP[i-1]+1;
++j;
}
else
{
j=preKMP[j-1];
while (1)
{
if (a[i]==a[j])
{
preKMP[i]=preKMP[j++]+1;
break;
}
if (j==0)
{
preKMP[i]=0;
break;
}
j=preKMP[j-1];
}
++j;
}
}
}
void kmp()
{
int j=0;
for (int i=0; i<len2; ++i)
{
if (a[j]==b[i])
{
value[i]=j+1;
j=min(len1-1,j+1);
}
else
{
j=preKMP[j];
while (1)
{
if (a[j]==b[i])
{
if (j>0)
{
if (a[j-1]==b[i-1])
value[i]=j+1;
else
value[i]=1;
}
else
value[i]=1;
break;
}
if (j==0)
{
value[i]=0;
break;
}
j=preKMP[j];
}
++j;
}
}
for (int i=0; i<len2; ++i)
if (value[i]==len1)
stk.push_back(i-len1+1);
g<<stk.size()<<'\n';
for (auto w:stk)
g<<w<<' ';
}
void solve()
{
prekmp();
kmp();
}
int main()
{
read();
solve();
return 0;
}