Cod sursa(job #1933801)

Utilizator serbanSlincu Serban serban Data 20 martie 2017 22:31:54
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <bits/stdc++.h>

using namespace std;

const int mod1 = 87407;
const int mod2 = 87403;
const int wut = 130;
long long h1, h2;
long long a1, a2;

vector<int> ret;

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

    string A; f >> A;
    int n = A.size();

    string B; f >> B;
    int m = B.size();

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

    long long p1 = 1, p2 = 1;
    h1 = A[0];
    h2 = A[0];

    for(int i = 1; i < n; i ++) {
        p1 *= wut; p1 %= mod1;
        p2 *= wut; p2 %= mod2;
        h1 = (h1 * wut + A[i]) % mod1;
        h2 = (h2 * wut + A[i]) % mod2;
    }

    a1 = B[0];
    a2 = B[0];
    for(int i = 1; i < n; i ++) {
        a1 = (a1 * wut + B[i]) % mod1;
        a2 = (a2 * wut + B[i]) % mod2;
    }

    if(a1 == h1 && a2 == h2) {
        ret.push_back(0);
    }

    for(int i = n; i < m; i ++) {

        a1 = (a1 - (B[i - n] * p1) % mod1 + mod1) % mod1;
        a2 = (a2 - (B[i - n] * p2) % mod2 + mod2) % mod2;

        a1 = (a1 * wut + B[i]) % mod1;
        a2 = (a2 * wut + B[i]) % mod2;

        if(a1 == h1 && a2 == h2) {
            ret.push_back(i - n + 1);
        }
    }
    int l = min(1000, (int)ret.size());
    g << l << "\n";

    for(int i = 0; i < l; i ++) g << ret[i] << " ";
    g << "\n";
    return 0;
}