Pagini recente » Cod sursa (job #2834144) | Cod sursa (job #730065) | Cod sursa (job #135391) | Cod sursa (job #39800) | Cod sursa (job #1947122)
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
const string IN_FILE = "strmatch.in";
const string OUT_FILE = "strmatch.out";
vector<int> match(const string& pattern, const string& whereToSearch) {
const string S = pattern + "#" + whereToSearch;
auto pi = vector<int>(int(S.length()), -1);
auto matches = vector<int>();
for (int i = 1, p = -1; i < int(S.length()); i++) {
for (; p != -1 && S[p + 1] != S[i]; p = pi[p]);
p += (S[p + 1] == S[i] ? 1 : 0);
pi[i] = p;
if (pi[i] == int(pattern.length()) - 1) {
matches.push_back(i - 2 * int(pattern.length()));
}
}
return matches;
}
int main() {
ifstream in(IN_FILE);
string pattern, whereToSearch;
in >> pattern >> whereToSearch;
in.close();
const auto matches = match(pattern, whereToSearch);
ofstream out(OUT_FILE);
out << int(matches.size()) << "\n";
const int n = min(1000, int(matches.size()));
for (int i = 0; i < n; i++) {
out << matches[i] << (i + 1 < n ? " " : "\n");
}
out.close();
return 0;
}