Cod sursa(job #1428869)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 5 mai 2015 11:00:11
Problema Potrivirea sirurilor Scor 14
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <bits/stdc++.h>

using namespace std;

const int BASE = 73;

template <const int MOD>
struct RollingHash
{
    int length;
    int code;
    int base;

    RollingHash(const int lg = 0) : length(lg), code(0), base(1) {

        for (int i = 1; i < lg; ++i)
            base = (base * BASE) % MOD;
    }

    void pop_front(const char ch)
    {
        code = (code -  (base * ch) % MOD + MOD) % MOD;
    }

    void push_back(const char ch)
    {
        code = (code * BASE) % MOD;
        code = (code + ch) % MOD;
    }

    bool operator == (const RollingHash& R) const
    {
        return this->code == R.code;
    }

    bool operator != (const RollingHash& R) const
    {
        return this->code != R.code;
    }
};

const int Nmax = 2000000 + 1;

char A[Nmax], B[Nmax];
int N, M;

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

    in >> A >> B;
    N = strlen(A);
    M = strlen(B);

    RollingHash<666013> A1(N);
    RollingHash<100007> A2(N);
    RollingHash<666013> B1(N);
    RollingHash<100007> B2(N);

    if (N > M)
    {
        out << "0\n";
        return 0;
    }

    for (int i = 0; i < N; ++i)
    {
        A1.push_back(A[i]);
        A2.push_back(A[i]);

        B1.push_back(B[i]);
        B2.push_back(B[i]);
    }

    vector<int> sol;

    if (A1 == B1 && A2 == B2)
        sol.push_back(0);

    for (int i = N; i < M; ++i)
    {
        B1.pop_front(B[i - N]);
        B2.pop_front(B[i - N]);

        B1.push_back(B[i]);
        B2.push_back(B[i]);

        if (A1 == B1 && A2 == B2)
            sol.push_back(i - N + 1);
    }

    cout << sol.size() << "\n";

    for (int i = 0; i < min(1000, (int)sol.size()); ++i)
        cout << sol[i] << " ";

    cout << "\n";

    return 0;
}