Cod sursa(job #2247045)

Utilizator preda.andreiPreda Andrei preda.andrei Data 27 septembrie 2018 20:11:55
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <string>
#include <vector>

using namespace std;

vector<int> FindPrefix(const string &str)
{
    vector<int> prefix(str.size());
    prefix[0] = -1;

    auto index = -1;
    for (size_t i = 1; i < str.size(); i += 1) {
        while (index >= 0 && str[index + 1] != str[i]) {
            index = prefix[index];
        }
        if (str[index + 1] == str[i]) {
            index += 1;
        }
        prefix[i] = index;
    }
    return prefix;
}

pair<int, vector<int>> FindMatches(const string &word, const string &text)
{
    static constexpr int kMatchLimit = 1000;
    auto count = 0;
    vector<int> pos;

    auto prefix = FindPrefix(word);
    auto index = -1;

    for (size_t i = 0; i < text.size(); i += 1) {
        while (index >= 0 && word[index + 1] != text[i]) {
            index = prefix[index];
        }
        if (word[index + 1] == text[i]) {
            index += 1;
        }
        if (index + 1 >= (int)word.size()) {
            if (count < kMatchLimit) {
                pos.push_back(i - word.size() + 1);
            }
            count += 1;
        }
    }
    return {count, pos};
}

int main()
{
    ifstream fin("strmatch.in");
    ofstream fout("strmatch.out");

    string word, text;
    getline(fin, word);
    getline(fin, text);

    auto matches = FindMatches(word, text);
    fout << matches.first << "\n";

    for (const auto &pos : matches.second) {
        fout << pos << " ";
    }
    fout << "\n";

    return 0;
}