Pagini recente » Cod sursa (job #3325518) | Cod sursa (job #3347758) | Cod sursa (job #242909) | Cod sursa (job #3313951) | Cod sursa (job #3333335)
#include <bits/stdc++.h>
using namespace std;
ifstream input("strmatch.in");
ofstream output("strmatch.out");
const int LIM = 2000010;
string pattern, source;
int lps[LIM], positions[LIM];
int lenPattern, lenSource, totalMatches;
void buildLPS() {
int idx = 1, len = 0;
while (idx < lenPattern) {
if (pattern[idx] == pattern[len]) {
lps[idx++] = ++len;
} else {
if (len)
len = lps[len - 1];
else
lps[idx++] = 0;
}
}
}
void findPattern() {
int i = 0, j = 0;
while (i < lenSource) {
if (source[i] == pattern[j]) {
i++; j++;
if (j == lenPattern) {
positions[++totalMatches] = i - j;
j = lps[j - 1];
}
} else {
if (j)
j = lps[j - 1];
else
i++;
}
}
output << totalMatches << "\n";
if (totalMatches > 1000) totalMatches = 1000;
for (int k = 1; k <= totalMatches; k++)
output << positions[k] << " ";
}
int main() {
input >> pattern;
input >> source;
lenPattern = pattern.size();
lenSource = source.size();
buildLPS();
findPattern();
return 0;
}