Cod sursa(job #2823598)

Utilizator matei.tudoseMatei Tudose matei.tudose Data 28 decembrie 2021 23:18:29
Problema Potrivirea sirurilor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <fstream>
#include <vector>
using namespace std;

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

const int mod1 = 651097, mod2 = 699401;
int base = 97, sol;
string A, B;
int rasp[2000001];

int get_hash(int modulo, int baza, string cuv)
{
    long long int hash = 0, contor = 1;
    for (int i = cuv.size() - 1; i >= 0; i--)
    {
        int ascii = (int)cuv[i];
        hash += (ascii * contor);
        hash %= modulo;
        contor *= baza;
        contor %= modulo;
    }
    return hash;
}

int main()
{
    fin >> A >> B;
    // Get the number of occurences of A in B using rolling hash
    int n = A.size(), m = B.size();
    string cuv_it = B.substr(0, n);
    int h1_A = get_hash(mod1, base, A), h2_A = get_hash(mod2, base, A);
    int h1_cuv_it = get_hash(mod1, base, cuv_it), h2_cuv_it = get_hash(mod2, base, cuv_it);
    // Calculate a "put1" and "put2" variable for the rolling hash
    int put1 = 1, put2 = 1;
    for (int i = 1; i <= n; i++)
    {
        put1 *= base;
        put1 %= mod1;
        put2 *= base;
        put2 %= mod2;
    }
    for (int i = 0; i < m - n + 1; i++)
    {
        if (h1_A == h1_cuv_it && h2_A == h2_cuv_it)
        {
            sol++;
            if (sol <= 1000)
                rasp[i] = 1;
        }
        // Remove the value of the first character of cuv_it and add the next character in B
        h1_cuv_it = (h1_cuv_it * base + (int)B[i + n]) % mod1;
        h2_cuv_it = (h2_cuv_it * base + (int)B[i + n]) % mod2;
        // Remove the first character of cuv_it and add the last character in B
        h1_cuv_it = (h1_cuv_it - (int)B[i] * put1) % mod1;
        h2_cuv_it = (h2_cuv_it - (int)B[i] * put2) % mod2;
        if (h1_cuv_it < 0)
            h1_cuv_it += mod1;
        if (h2_cuv_it < 0)
            h2_cuv_it += mod2;
    }
    fout << sol << "\n";
    sol = 0;
    for (int i = 0; i < 2000001, sol < 1000; i++)
    {
        if (rasp[i] == 1)
        {
            sol++;
            fout << i << " ";
        }
    }
    fout << "\n";
    return 0;
}