Cod sursa(job #1671804)

Utilizator MciprianMMciprianM MciprianM Data 2 aprilie 2016 10:52:12
Problema Potrivirea sirurilor Scor 16
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 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 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;
    for(int i = 0; i < P.length(); i++)
    {
        pHash = (pHash * BASE + P[i]) % MOD;
        tHash = (tHash * BASE + T[i]) % MOD;
        coef = (coef * BASE) % MOD;
    }
    if(pHash == tHash)
    {
        res.push_back(0);
    }
    for(int i = P.length(); i < T.length(); i++)
    {
        tHash = (tHash * BASE + T[i] - coef * T[i - P.length()]) % MOD;
        if(tHash == pHash)
        {
            res.push_back(i - P.length() + 1);
        }
        if(res.size() == 1000)
        {
            break;
        }
    }
    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++)
    {
        g << ans[i] << ' ';
    }
    g.close();
    return 0;
}