Pagini recente » Cod sursa (job #397834) | Cod sursa (job #2600346) | Cod sursa (job #19655) | Cod sursa (job #2601853) | Cod sursa (job #3250424)
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
vector<int> buildPrefixTable(const string &A) {
int m = A.length();
vector<int> prefix(m, 0);
int j = 0;
for (int i = 1; i < m; i++) {
while (j > 0 && A[i] != A[j]) {
j = prefix[j - 1];
}
if (A[i] == A[j]) {
j++;
}
prefix[i] = j;
}
return prefix;
}
void KMP(const string &A, const string &B, vector<int> &positions) {
int n = B.length();
int m = A.length();
vector<int> prefix = buildPrefixTable(A);
int j = 0;
for (int i = 0; i < n; i++) {
while (j > 0 && B[i] != A[j]) {
j = prefix[j - 1];
}
if (B[i] == A[j]) {
j++;
}
if (j == m) {
positions.push_back(i - m + 1);
j = prefix[j - 1];
}
}
}
int main() {
ifstream in("strmatch.in");
ofstream out("strmatch.out");
string A, B;
in>>A>>B;
vector<int> positions;
KMP(A, B, positions);
int N = positions.size();
out << N << endl;
for (int i = 0; i < min(N, 1000); i++) {
out << positions[i] << (i < min(N, 1000) - 1 ? " " : "");
}
out << endl;
return 0;
}