Cod sursa(job #1834146)

Utilizator raulmuresanRaul Muresan raulmuresan Data 23 decembrie 2016 23:09:09
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
//Algoritmul lui Rabin Karp
#include<fstream>
#include<vector>
#include<string>
#define P 73
#define MOD1 100007
#define MOD2 100021

using namespace std;

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

string a, b;
int i, n, m, k, j,aux,st,dr,x,y,t,poz,p1,p2,hash1,hash2,initHash1 , initHash2,contor ;

vector <int> sol;


int main()
{
    fin >> a >> b;
    n = a.length();
    m = b.length();
    //fout<<a<<" "<<b<<"\n";
    p1 = p2 = 1;
    initHash1 = initHash2 = 0;
    //calculam functiile hash pentru sirul initial
    for(i = 0; i < n; i++)
    {
        initHash1 = (initHash1 * P + a[i]) % MOD1;
        initHash2 = (initHash2 * P + a[i]) % MOD2;
    }
    for(i = 0; i < n - 1; i++)
    {
        p1 = (p1 * P) % MOD1;
        p2 = (p2 * P) % MOD2;
    }
    hash1 = hash2 = 0;
    for(i = 0; i < n ; i++)
    {
        hash1 = (hash1 * P + b[i]) % MOD1;
        hash2 = (hash2 * P + b[i]) % MOD2;

    }
    if(hash1 == initHash1 && hash2 == initHash2)
    {
        sol.push_back(0);
    }
    //eliminam elementul de pe pozitia i - n
    for(i = n ; i < m; i++)
    {
        hash1 = ((hash1 - ((b[i - n] * p1) % MOD1) + MOD1 ) * P + b[i]) % MOD1;
        hash2 = ((hash2 - ((b[i - n] * p2) % MOD2) + MOD2 ) * P + b[i]) % MOD2;
        if(hash1 == initHash1 && hash2 == initHash2)
        {
            sol.push_back(i - n + 1);
        }
    }

    if(sol.size() > 1000 ) contor = 1000;
    else contor = sol.size();



    fout << sol.size() << "\n";
    for(i = 0; i < contor;i++)
    {
        fout << sol[i] <<" ";
    }

}