Pagini recente » Cod sursa (job #467391) | Cod sursa (job #2581209) | Cod sursa (job #1651399) | Cod sursa (job #435402) | Cod sursa (job #996199)
Cod sursa(job #996199)
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;
const int Lmax = 2000002;
int L[Lmax];
char Pattern[Lmax], Text[Lmax];
vector <int> match;
int P, T;
void read()
{
ifstream f("strmatch.in");
f >> ( Pattern + 1 );
f >> ( Text + 1 );
Pattern[0] = ' ';
Text[0] = ' ';
P = strlen ( Pattern ) - 1;
T = strlen ( Text ) - 1;
f.close();
}
void prefix()
{
L[1] = 0;
int k = 0;
for ( int p = 2; p <= P; ++p )
{
while ( k > 0 && Pattern[k + 1] != Pattern[p] )
k = L[k];
if ( Pattern[k + 1] == Pattern[p] )
k++;
L[p] = k;
}
}
void KMP()
{
int k = 0;
for ( int t = 1; t <= T; ++t )
{
while ( k > 0 && Pattern[k + 1] != Text[t] )
k = L[k];
if ( Pattern[k + 1] == Text[t] )
k++;
if ( k == P )
{
match.push_back( t - P );
k = L[k];
}
}
}
void print()
{
ofstream g("strmatch.out");
g << match.size() << "\n";
for ( unsigned i = 0; i < min( match.size(), (unsigned)1000 ); ++i )
g << match[i] << " ";
g << "\n";
g.close();
}
int main()
{
read();
prefix();
KMP();
print();
return 0;
}