Cod sursa(job #2723577)

Utilizator vladm98Munteanu Vlad vladm98 Data 14 martie 2021 23:05:04
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.01 kb
#include <bits/stdc++.h>

using namespace std;

pair <int, int> hashes[2000005]; //hash[i] = s[i] + baza * s[i + 1] + baza ^ 2 * s[i + 2] + ... + baza ^ j * s[i + j] + ...
//Tinem o pereche pentru ca vom folosi 2 baze si 2 modulo
pair <int, int> powers[2000005]; //powers[i] = baza ^ i
pair <int, int> bases = {123, 217};
pair <int, int> modulos = {666013, 1000000007};

void buildHashes(string text) {
    int n = text.size();
    for (int i = n; i >= 1; --i) {
        hashes[i].first = (1LL * hashes[i + 1].first * bases.first + text[i - 1]) % modulos.first;
    }
}

void buildPowers(string text) {
    int n = text.size();
    powers[0] = {1, 1};
    for (int i = 1; i <= n; ++i) {
        powers[i].first = 1LL * powers[i - 1].first * bases.first % modulos.first;
    }
}

pair <int, int> buildPatternHash(string pattern) {
    int n = pattern.size();
    pair <int, int> hash = {0, 0};
    for (int i = n; i >= 1; --i) {
        hash.first = (1LL * hash.first * bases.first + pattern[i - 1]) % modulos.first;
    }
    return hash;
}

pair <int, int> buildTextHash(int left, int right) {
    return {((hashes[left].first - 1LL * hashes[right + 1].first * powers[right - left + 1].first) % modulos.first + modulos.first) % modulos.first,
            0};
}

bool patternMatch(pair <int, int> hash, int left, int right) {
    return hash == buildTextHash(left, right);
}

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

    string pattern, text;
    fin >> pattern >> text;

    buildHashes(text);
    buildPowers(text);
    pair <int, int> hash = buildPatternHash(pattern);
    int cnt = 0;
    for (int i = 1; i + pattern.size() - 1 <= text.size(); ++i) {
        if (patternMatch(hash, i, i + pattern.size() - 1)) {
            cnt += 1;
        }
    }
    fout << cnt << "\n";
    cnt = 0;
    for (int i = 1; i + pattern.size() - 1 <= text.size(); ++i) {
        if (cnt < 1000 and patternMatch(hash, i, i + pattern.size() - 1)) {
            cnt += 1;
            fout << i - 1 << " ";
        }
    }
    return 0;
}