Cod sursa(job #2086138)

Utilizator serban_ioan97Ciofu Serban serban_ioan97 Data 11 decembrie 2017 16:02:16
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>

using namespace std;

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

const int d = 127;
const int NMAX = 2000000;

int n, m;
char P[NMAX + 1];
char T[NMAX + 1];
vector <int> sol;

unsigned long long get_hash(int n, char *s) {
    unsigned long long h = 0;
    for (int i = 0; i < n; i++) {
        h = h * d + s[i];
    }
    return h;
}

void rk() {
    unsigned long long h = get_hash(m, P);
    unsigned long long current_h = get_hash(m, T);

    unsigned long long x = 1;

    for (int i = 1; i < m; i++) {
        x = x * d;
    }

    if (current_h == h) {
        sol.push_back(0);
    }

    for (int i = m; i < n; i++) {
        current_h -= x * T[i - m];
        current_h = current_h * d + T[i];

        if (current_h == h)  {
            sol.push_back(i - m + 1);
        }
    }
}

int main() {
    f >> P >> T;
    m = strlen(P);
    n = strlen(T);

    rk();

    int k = sol.size();

    g << k << '\n';
    k = min(k, 1000);
    for (int i = 0; i < k; i++)
        g << sol[i] << ' ';
    g << '\n';
    return 0;
}