Cod sursa(job #2791114)

Utilizator domistnSatnoianu Dominic Ioan domistn Data 30 octombrie 2021 09:31:21
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

typedef long long ll;

const int NMAX = 2000003;

int sl, micutl, ans[1001], ansl;
char s[NMAX + 1], micut[NMAX + 1];

class Hash {
    private:
        ll n = 3301, m = 666013, power = 0, value = 0;
    public:
        Hash() {
            power = value = 0;
        }

        void init(const char * X, const int XL, const int M) {
            m = M;
            power = 1;
            value = 0;
            for(int i = XL; i; --i) {
                value = (value + power * X[i] % m) % m;
                if(i - 1) power = power * n % m;
            }
        }

        void roll(const char toRem, const char toAdd) {
            value = (((value - (1ll * toRem * power) % m + m) * n) % m + toAdd) % m;
        }

        bool operator==(const Hash &X) const {
            return value == X.value;
        }
};

int main()
{
    freopen("strmatch.in", "r", stdin);
    freopen("strmatch.out", "w", stdout);
    scanf("%s %s", micut + 1, s + 1);
    micutl = strlen(micut + 1), sl = strlen(s + 1);
    Hash mh1, mh2, sh1, sh2;
    mh1.init(micut, micutl, 123457);
    mh2.init(micut, micutl, 666013);
    sh1.init(s, micutl, 123457);
    sh2.init(s, micutl, 666013);

    for(int i = micutl; i <= sl; ++i) {
        if(sh1 == mh1 && sh2 == mh2) {
            ++ansl;
            if(ansl <= 1000) ans[ansl] = i - micutl;
        }
        if(i < sl)
            sh1.roll(s[i - micutl + 1], s[i + 1]),
            sh2.roll(s[i - micutl + 1], s[i + 1]);
    }
    printf("%d\n", ansl);
    ansl = min(ansl, 1000);
    for(int i = 1; i <= ansl; ++i) {
        printf("%d ", ans[i]);
    }
    return 0;
}