Cod sursa(job #2168737)

Utilizator NicuBaciuNicu Baciu NicuBaciu Data 14 martie 2018 12:06:33
Problema Potrivirea sirurilor Scor 18
Compilator cpp Status done
Runda Arhiva educationala Marime 1.93 kb
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
#include <cmath>

using namespace std;

#define prime 3

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

string pattern;
string text;

int nrmatch=0;
vector <int> res;

int gen_hash(string s)
{
    int hash0=0;

    for(int i=0; i<s.size(); i++)
        hash0+=(s[i]-'A'+1)*pow(prime, i);

    return hash0;
}

int gen_hash_recurs(int hprev, int pos)
{
    int newhash=hprev;

    newhash-=text[pos-1]-'A'+1;

    newhash/=prime;

    newhash+=(text[pos+pattern.size()-1]-'A'+1)*pow(prime, pattern.size()-1);

    return newhash;
}

int main()
{
    getline(fin, pattern);
    getline(fin, text);

    int hpattern=gen_hash(pattern);
    int firsthash=0;

    for(int i=0; i<pattern.size(); i++)
        firsthash+=(text[i]-'A'+1)*pow(prime, i);

    if(firsthash==hpattern)
    {
        bool sem=false;

        for(int i=0; i<pattern.size() && !sem; i++)
        {
            if(text[i]!=pattern[i])
                sem=true;
        }

        if(sem==false)
        {
            nrmatch++;
            res.push_back(0);
        }
    }

    int hprev=firsthash;
    int limit;


    if(text.size()-pattern.size()>1000)
        limit=1000;
    else
        limit=text.size()-pattern.size();

    for(int i=1; i<=limit; i++)
    {
        int newhash=gen_hash_recurs(hprev, i);

        if(newhash==hpattern)
        {
            bool sem=false;

            for(int j=i; j<i+pattern.size() && !sem; j++)
            {
                if(text[j]!=pattern[j-i])
                    sem=true;
            }

            if(sem==false)
            {
                nrmatch++;
                res.push_back(i);
            }
        }

        hprev=newhash;
    }

    fout << nrmatch << '\n';

    for(int i=0; i<res.size(); i++)
        fout << res[i] << " ";

    return 0;
}