Pagini recente » Cod sursa (job #2589788) | Profil gheorghelupu17 | Cod sursa (job #1585563) | Cod sursa (job #1587339) | Cod sursa (job #796837)
Cod sursa(job #796837)
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
const int hash_base = 47;
int init_hash(string s) {
int hash = 0;
int base = 1;
for(int i = s.length()-1; i >= 0; i--) {
hash += base * (int)s[i];
base *= hash_base;
}
return hash;
}
int roll_hash(int oldv, int hash, int newv, int exp) {
hash -= oldv*pow(hash_base, exp-1);
hash *= hash_base;
hash += newv;
return hash;
}
int main() {
string A, B;
ifstream in("strmatch.in");
in >> A >> B;
in.close();
vector<int> poz;
int nr_matches = 0;
int N = B.length();
int M = A.length();
int a_hash = init_hash(A);
int sub_hash = init_hash(B.substr(0, M));
for(int i = 0; i < N - M + 1; i++) {
if(a_hash == sub_hash)
if(B.compare(i, M, A) == 0) {
nr_matches++;
if(nr_matches <= 1000)
poz.push_back(i);
}
sub_hash = roll_hash((int)B[i], sub_hash, (int)B[i+M], M);
}
ofstream out("strmatch.out");
out << nr_matches << endl;
for(int i = 0; i < poz.size(); i++)
out << poz[i] << " ";
out.close();
return 0;
}