Pagini recente » Cod sursa (job #1018933) | Cod sursa (job #2571427) | Cod sursa (job #632672) | Cod sursa (job #1996428) | Cod sursa (job #2121244)
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;
ifstream f("strmatch.in" );
ofstream g("strmatch.out");
char A[2000001], B[2000001];
int state[2000001];
int suffixe[2000001];
void InitializareAutomat(char A[])
{
int m = strlen(A+1);
suffixe[1] = 0;
int i = 0;
for ( int j=2; j<=m; j++ )
{
while ( i>0 && A[i+1] != A[j] )
i = suffixe[i];
if ( A[i+1] == A[j] ) i++;
suffixe[j] = i;
}
}
void KMP(char A[], char B[])
{
int m = strlen(A+1);
int n = strlen(B+1);
for ( int i=1; i<=n; i++ )
if ( B[i] == A[state[i-1]+1] )
state[i] = state[i-1]+1;
else
{
int k = suffixe[state[i-1]];
while ( k>0 && B[i] != A[k+1] ) k = suffixe[k];
state[i] = k+1;
}
}
int main()
{
f.getline(A+1, 2000000);
f.getline(B+1, 2000000);
int m = strlen(A+1);
int n = strlen(B+1);
InitializareAutomat(A);
KMP(A, B);
vector<int> output;
for ( int i=1; i<=n; i++ )
if ( state[i] == m )
output.push_back(i-m);
g << output.size() << '\n';
for ( int i=0; i<min(unsigned(1000), output.size()); i++ )
g << output[i] << ' ';
}