Pagini recente » Cod sursa (job #872495) | Cod sursa (job #2487030) | Cod sursa (job #1389757) | Cod sursa (job #47418) | Cod sursa (job #1096751)
/* Potrivirea sirurilor algoritmul KMP */
#include <fstream>
#include <string>
using namespace std;
#define MAX 2000001
ifstream f("strmatch.in");
ofstream g("strmatch.out");
string a, b;
int Pre[MAX], Sol[1001], Nr;
void Prefix()
{
for (int i = 2, K = 0; i < a.length(); i++)
{
while (a[K + 1] != a[i] && K != 0) K = Pre[K];
if (a[K + 1] == a[i])
{
K++;
}
Pre[i] = K;
}
}
void KMP()
{
for (int i = 1, K = 0; i < b.length(); i++)
{
while (a[K + 1] != b[i] && K != 0) K = Pre[K];
if (a[K + 1] == b[i])
{
K++;
}
if (K == a.length() - 1)
{
if (Nr < 1000)
{
Sol[++Nr] = i - a.length() + 1;
}
K = Pre[K];
}
}
}
int main()
{
f >> a;
f >> b;
a = " " + a;
b = " " + b;
Prefix();
KMP();
g << Nr << "\n";
for (int i = 1; i <= min(1000, Nr); i++)
{
g << Sol[i] << " ";
}
}