Cod sursa(job #1834110)

Utilizator bogdanboboc97Bogdan Boboc bogdanboboc97 Data 23 decembrie 2016 21:40:57
Problema Potrivirea sirurilor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

bool naiveComp(std::string haystack, std::string needle, int startPos)
{
    for(int i=startPos;i<(int)needle.size()+startPos;i++)
    {
        if(haystack[i]!=needle[i-startPos])
            return false;
    }
    return true;
}

std::vector<int> rabin_karp(std::string haystack, std::string needle)
{
    const int prime=101,mod=666013;
    std::vector<int> sol;
    int needleCode=0,haystackCode=0,P=1;

    for(int i=(int)needle.size()-1;i>=0;i--)
    {
        needleCode=(needleCode+(P*1LL*needle[i])%mod)%mod;//hash code for needle
        haystackCode=(haystackCode+(P*1LL*haystack[i])%mod)%mod;//hash code for the first substring of the same length with needle from haystack
        if(i!=0)
            P=(P*prime)%mod;

    }

    if(haystackCode==needleCode)
    {
        if(naiveComp(haystack,needle,0)==true)
            sol.push_back(0);
    }

    for(int i=(int)needle.size();i<(int)haystack.size();i++)
    {
        haystackCode=((haystackCode-(P*1LL*haystack[i-needle.size()])%mod+mod)*1LL*prime+haystack[i])%mod;//the code for next substring
        if(haystackCode==needleCode)
        {
            if(naiveComp(haystack,needle,i-needle.size()+1)==true)
                sol.push_back(i-needle.size());
        }
    }
    return sol;
}

int main()
{
    std::string haystack,needle;
    //std::cin>>needle>>haystack;
    std::ifstream in("strmatch.in");
    in>>needle>>haystack;
    std::vector<int> sol=rabin_karp(haystack,needle);
    //std::cout<<sol.size()<<'\n';
    std::ofstream out("strmatch.out");
    for(int i=0;i<(int)sol.size();i++)
        out<<sol[i]+1<<' ';
        //std::cout<<sol[i]<<' ';
    return 0;
}