Pagini recente » Cod sursa (job #1240607) | Cod sursa (job #2573233) | Cod sursa (job #1881287) | Cod sursa (job #1854173) | Cod sursa (job #1127997)
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
const int RADIX = 125;
const int MAXLEN = 2000005;
string pattern, text;
int patternLength, textLength, NrSol;
int DFA[MAXLEN][RADIX];
vector<int> Sol;
void Read() {
fin >> pattern;
patternLength = pattern.length();
fin >> text;
textLength = text.length();
}
void BuildDFA() {
int X = 0;
DFA[0][pattern[0]] = 1;
for (int i = 1; i <= patternLength; ++i) {
for (int c = '0'; c <= 'z'; ++c)
DFA[i][c] = DFA[X][c];//copy mismatch cases
if (i == patternLength) continue;
DFA[i][pattern[i]] = i + 1;//equality case
X = DFA[X][pattern[i]];//update X
}
}
void KMP() {
int X = 0;//the state in which we are
for (int c = 0; c < textLength; ++c) {
X = DFA[X][text[c]];
if (X == patternLength) {
++NrSol;
if (NrSol <= 1000)
Sol.push_back(c - patternLength + 1);
}
}
}
void Write() {
fout << NrSol << '\n';
for (int it = 0; it < min((int)Sol.size(), 1000); ++it)
fout << Sol[it] << ' ';
}
int main() {
Read();
cerr << "Data read.\n";
BuildDFA();
cerr << "DFA built.\n";
KMP();
cerr << "KMP done.\n";
Write();
cerr << "Data written.\n";
fin.close();
fout.close();
return 0;
}