Pagini recente » Cod sursa (job #3262455) | Cod sursa (job #795204) | Cod sursa (job #3136859) | Monitorul de evaluare | Cod sursa (job #2675497)
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
const int base = 20001;
const int mod = 10007;
std::vector<int> rabin_karp(const std::string& A, const std::string& B)
{
if (A.length() > B.length())
return {};
if (A.length() == B.length())
{
if (A == B)
return { 0 };
return {};
}
std::vector<int> sol;
int refHash = 0;
int currHash = 0;
for (int i = 0; i < A.length(); ++i)
{
refHash = (refHash * base + A[i]) % mod;
currHash = (currHash * base + B[i]) % mod;
}
int h = 1;
for (int i = 0; i < A.length() - 1; ++i)
{
h = (h * base) % mod;
}
for (int i = 0; i <= B.length() - A.length(); ++i)
{
if(currHash == refHash && A == B.substr(i, A.length()))
{
sol.push_back(i);
}
currHash = (((currHash - h * B[i]) * base + B[i + A.length()]) % mod + mod) % mod;
}
return std::move(sol);
}
int main()
{
std::ifstream in("strmatch.in");
std::ofstream out("strmatch.out");
std::string A, B;
in >> A >> B;
auto sol = rabin_karp(A, B);
out << sol.size() << std::endl;
for (size_t i = 0; i < std::min(sol.size(), size_t(1000)); ++i)
{
out << sol[i] << ' ';
}
return 0;
}