Cod sursa(job #3176887)

Utilizator paull122Paul Ion paull122 Data 27 noiembrie 2023 22:59:57
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <bits/stdc++.h>

using namespace std;
typedef long long int ll;
#define MOD 666013
#define VMAX 200000
#define HBASE1 128
#define HBASE2 243
#define HSIZE1 666013
#define HSIZE2 1000007

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




int gethash(char *s,int len,int base,int hsize)
{
    int hval=0;
    for(int i=0;i<len;i++)
    {
        hval = (hval * base + s[i])%hsize;
    }
    return hval;
}

bool cmp(char *a , char *b)
{
    int i=0;
    while(i<strlen(a) && a[i]==b[i])
    {
        i++;
    }
    return i==strlen(a);
}

int addhash(int val,char c,int base,int hsize)
{
    val = (val * base + c)%hsize;
    return val;
}
int removehash(int val,char c,int put,int hsize)
{
    val -= c*put %hsize;
    if(val < 0)
    {
        val += hsize;
    }
    return val;
}
char a[2000001];
char b[2000001];
int main()
{
    fin >> a >> b;
    vector<int> r;
    int len = strlen(a);
    int put1=1,put2=1;
    for(int i=1;i<=len-1;i++)
    {
        put1=put1 * HBASE1 % HSIZE1;
        put2=put2 * HBASE2 % HSIZE2;
    }

    int pathash1 = gethash(a,len,HBASE1,HSIZE1);
    int pathash2 = gethash(a,len,HBASE2,HSIZE2);

    int currhash1 = gethash(b,len-1,HBASE1,HSIZE1);
    int currhash2 = gethash(b,len-1,HBASE2,HSIZE2);

    for(int i=len-1;i<strlen(b);i++)
    {
        currhash1 = addhash(currhash1,b[i],HBASE1,HSIZE1);
        currhash2 = addhash(currhash2,b[i],HBASE2,HSIZE2);

        if(currhash1==pathash1 && currhash2==pathash2)
        {
            r.push_back(i-len+1);
        }
        currhash1 = removehash(currhash1,b[i-len+1],put1,HSIZE1);
        currhash2 = removehash(currhash2,b[i-len+1],put2,HSIZE2);
    }
    int n=r.size();
    fout << n << "\n";
    for(int i=0;i<min(n,1000);i++)
    {
        fout << r[i] << " ";
    }
}