Cod sursa(job #1671870)

Utilizator MciprianMMciprianM MciprianM Data 2 aprilie 2016 11:16:19
Problema Potrivirea sirurilor Scor 16
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
/* 
 * File:   main.cpp
 * Author: ex_301_05
 *
 * Created on April 2, 2016, 10:29 AM
 */

#include <vector>
#include <string>
#include<fstream>

using namespace std;

static const int MOD = 666013;
static const int MOD2 = 100021;
static const int BASE = 256;

vector<int> str_match(const string& T, const string &P)
{
    vector<int> res;
    if(T.length() < P.length())
    {
        return res;
    }
    int pHash = 0, tHash = 0, coef = 1;
    int pHash2 = 0, tHash2 = 0, coef2 = 1;
    for(int i = 0; i < P.length(); i++)
    {
        pHash = (pHash * BASE + P[i]) % MOD;
        tHash = (tHash * BASE + T[i]) % MOD;
        coef = (coef * BASE) % MOD;
        pHash2 = (pHash2 * BASE + P[i]) % MOD2;
        tHash2 = (tHash2 * BASE + T[i]) % MOD2;
        coef2 = (coef2 * BASE) % MOD2;
    }
    if(pHash2 == tHash2)
    {
        res.push_back(0);
    }
    for(int i = P.length(); i < T.length(); i++)
    {
        tHash = (tHash * BASE + T[i] - coef * T[i - P.length()] + MOD) % MOD;
        tHash2 = (tHash2 * BASE + T[i] - coef2 * T[i - P.length()] + MOD2) % MOD2;
        if(tHash2 == pHash2 && tHash == pHash)
        {
            res.push_back(i - P.length() + 1);
        }
    }
    return res;
}

int main(int argc, char** argv) {
    string P, T;
    ifstream f("strmatch.in");
    f >> P >> T;
    f.close();
    vector<int> ans = str_match(T, P);
    ofstream g("strmatch.out");
    g << ans.size() << endl;
    for(int i = 0; i < ans.size() && i < 1000; i++)
    {
        g << ans[i] << ' ';
    }
    g.close();
    return 0;
}