Cod sursa(job #2874998)

Utilizator RobertuRobert Udrea Robertu Data 20 martie 2022 17:07:18
Problema Potrivirea sirurilor Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
/*
    Rezolvare problemei Strmatch folosinf algoritmul Rabin-Karp
    adaptat la litere mari si cifre
*/

#include <bits/stdc++.h>
#include <string>
#define prime 101
using namespace std;

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

int firstHash(string text);

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int cnt = 0;
    vector<int> potriviri;
    string text, pattern;
    fin >> pattern >> text;

    int i, j;
    int n = pattern.length(), m = text.length();
    int hash = firstHash(pattern);

    string firstWindow = text.substr(0, n);
    int windowHash = firstHash(firstWindow);

    int h = 1;
    for(int i = 0; i < n - 1; i++)
        h = (h * 256) % prime;

    for(i = 0; i <= m - n; i++) {
        if( hash == windowHash ) {
            for(j = 0; j < n; j++)
                if( pattern[j] != text[i + j] )
                    break;

            if( j == n ) {
                if( cnt <= 1000 ) 
                    potriviri.push_back(i);
                cnt++;
            }
        }

        if( i < m - n ) {
            windowHash = (256*(windowHash - text[i]*h) + text[i + n]) % prime;

            if(windowHash < 0)
                windowHash += prime;
        }
    }

    fout << cnt << '\n';
 
    for(i = 0; i < min(1000, cnt); i++)
        fout << potriviri[i] << " ";

    return 0;
}

int firstHash(string text) {
    int hash = 0;
    int n = text.length();

    for(int i = 0; i < n; i++)
        hash = (256 * hash + text[i]) % prime; 

    return hash;
}