Cod sursa(job #2772929)

Utilizator pregoliStana Andrei pregoli Data 3 septembrie 2021 13:41:10
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.68 kb

#include <bits/stdc++.h>
#define newline '\n'
using namespace std;
const string fname = "strmatch";
ifstream fin(fname + ".in");
ofstream fout(fname + ".out");
///************************

class RollingHash {
public:
    RollingHash(const string &text) {
        this->text = text;
    }

    vector<int64_t> getMatchingIndexes(const string &pattern) const noexcept {
        vector<int64_t> indexes;
        auto patternCode = getCode(pattern);
        const int64_t patternLen = pattern.size();
        auto poweredBasePair = getPoweredBase(patternLen);
        int64_t poweredBase[] = {
            poweredBasePair.first,
            poweredBasePair.second
        };

        int64_t match[] = {0, 0};
        for (int64_t i = 0; i < patternLen; i++) {
            for (int64_t j = 0; j < 2; j++) {
                match[j] = (match[j] * kBase + text[i]) % kHashPrimes[j];
            }
        }
        if (make_pair(match[0], match[1]) == patternCode) {
            indexes.push_back(0);
        }

        for (int64_t i = patternLen; i < (int64_t)text.size(); i++) {
            for (int64_t j = 0; j < 2; j++) {
                match[j] = ((match[j] - (poweredBase[j] * text[i - patternLen]) % kHashPrimes[j] + kHashPrimes[j])
                             * kBase + text[i]) % kHashPrimes[j];
            }

            if (make_pair(match[0], match[1]) == patternCode) {
                indexes.push_back(i - patternLen + 1);
            }
        }

        return indexes;
    }
private:
    const int64_t kHashPrimes[2] = {100003, 666013};
    static constexpr int64_t kBase = 137;
    string text;

    pair<int64_t, int64_t> getCode(const string &pattern) const noexcept {
        int64_t match[] = {0, 0};
        for (int64_t i = 0; i < (int64_t)pattern.size(); i++) {
            for (int64_t j = 0; j < 2; j++) {
                match[j] = (match[j] * kBase + pattern[i]) % kHashPrimes[j];
            }
        }
        return make_pair(match[0], match[1]);
    }

    pair<int64_t, int64_t> getPoweredBase(const int64_t &len) const noexcept {
        int64_t poweredBase[] = {1, 1};
        for (int64_t i = 1; i < len; i++) {
            for (int64_t j = 0; j < 2; j++) {
                poweredBase[j] = (poweredBase[j] * kBase) % kHashPrimes[j];
            }
        }
        return make_pair(poweredBase[0], poweredBase[1]);
    }
};

int main() {
    string text, pattern;
    fin >> pattern >> text;
    const auto rh = new RollingHash(text);
    auto ans = rh->getMatchingIndexes(pattern);
    fout << ans.size() << endl;
    for (const int64_t &nr : ans) {
        fout << nr << ' ';
    }
    fout << endl;
    return 0;
}