Cod sursa(job #3231371)

Utilizator AlexPlesescuAlexPlesescu AlexPlesescu Data 26 mai 2024 11:00:51
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <bits/stdc++.h>

using namespace std;
#define int long long int
const int mod = 2000000011, p = 9973, N = 2e6 + 5;

string a, b;
int hash1[N], hash2[N], pw[N], n, m;

int lgput(int a, int n) {
    if (!n)
        return 1;
    else {
        if (n % 2)
            return a * lgput(a, n - 1) % mod;
        else {
            int c = lgput(a, n / 2);
            return c * c % mod;
        }
    }
}

int inv_mod(int a) {
    return lgput(a, mod - 2);
}

int cod(char c) {
    if (islower(c)) {
        return c - 'a' + 1;
    } else {
        return c - 'A' + 27;
    }
}

int get_hash(int l, int r) {
    int aux = hash2[r] - hash2[l - 1] + mod;
    aux %= mod;
    return aux * inv_mod(pw[l - 1]) % mod;
}

signed main()
{
    freopen("strmatch.in", "r", stdin);
    freopen("strmatch.out", "w", stdout);
    cin.tie(nullptr)->sync_with_stdio(0);
    cin >> a >> b;
    n = a.size(); m = b.size();
    pw[0] = 1;
    for (int i = 1; i <= n + m; i++)
        pw[i] = pw[i - 1] * p % mod;
    for (int i = 1; i <= n; i++) {
        int aux = hash1[i - 1] + a[i - 1] * pw[i - 1];
        aux %= mod;
        hash1[i] = aux;
    }
    for (int i = 1; i <= m; i++) {
        int aux = hash2[i - 1] + b[i - 1] * pw[i - 1];
        aux %= mod;
        hash2[i] = aux;
    }
    vector<int> ans;
    int cnt = 0;
    for (int i = 1; i <= m - n + 1; i++) {
        if (cnt < 1000 && get_hash(i, i + n - 1) == hash1[n]) {
            ans.emplace_back(i - 1);
            cnt++;
        }
        else if (cnt > 1000)
            break;
    }
    cout << cnt << '\n';
    for (auto it : ans)
        cout << it << ' ';


    return 0;
}