Cod sursa(job #1947122)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 30 martie 2017 19:19:46
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#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;
}