Cod sursa(job #2277167)

Utilizator preda.andreiPreda Andrei preda.andrei Data 5 noiembrie 2018 20:50:31
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#include <string>
#include <vector>

using namespace std;

vector<int> GetPrefix(const string &str)
{
    vector<int> prefix(str.size(), 0);
    auto pos = 0;

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

pair<int, vector<int>> GetMatches(const string &pattern, const string &text)
{
    constexpr auto kMaxMatches = 1000;
    vector<int> matches;
    auto match_count = 0;

    auto prefix = GetPrefix(pattern);
    auto pos = 0;

    for (size_t i = 0; i < text.size(); i += 1) {
        while (pos > 0 && text[i] != pattern[pos]) {
            pos = prefix[pos - 1];
        }
        if (text[i] == pattern[pos]) {
            pos += 1;
        }
        if (pos >= (int)pattern.size()) {
            match_count += 1;
            if (match_count <= kMaxMatches) {
                matches.push_back({(int)(i - pattern.size() + 1)});
            }
            pos = prefix[pos - 1];
        }
    }

    return {match_count, matches};
}

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

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

    auto matches = GetMatches(pattern, text);
    fout << matches.first << "\n";

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

    return 0;
}