Cod sursa(job #2515007)

Utilizator SoranaAureliaCatrina Sorana SoranaAurelia Data 27 decembrie 2019 16:33:40
Problema Abc2 Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.96 kb
#include <fstream>
#include <cstring>
#define LMAX 10000005
#define LLMAX 25
using namespace std;

ifstream f("abc2.in");
ofstream g("abc2.out");

struct Hash{
    long long n, m, power, hashh;
    void init(char *s, long long len){
        power = 1;
        hashh = 0;
        for(long long i=len-1; i>=0; i--){
            hashh = (hashh + (1LL*power*s[i])%m)%m;
            if(i) power = (power*n)%m;
        }
    }
   void roll(char toRemove, char toAdd)
    {
        hashh=(((hashh-(1LL*toRemove*power)%m+m)*n)%m+toAdd)%m;
    }
};
char s[LMAX];
int n;
char cuv[LLMAX];
int m;

int nr=0;

int fr1[40105];
int fr2[319997];

long long rollings1[LMAX];
long long rollings2[LMAX];
int main()
{
    f.getline(s, LMAX);
    n=strlen(s);

    Hash s1pHash{31, 40099}, s2pHash{31, 40099};
    Hash s1oHash{53, 319993}, s2oHash{53, 319993};

    f.getline(cuv, LLMAX);
    m=strlen(cuv);
    s1pHash.init(s, m);
    s1oHash.init(s, m);
    s2pHash.init(cuv, m);
    s2oHash.init(cuv, m);

    fr1[s2pHash.hashh] = 1;
    fr2[s2oHash.hashh] = 1;

    int k=0;
    rollings1[k]=s1pHash.hashh;
    rollings2[k++]=s1oHash.hashh;

    if(rollings1[0] == s2pHash.hashh && rollings2[0] == s2oHash.hashh)
        nr++;

    for(long long i=m; i<n; i++){
        s1pHash.roll(s[i-m], s[i]);
        s1oHash.roll(s[i-m], s[i]);
        rollings1[k]=s1pHash.hashh;
        rollings2[k++]=s1oHash.hashh;
        if(rollings1[k-1] == s2pHash.hashh && rollings2[k-1] == s2oHash.hashh)
            nr++;
    }

    while(f.getline(cuv, LLMAX)){
        s2pHash.init(cuv, m);
        s2oHash.init(cuv, m);
        if(fr1[s2pHash.hashh] == 1 && fr2[s2oHash.hashh]==1)
            continue;
        fr1[s2pHash.hashh] = 1;
        fr2[s2oHash.hashh] = 1;
        for(long long i=0; i<k; i++){
            if(rollings1[i] == s2pHash.hashh && rollings2[i] == s2oHash.hashh)
                nr++;
        }
    }
    g<<nr;
    return 0;
}