Pagini recente » Cod sursa (job #2589857) | Cod sursa (job #1661165) | Cod sursa (job #2008280) | Cod sursa (job #925803) | Cod sursa (job #3170500)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
char txt[2000010], pat[2000010];
int lps[2000005];
int sol[1005], solutions;
void computeLPS(int length) {
int last = 0;
lps[last] = 0;
int i = 1;
while (i < length) {
if (pat[i] == pat[last])
lps[i++] = ++last;
else {
if (last != 0)
last = lps[last - 1];
else
lps[i++] = 0;
}
}
}
void kmp() {
int n = strlen(txt);
int m = strlen(pat);
computeLPS(m);
int i = 0, j = 0;
while (n - i >= m - j) {
if (txt[i] == pat[j])
i++, j++;
if (j == m) {
solutions++;
if (solutions < 1000)
sol[solutions - 1] = i - j;
j = lps[j - 1];
} else if (i < n && txt[i] != pat[j]){
if (j != 0)
j = lps[j - 1];
else
i++;
}
}
}
int main() {
fin >> pat;
fin >> txt;
kmp();
fout << solutions << "\n";
for (int i = 0; i < solutions && i < 1000; i++)
fout << sol[i] << " ";
}