Pagini recente » Cod sursa (job #2724247) | Cod sursa (job #2917979) | Cod sursa (job #2975744) | Cod sursa (job #262149) | Cod sursa (job #1420718)
// KMP - O(N+M)
#include <fstream>
#include <cstring>
#include <vector>
#define Nmax 2000099
using namespace std;
ifstream f("strmatch.in");
ofstream g("strmatch.out");
int N, M;
char A[Nmax], B[Nmax];
vector<int> sol;
void KMP(const char A[Nmax], const char B[Nmax], vector<int> &sol) {
int phi[Nmax], q, N, M;
N = strlen(A+1), M = strlen(B+1);
for (int i = 0; i <= N; i++) {
phi[i] = 0;
}
q = 0;
phi[1] = 0;
for(int i = 2; i <= N; ++i) {
while(q && A[q+1] != A[i]) q = phi[q];
if(A[q+1] == A[i]) ++q;
phi[i] = q;
}
q = 0;
for(int i = 1; i <= M; ++i) {
while(q && A[q+1] != B[i]) q = phi[q];
if(A[q+1] == B[i]) ++q;
if(q == N) {
sol.push_back(i-N+1);
q = phi[N];
}
}
}
int main() {
f >> (A+1) >> (B+1) ;
N = strlen(A+1);
M = strlen(B+1);
KMP(A, B, sol);
g << sol.size() << '\n';
for(int i = 0; i < min((int)sol.size(), 1000); ++i) g << sol[i] - 1 << ' ';
g << '\n';
f.close();g.close();
return 0;
}