Pagini recente » Cod sursa (job #443733) | Cod sursa (job #2138971) | Cod sursa (job #2405246) | Cod sursa (job #2134807) | Cod sursa (job #2087100)
#include <bits/stdc++.h>
using namespace std;
ifstream f("strmatch.in");
ofstream g("strmatch.out");
vector<int> makePrefix (string pattern) {
vector<int> F (pattern.length() + 1, 0);
int j = 0;
for (int i = 2; i <= pattern.length(); i++) {
while ((j > 0) && (pattern[j] != pattern[i - 1])) {
j = F[j];
}
if (pattern[j] == pattern[i - 1]) {
j = j + 1;
}
F[i] = j;
}
return F;
}
vector<int> kmp(string text, string pattern) {
vector<int> F = makePrefix(pattern);
int indexText = 0, indexPattern = 0, countMatch = 0;
vector<int> solution;
while(true) {
if (indexText == text.length()) {
break;
}
if (text[indexText] == pattern[indexPattern]) {
++indexText;
++indexPattern;
if(indexPattern == pattern.length()) {
solution.push_back(indexText - indexPattern);
countMatch++;
if(countMatch == 1000) {
break;
}
indexPattern = F[indexPattern];
}
}else if (indexPattern > 0) {
indexPattern = F[indexPattern];
}else {
indexText++;
}
}
return solution;
}
int main()
{
/*vector <int> preffixMatch = makePrefix("AAAA");
for (vector<int>::iterator it = preffixMatch.begin(); it != preffixMatch.end(); it++) {
cout<<*it<<" ";
}*/
string pattern, text;
f>>pattern>>text;
vector <int> solution = kmp(text, pattern);
g<<solution.size()<<"\n";
for (vector<int>::iterator it = solution.begin(); it != solution.end(); it++) {
g<<*it<<" ";
}
return 0;
}