Cod sursa(job #2792945)

Utilizator stefandutastefandutahoria stefanduta Data 2 noiembrie 2021 15:59:13
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.58 kb
#include <fstream>
#include <cstring>
#define NMAX 2000005
#define HASH1 15
#define HASH2 34
#define HASH_SIZE1 65536
#define HASH_SIZE2 65537
using namespace std;
ifstream in ("strmatch.in");
ofstream out ("strmatch.out");

char s[NMAX], v[NMAX];
int rez[200005], n, m, i;

int calculeazahash(char s[], int lg, int hashx, int mod)
{
    int h = 0;
    i = 0;
    while (i < lg)
    {
        h = ((long long)h * hashx + s[i]) % mod;
        ++i;
    }
    return h;
}

int adauga(int h, char ch, int hashx, int mod)
{
    h = ((long long)h * hashx + ch) % mod;
    return h;
}

int scoate(int h, char ch, int put, int mod)
{
    h = h - ((long long)ch * put) % mod;
    if (h < 0)
        h = h + mod;
    return h;
}

int lgput (int a, int n, int mod)
{
    int p = 1;
    while (n > 0)
    {
        if (n % 2 == 1)
        {
            p = (long long)p * a % mod;
        }
        a = (long long)a * a % mod;
        n = n / 2;
    }
    return p;
}

bool verif(char v[], char s[])
{
    int j = 0;
    while (v[j] && s[j])
    {
        if (v[j] != s[j])
            return 0;
        ++j;
    }
    return 1;
}

bool alph(char x)
{
    return (x >= '0' && x <= '9') || (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');
}

int main()
{
    in.getline(s, NMAX);
    in.getline(v, NMAX);

    int shash1, shash2, vhash1, vhash2, puthash1, puthash2, cnt = 0;
    n = strlen(s);
    while (alph(s[n]) == 0)
        n--;
    n++;
    m = strlen(v);
    while (alph(v[m]) == 0)
        m--;
    m++;
    i = 0;

    shash1 = calculeazahash(s, n, HASH1, HASH_SIZE1);
    shash2 = calculeazahash(s, n, HASH2, HASH_SIZE2);
    vhash1 = calculeazahash(v, n - 1, HASH1, HASH_SIZE1);
    vhash2 = calculeazahash(v, n - 1, HASH2, HASH_SIZE2);
    ++i;

    puthash1 = lgput(HASH1, n - 1, HASH_SIZE1);
    puthash2 = lgput(HASH2, n - 1, HASH_SIZE2);

    while (i <= m)
    {
        vhash1 = adauga(vhash1, v[i - 1], HASH1, HASH_SIZE1);
        vhash2 = adauga(vhash2, v[i - 1], HASH2, HASH_SIZE2);
        if (vhash1 == shash1 && vhash2 == shash2)
        {
            if (verif(v + i - n, s))
            {
                ++cnt;
                rez[cnt] = i - n;
            }
        }
        //out << vhash1 << " " << vhash2 << " " << shash1 << " " << shash2 << '\n';
        vhash1 = scoate(vhash1, v[i - n], puthash1, HASH_SIZE1);
        vhash2 = scoate(vhash2, v[i - n], puthash2, HASH_SIZE2);
        ++i;
    }

    out << cnt << '\n';
    for (i = 1; i <= cnt; ++i)
        out << rez[i] << " ";

    return 0;
}