Pagini recente » Cod sursa (job #3182809) | Rating Florea Mihai Florin (florea.florin) | Cod sursa (job #1212220) | Cod sursa (job #1681991) | Cod sursa (job #1199595)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class ZAlgorithm{
public:
ZAlgorithm(){}
ZAlgorithm(const string& text){
//cout << text << "\n";
this->makeZValues(text, this->zValues);
}
vector<int> getZValues(){
return this->zValues;
}
private:
vector<int> zValues;
static int compara(const int &x,const int &y, const string &S){
int cnt = 0;
for(int i=x, j=y; j<(int)S.size(); ++i, ++j){
if(S[i] != S[j]) return cnt;
++cnt;
}
return cnt;
}
static void makeZValues(const string &S, vector<int> &z){
z.assign((int)S.size(), 0);
z[0] = S.size();
int L = -1; int R = -1;
for(int i=1; i<S.size(); ++i){
if (i > R){
z[i] = compara(0, i, S);
if (z[i] != 0){
L = i; R = i + z[i]- 1;
}
}else {
int lungA = R - L + 1; int lungB = R - i + 1;
int R2 = 0 + lungA - 1; int i2 = R2 - lungB + 1;
if (z[i2] < lungB){
z[i] = z[i2]; continue;
}
z[i] = lungB + compara(lungB, R+1, S);
if (i + z[i]-1 > R){
L = i; R = i + z[i] - 1;
}
}
}
}
};
int main(){
ifstream f("strmatch.in");
string text, pattern;
getline(f, pattern);
getline(f, text);
string S = pattern + text;
ZAlgorithm *X = new ZAlgorithm(S);
vector<int> z = X->getZValues();
vector<int> ans;
for(int i=(int)pattern.size(); i<S.size(); ++i){
if (z[i] >= pattern.size()){
ans.push_back(i-(int)pattern.size());
if ((int)ans.size() == 1000) break;
}
}
f.close();
ofstream g("strmatch.out");
g << ans.size() << "\n";
for(int i=0; i<(int)ans.size(); ++i){
g << ans[i] << " ";
}
g.close();
}