Cod sursa(job #1987273)

Utilizator MaligMamaliga cu smantana Malig Data 30 mai 2017 08:34:15
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stack>
#include <cstring>

using namespace std;
ifstream in("strmatch.in");
ofstream out("strmatch.out");

#define ll long long
#define pb push_back
const int strMax = 1e6 + 5;
const ll inf = 9e18 + 5;
#define mod1 100002
#define mod2 100001
#define base 73

int N,M,nrSol;
char str[strMax],patt[strMax];
int sol[strMax];

int main() {
    in>>(patt+1)>>(str+1);
    N = strlen(patt+1);
    M = strlen(str+1);

    int pattHash1 = 0,pattHash2 = 0,strHash1 = 0,strHash2 = 0;
    int pw1 = 1,pw2 = 1;

    for (int i=1;i <= N;++i) {
        pattHash1 = (pattHash1 * base + patt[i] * base) % mod1;
        pattHash2 = (pattHash2 * base + patt[i] * base) % mod2;

        strHash1 = (strHash1 * base + str[i] * base) % mod1;
        strHash2 = (strHash2 * base + str[i] * base) % mod2;

        pw1 = (pw1 * base) % mod1;
        pw2 = (pw2 * base) % mod2;
    }

    if (strHash1 == pattHash1 && strHash2 == pattHash2) {
        sol[++nrSol] = 0;
    }

    for (int i=N+1;i <= M;++i) {
        strHash1 = ((strHash1 - (str[i-N] * pw1) % mod1 + mod1) * base + str[i] * base) % mod1;
        strHash2 = ((strHash2 - (str[i-N] * pw2) % mod2 + mod2) * base + str[i] * base) % mod2;

        if (strHash1 == pattHash1 && strHash2 == pattHash2) {
            sol[++nrSol] = i-N;
        }
    }

    out<<nrSol<<'\n';
    nrSol = min(nrSol,1000);
    for (int i=1;i <= nrSol;++i) {
        out<<sol[i]<<' ';
    }
    out<<'\n';


    in.close();out.close();
    return 0;
}