Cod sursa(job #3201343)

Utilizator EdyIordacheIordache Eduard EdyIordache Data 7 februarie 2024 17:14:50
Problema Potrivirea sirurilor Scor 86
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cstring>

using namespace std;

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

#define NMAX 2000001

char pat[NMAX], str[NMAX];
int mod1 = 100007;
int mod2 = 100021;

int match[NMAX], k = 0;
int pat_length, str_length;

void search() {
    pat_length = strlen(pat), str_length = strlen(str);

    int h1 = 1, h2 = 1;
    int d = 73;

    for (int i = 1; i < pat_length; i++) {
        h1 = (h1*d) % mod1;
        h2 = (h2*d) % mod2;
    }

    int t1 = 0, t2 = 0, p1 = 0, p2 = 0;
    for (int i = 0; i < pat_length; i++) {
        p1 = (p1*d + pat[i]) % mod1;
        p2 = (p2*d + pat[i]) % mod2;

        t1 = (t1*d + str[i]) % mod1;
        t2 = (t2*d + str[i]) % mod2;
    }

    for (int i = pat_length; i < str_length; i++) {
        if (p1 == t1 && p2 == t2) {
            match[i - pat_length] = 1, k++;
        }

        t1 = (d * (t1 - str[i - pat_length]*h1 % mod1 + mod1) + str[i]) % mod1;
        t2 = (d * (t2 - str[i - pat_length]*h2 % mod2 + mod2) + str[i]) % mod2;
    }
    if (p1 == t1 && p2 == t2) {
        match[str_length - pat_length] = 1, k++;
    }
}

int main() {
    fin>>pat>>str;
    search();
    if (pat_length > str_length) return 0;

    fout<<k<<endl;

    k = 0;
    for (int i = 0; i < str_length && k < 1000; i++) {
        if (match[i]) fout<<i<<" ", k++;
    }

    return 0;
}