Cod sursa(job #2223806)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 21 iulie 2018 16:25:19
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#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 * int(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";
    const int n = min(MAX_MATCHES, int(matches.size()));
    for (int i = 0; i < n; i++) {
        out << matches[i] << (i + 1 < n ? " " : "\n");
    }
    out.close();
}

int main() {
    string pattern, text;
    tie(pattern, text) = readInput();
    const auto matches = getMatches(pattern, text);
    writeOutput(matches);
    return 0;
}