Pagini recente » Cod sursa (job #1081005) | Cod sursa (job #422989) | Cod sursa (job #2209387) | Cod sursa (job #1399520) | Cod sursa (job #1834122)
#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=66013;
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()+1);
}
}
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");
out<<sol.size()<<'\n';
for(int i=0;i<std::min(1000,(int)sol.size());i++)
out<<sol[i]<<' ';
//std::cout<<sol[i]<<' ';
return 0;
}