Cod sursa(job #2959157)

Utilizator cristiWTCristi Tanase cristiWT Data 29 decembrie 2022 22:09:39
Problema Potrivirea sirurilor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>

#define int long long

using namespace std;

const int p = 53, mod = 1e9 + 7, NMAX = 2e6;
string a, b;
int hb[NMAX];

int id(char ch) {
    if (islower(ch)) return char(ch - 'a');
    return char(ch - 'A' + 26);
}

int inv(int _a) {
    int _b = mod - 2, _ans = 1;
    while (_b) {
        if (_b & 1) _ans = (_ans * _a) % mod;
        _a = (_a * _a) % mod;
        _b /= 2;
    }
    return _ans;
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    freopen("strmatch.in", "r", stdin);
    freopen("strmatch.out", "w", stdout);

    cin >> a >> b;
    int ha = 0, pw = 1;
    for (auto ch: a) {
        ha = (ha + id(ch) * pw % mod) % mod;
        pw = pw * p % mod;
    }
    hb[0] = id(b[0]), pw = p;
    for (int i = 1; i < b.size(); i++) {
        hb[i] = (hb[i - 1] + id(b[i]) * pw % mod) % mod;
        pw = pw * p % mod;
    }

    pw = 1;
    vector<int> ans;
    for (int i = 0; i < b.size() - a.size() + 1; i++) {
        int crt = hb[i + a.size() - 1];
        if (i) crt = (crt - hb[i - 1] + mod) % mod * inv(pw) % mod;
        pw = pw * p % mod;
        if (crt == ha) ans.push_back(i);
    }

    cout << ans.size() << ' ';
    for (int i = 0; i < min((int32_t) ans.size(), 1000); i++)
        cout << ans[i] << ' ';
}