Cod sursa(job #1382658)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 9 martie 2015 13:15:48
Problema Potrivirea sirurilor Scor 78
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>

using namespace std;

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

const int maxn = 2000005;
const int mod1 = 1000000007;
const int base = 73;

char a[maxn], b[maxn];
int n, m;
int pattern_hash1, patther_hash2;
int text_hash1, text_hash2;

int main() {
    fin.getline(a + 1, maxn);
    fin.getline(b + 1, maxn);

    n = strlen(a + 1);
    m = strlen(b + 1);

    if(n > m) {
        fout << "0\n";
        return 0;
    }

    for(int i = 1 ; i <= n ; ++ i) {
        pattern_hash1 = (1LL * pattern_hash1 * base + a[i]) % mod1;
        cerr << pattern_hash1 << ' ';
    }
    int power = 1;
    for(int i = 1 ; i <= n ; ++ i) {
        text_hash1 = (1LL * text_hash1 * base + b[i]) % mod1;
        power = (1LL * power * base) % mod1;
    }
    vector <int> matches;
    for(int i = n + 1 ; i <= m ; ++ i) {
        text_hash1 = (1LL * text_hash1 * base + b[i]) % mod1;
        text_hash1 = (1LL * text_hash1 - (1LL * power * (b[i - n])) % mod1 + mod1) % mod1;
        if(pattern_hash1 == text_hash1)
            matches.push_back(i - n);
    }
    fout << matches.size() << '\n';
    for(int i = 0 ; i < min((int)(1000), (int)(matches.size())) ; ++ i)
        fout << matches[i] << ' ';
}