Cod sursa(job #1784421)

Utilizator OleaginoasaCristina Oleaginoasa Data 20 octombrie 2016 00:10:53
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;

#define MOD 666013;

void strmatch(string A, string B){
    vector<int> v;
    int count = 0;
    int p = 26, p1 = 1;
    
    int hashA = 0, hashB = 0;
    int sizeA = A.size(), sizeB = B.size();
    
    for(int i = 0; i < sizeA; ++i){
        hashA = (hashA * p + A[i]) % MOD;
        hashB = (hashB * p + B[i]) % MOD;
        
        if(i != 0){
            p1 = (p1 * p) % MOD;
        }
    }
    
    if(hashA == hashB){
        v.push_back(0);
        count++;
    }
    
    for(int i = sizeA; i < sizeB; ++i){
        hashB = ((hashB - B[i-sizeA] * p1) * p + B[i]) % MOD;
        if (hashB < 0) {
            hashB += MOD;
        }
        
        if(hashB == hashA){
            v.push_back(i-sizeA+1);
            count++;
        }
    }
    
    cout << count << endl;
    int minSize = min((int)v.size(), 1000);
    for(int i = 0; i < minSize; ++i)
        cout << v[i] << " ";
}

int main(){
    freopen("strmatch.in", "r", stdin);
    freopen("strmatch.out","w", stdout);
    string A, B;
    cin >> A >> B;
    strmatch(A, B);
    
    return 0;
}