Pagini recente » Cod sursa (job #1113555) | Cod sursa (job #1359601) | Cod sursa (job #198121) | Cod sursa (job #1762061) | Cod sursa (job #2223805)
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <tuple>
using namespace std;
const string IN_FILE = "strmatch.in";
const string OUT_FILE = "strmatch.out";
const int MAX_MATCHES = 1000;
vector<int> getMatches(const string& pattern, const string& text) {
const string s = pattern + "#" + text;
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[i] != s[p + 1]; p = pi[p]);
p += s[i] == s[p + 1] ? 1 : 0;
pi[i] = p;
if (pi[i] == int(pattern.length()) - 1) {
matches.push_back(i - 2 * pattern.length());
}
}
return matches;
}
pair<string, string> readInput() {
ifstream in(IN_FILE);
string pattern, text;
in >> pattern >> text;
in.close();
return make_pair(pattern, text);
}
void writeOutput(const vector<int> matches) {
ofstream out(OUT_FILE);
out << int(matches.size()) << "\n";
for (int i = 0; i < int(matches.size()); i++) {
out << matches[i] << (i + 1 < int(matches.size()) ? " " : "\n");
}
out.close();
}
int main() {
string pattern, text;
tie(pattern, text) = readInput();
auto matches = getMatches(pattern, text);
matches.resize(min(MAX_MATCHES, int(matches.size())));
writeOutput(matches);
return 0;
}