Cod sursa(job #2773329)

Utilizator andcovAndrei Covaci andcov Data 6 septembrie 2021 15:29:42
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
//
// Created by Andrei Covaci on 03.09.2021.
//

//#include "005_strmatch.h"

#include <fstream>
#include <vector>

using namespace std;

ifstream in("strmatch.in");
ofstream out("strmatch.out");

const int BASE = 256;
const int PRIME_MODULUS = 101;
int OFFSET = 1;

pair<string, string> read() {
    pair<string, string> res;
    getline(in, res.first);
    getline(in, res.second);
    return res;
}

int hasher(string s) {
    int hash = s[0];
    for(int i = 1; i < s.size(); ++i) {
        hash *= BASE;
        hash %= PRIME_MODULUS;
        hash += s[i];
        hash %= PRIME_MODULUS;
    }

    return hash;
}

vector<int> solve(pair<string, string> strings) {
    string pattern = strings.first, s = strings.second;

    if(pattern.size() > s.size()) {
        return vector<int>();
    }

    auto pattern_hash = hasher(pattern);
    auto curr_hash = hasher(s.substr(0, pattern.size()));
    vector<int> pos;

    for(int i = 0; i < pattern.size() - 1; ++i) {
        OFFSET %= PRIME_MODULUS;
        OFFSET *= BASE;
    }

    for(int i = 0; i <= s.size() - pattern.size(); ++i) {
        if (pattern_hash == curr_hash && s.substr(i, pattern.size()) == pattern) {
            pos.push_back(i);
        }

        curr_hash = ((curr_hash + PRIME_MODULUS - s[i] * OFFSET % PRIME_MODULUS) * BASE + s[i + pattern.size()]) % PRIME_MODULUS;
    }

    return pos;
}

void print(vector<int> res) {
    out << res.size() << '\n';
    if(res.size() > 1000) {
        for(int i = 0; i <= 1000; ++i) {
            out << res[i] << ' ';
        }
    } else {
        for(auto pos : res) {
            out << pos << ' ';
        }
    }
}

int main() {
    auto nums = read();
    auto res = solve(nums);
    print(res);


    return 0;
}