Pagini recente » Cod sursa (job #1738858) | Cod sursa (job #2246154) | Cod sursa (job #2445064) | Cod sursa (job #813741) | Cod sursa (job #2168752)
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
#include <cmath>
using namespace std;
#define prime 3
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
string pattern;
string text;
int nrmatch=0;
vector <int> res;
int gen_hash(string s)
{
int hash0=0;
for(int i=0; i<s.size(); i++)
hash0+=(s[i]-'A'+1)*pow(prime, i);
return hash0;
}
int gen_hash_recurs(int hprev, int pos)
{
int newhash=hprev;
newhash-=text[pos-1]-'A'+1;
newhash/=prime;
newhash+=(text[pos+pattern.size()-1]-'A'+1)*pow(prime, pattern.size()-1);
return newhash;
}
int main()
{
getline(fin, pattern);
getline(fin, text);
int hpattern=gen_hash(pattern);
int firsthash=0;
for(int i=0; i<pattern.size(); i++)
firsthash+=(text[i]-'A'+1)*pow(prime, i);
if(firsthash==hpattern)
{
bool sem=false;
for(int i=0; i<pattern.size() && !sem; i++)
{
if(text[i]!=pattern[i])
sem=true;
}
if(sem==false)
{
nrmatch++;
res.push_back(0);
}
}
int hprev=firsthash;
int limit;
limit=text.size()-pattern.size();
for(int i=1; i<=limit; i++)
{
int newhash=gen_hash_recurs(hprev, i);
if(newhash==hpattern)
{
bool sem=false;
for(int j=i; j<i+pattern.size() && !sem; j++)
{
if(text[j]!=pattern[j-i])
sem=true;
}
if(sem==false)
{
nrmatch++;
res.push_back(i);
if(nrmatch==1000)
break;
}
}
hprev=newhash;
}
fout << nrmatch << '\n';
for(int i=0; i<res.size(); i++)
fout << res[i] << " ";
return 0;
}