Pagini recente » Cod sursa (job #2262671) | Cod sursa (job #1190092) | Cod sursa (job #409924) | Cod sursa (job #1209848) | Cod sursa (job #1834110)
#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;
}