Cod sursa(job #2483449)

Utilizator XXMihaiXX969Gherghinescu Mihai Andrei XXMihaiXX969 Data 29 octombrie 2019 19:33:51
Problema Potrivirea sirurilor Scor 14
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <string.h>
#include <algorithm>

using namespace std;

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

const int DIM =  2000005;

const int cst = 1 << 31;
const int nr = 52;

char a[DIM];
char b[DIM];

int power[DIM];
int rez[DIM];

int main()
{
    /*functia hash se face cu puterile nr de litere posibile din vector in cazul acesta sunt nr de litere mici si mari din alfabet englez adica 52 */
    in >> a;
    in >> b;

    int  K = 0;
    power[0] = 1;
    int A = strlen(a);
    for(int i = 1;i <= A;i++)
    {
     power[i] = (power[i - 1] * nr )% cst;
    }
    int B = strlen(b);

    if(A > B)
    {out << 0;
    return 0;
    }

    long long S = 0;
    long long val = 0;
    for(int i = 0;i < A;i++)
    {
        val += (power[A - i - 1] * (int(a[i]) - 47)) % cst;
        S += (power[A - i - 1] *(int (b[i]) - 47)) % cst;
    }
    if(S == val)
    {K++;
    rez[K] = 0;
    }
    for(int i = 1; i <= B - A;i++)
    {
        S = ((S - power[A - 1] * (int(b[i-1]) - 47)) * nr % cst + (int(b[i + A - 1]) - 47)) % cst;
        if(S == val)
        {
            K++;
            rez[K] = i;
        }
    }
    out << K<<"\n";
    /* normal K ,in cazul asta e restrictie de 1000 de afisari*/
    for(int i = 1; i <= min(1000,K); i++)
        out << rez[i] <<" ";
    return 0;
}