Cod sursa(job #2985037)

Utilizator pifaDumitru Andrei Denis pifa Data 25 februarie 2023 15:58:20
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>
#define HASH1 256
#define HASH2 300
#define MOD1 666013
#define MOD2 777013

using namespace std;

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

const int N = 2000005;

char v[N], s[N];

int fastpow(int base, int exp, int mod)
{
    int prod = 1;
    while(exp)
    {
        if(exp&1)
            prod = (long long)prod * base % mod;
        base = (long long)base * base % mod;
        exp /= 2;
    }
    return prod;
}

int adauga_hash(int x, char ch, int hsh, int mod)
{
    return ((long long) x * hsh + ch) % mod;
}

int scoate_hash(int x, char ch, int putere, int mod)
{
    x = x - (long long)ch * putere % mod;
    if(x < 0)
      x = x + mod;
    return x;
}

int rez[N];

int cnt;

int main()
{
    in.getline(v, N);
    in.getline(s, N);
    int n = strlen(v);
    int m = strlen(s);
    int put1 = fastpow(HASH1, n - 1, MOD1);
    int put2 = fastpow(HASH2, n - 1, MOD2);
    int h1v = 0, h2v = 0, h1s = 0, h2s = 0;
    for(int i = 0; i < n; i++)
    {
        h1v = adauga_hash(h1v, v[i], HASH1, MOD1);
        h2v = adauga_hash(h2v, v[i], HASH2, MOD2);
    }
    for (int i = 0; i < n - 1; i++)
    {
        h1s = adauga_hash(h1s, s[i], HASH1, MOD1);
        h2s = adauga_hash(h2s, s[i], HASH2, MOD2);
    }
    int i = n;
    while(i <= m)
    {
        h1s = adauga_hash(h1s, s[i - 1], HASH1, MOD1);
        h2s = adauga_hash(h2s, s[i - 1], HASH2, MOD2);
        if(h1v == h1s && h2v == h2s)
        {
            rez[++cnt] = i - n;
        }
        h1s = scoate_hash(h1s, s[i - n], put1, MOD1);
        h2s = scoate_hash(h2s, s[i - n], put2, MOD2);
        i++;
    }
    out << cnt << '\n';
    for(int i = 1; i <= min(cnt, 1000); i++)
        out << rez[i] << ' ';
    return 0;
}