Pagini recente » Cod sursa (job #2497465) | Cod sursa (job #2555359) | Cod sursa (job #1489892) | Cod sursa (job #2988020) | Cod sursa (job #1834146)
//Algoritmul lui Rabin Karp
#include<fstream>
#include<vector>
#include<string>
#define P 73
#define MOD1 100007
#define MOD2 100021
using namespace std;
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
string a, b;
int i, n, m, k, j,aux,st,dr,x,y,t,poz,p1,p2,hash1,hash2,initHash1 , initHash2,contor ;
vector <int> sol;
int main()
{
fin >> a >> b;
n = a.length();
m = b.length();
//fout<<a<<" "<<b<<"\n";
p1 = p2 = 1;
initHash1 = initHash2 = 0;
//calculam functiile hash pentru sirul initial
for(i = 0; i < n; i++)
{
initHash1 = (initHash1 * P + a[i]) % MOD1;
initHash2 = (initHash2 * P + a[i]) % MOD2;
}
for(i = 0; i < n - 1; i++)
{
p1 = (p1 * P) % MOD1;
p2 = (p2 * P) % MOD2;
}
hash1 = hash2 = 0;
for(i = 0; i < n ; i++)
{
hash1 = (hash1 * P + b[i]) % MOD1;
hash2 = (hash2 * P + b[i]) % MOD2;
}
if(hash1 == initHash1 && hash2 == initHash2)
{
sol.push_back(0);
}
//eliminam elementul de pe pozitia i - n
for(i = n ; i < m; i++)
{
hash1 = ((hash1 - ((b[i - n] * p1) % MOD1) + MOD1 ) * P + b[i]) % MOD1;
hash2 = ((hash2 - ((b[i - n] * p2) % MOD2) + MOD2 ) * P + b[i]) % MOD2;
if(hash1 == initHash1 && hash2 == initHash2)
{
sol.push_back(i - n + 1);
}
}
if(sol.size() > 1000 ) contor = 1000;
else contor = sol.size();
fout << sol.size() << "\n";
for(i = 0; i < contor;i++)
{
fout << sol[i] <<" ";
}
}