Cod sursa(job #2942330)

Utilizator patrickunudoiBeres Patrick Stefan patrickunudoi Data 19 noiembrie 2022 16:10:45
Problema Potrivirea sirurilor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <string>
#include <vector>
#include <ifstream>
using namespace std;
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
const long long A=9679;
const long long B=2743493;
string s1,s2;
int h1;
vector<long long> h2,pA,indici;
// s2 == "ABCD", i=1, j=2 returns BC
long long substr_hash(int i,int j)
{
    if(i==0)
        return h2[j];
    long long hash =(h2[j]-(h2[i-1]*pA[j-i+1])%B)%B;
    if(hash<0)hash = hash + B;
    return hash;
}

int main()
{
    fin>>s1>>s2;
    for(char c : s1)
    {
        h1=(h1 * A + c)%B;
    }
    long long h2_temp = 0, pA_temp = 1;

    for(char c : s2)
    {
        h2_temp=(h2_temp * A + c)% B;
        h2.push_back(h2_temp);
        pA.push_back(pA_temp);
        pA_temp = (pA_temp * A) %B;
    }
    pA.push_back(pA_temp);

    for (int i = 0; i<= s2.size() - s1.size(); ++i)
    {
        int j = i+s1.size()-1;
        if(h1 == substr_hash(i,j))
            indici.push_back(i);
    }
    fout <<indici.size() << '\n';
    for(int i=0;i<indici.size() && i<1000;i++)
        fout<<indici[i]<<' ';
    return 0;
}